blob: 4576a0eab2c22dea1eaaa5af7e9a7368d60ab588 [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
Rafael Espindola90cc3902013-04-15 12:49:13 +0000943 if (!shouldLinkPossiblyHiddenDecl(*I, New))
944 continue;
945
John McCall871b2e72009-12-09 03:35:25 +0000946 Match = *I;
947 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000948 }
John McCalld7945c62010-11-10 03:01:53 +0000949 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000950 // We can overload with these, which can show up when doing
951 // redeclaration checks for UsingDecls.
952 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000953 } else if (isa<TagDecl>(OldD)) {
954 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000955 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
956 // Optimistically assume that an unresolved using decl will
957 // overload; if it doesn't, we'll have to diagnose during
958 // template instantiation.
959 } else {
John McCall68263142009-11-18 22:49:29 +0000960 // (C++ 13p1):
961 // Only function declarations can be overloaded; object and type
962 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000963 Match = *I;
964 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000965 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000966 }
John McCall68263142009-11-18 22:49:29 +0000967
John McCall871b2e72009-12-09 03:35:25 +0000968 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000969}
970
Rafael Espindola78eeba82012-12-28 14:21:58 +0000971static bool canBeOverloaded(const FunctionDecl &D) {
972 if (D.getAttr<OverloadableAttr>())
973 return true;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000974 if (D.isExternC())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000975 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000976
977 // Main cannot be overloaded (basic.start.main).
978 if (D.isMain())
979 return false;
980
Rafael Espindola78eeba82012-12-28 14:21:58 +0000981 return true;
982}
983
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000984static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
985 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000986 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
987 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
988
989 // C++ [temp.fct]p2:
990 // A function template can be overloaded with other function templates
991 // and with normal (non-template) functions.
992 if ((OldTemplate == 0) != (NewTemplate == 0))
993 return true;
994
995 // Is the function New an overload of the function Old?
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000996 QualType OldQType = S.Context.getCanonicalType(Old->getType());
997 QualType NewQType = S.Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +0000998
999 // Compare the signatures (C++ 1.3.10) of the two functions to
1000 // determine whether they are overloads. If we find any mismatch
1001 // in the signature, they are overloads.
1002
1003 // If either of these functions is a K&R-style function (no
1004 // prototype), then we consider them to have matching signatures.
1005 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1006 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1007 return false;
1008
John McCallf4c73712011-01-19 06:33:43 +00001009 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1010 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001011
1012 // The signature of a function includes the types of its
1013 // parameters (C++ 1.3.10), which includes the presence or absence
1014 // of the ellipsis; see C++ DR 357).
1015 if (OldQType != NewQType &&
1016 (OldType->getNumArgs() != NewType->getNumArgs() ||
1017 OldType->isVariadic() != NewType->isVariadic() ||
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001018 !S.FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001019 return true;
1020
1021 // C++ [temp.over.link]p4:
1022 // The signature of a function template consists of its function
1023 // signature, its return type and its template parameter list. The names
1024 // of the template parameters are significant only for establishing the
1025 // relationship between the template parameters and the rest of the
1026 // signature.
1027 //
1028 // We check the return type and template parameter lists for function
1029 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001030 //
1031 // However, we don't consider either of these when deciding whether
1032 // a member introduced by a shadow declaration is hidden.
1033 if (!UseUsingDeclRules && NewTemplate &&
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001034 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1035 OldTemplate->getTemplateParameters(),
1036 false, S.TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001037 OldType->getResultType() != NewType->getResultType()))
1038 return true;
1039
1040 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001041 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001042 //
1043 // As part of this, also check whether one of the member functions
1044 // is static, in which case they are not overloads (C++
1045 // 13.1p2). While not part of the definition of the signature,
1046 // this check is important to determine whether these functions
1047 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001048 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1049 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001050 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001051 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1052 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1053 if (!UseUsingDeclRules &&
1054 (OldMethod->getRefQualifier() == RQ_None ||
1055 NewMethod->getRefQualifier() == RQ_None)) {
1056 // C++0x [over.load]p2:
1057 // - Member function declarations with the same name and the same
1058 // parameter-type-list as well as member function template
1059 // declarations with the same name, the same parameter-type-list, and
1060 // the same template parameter lists cannot be overloaded if any of
1061 // them, but not all, have a ref-qualifier (8.3.5).
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001062 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001063 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001064 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001065 }
1066 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001067 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
Richard Smith21c8fa82013-01-14 05:37:29 +00001069 // We may not have applied the implicit const for a constexpr member
1070 // function yet (because we haven't yet resolved whether this is a static
1071 // or non-static member function). Add it now, on the assumption that this
1072 // is a redeclaration of OldMethod.
1073 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001074 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001075 NewQuals |= Qualifiers::Const;
1076 if (OldMethod->getTypeQualifiers() != NewQuals)
1077 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001078 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001079
John McCall68263142009-11-18 22:49:29 +00001080 // The signatures match; this is not an overload.
1081 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001082}
1083
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001084bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1085 bool UseUsingDeclRules) {
1086 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1087 return false;
1088
1089 // If both of the functions are extern "C", then they are not
1090 // overloads.
1091 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1092 return false;
1093
1094 return true;
1095}
1096
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001097/// \brief Checks availability of the function depending on the current
1098/// function context. Inside an unavailable function, unavailability is ignored.
1099///
1100/// \returns true if \arg FD is unavailable and current context is inside
1101/// an available function, false otherwise.
1102bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1103 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1104}
1105
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001106/// \brief Tries a user-defined conversion from From to ToType.
1107///
1108/// Produces an implicit conversion sequence for when a standard conversion
1109/// is not an option. See TryImplicitConversion for more information.
1110static ImplicitConversionSequence
1111TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1112 bool SuppressUserConversions,
1113 bool AllowExplicit,
1114 bool InOverloadResolution,
1115 bool CStyle,
1116 bool AllowObjCWritebackConversion) {
1117 ImplicitConversionSequence ICS;
1118
1119 if (SuppressUserConversions) {
1120 // We're not in the case above, so there is no conversion that
1121 // we can perform.
1122 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1123 return ICS;
1124 }
1125
1126 // Attempt user-defined conversion.
1127 OverloadCandidateSet Conversions(From->getExprLoc());
1128 OverloadingResult UserDefResult
1129 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1130 AllowExplicit);
1131
1132 if (UserDefResult == OR_Success) {
1133 ICS.setUserDefined();
1134 // C++ [over.ics.user]p4:
1135 // A conversion of an expression of class type to the same class
1136 // type is given Exact Match rank, and a conversion of an
1137 // expression of class type to a base class of that type is
1138 // given Conversion rank, in spite of the fact that a copy
1139 // constructor (i.e., a user-defined conversion function) is
1140 // called for those cases.
1141 if (CXXConstructorDecl *Constructor
1142 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1143 QualType FromCanon
1144 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1145 QualType ToCanon
1146 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1147 if (Constructor->isCopyConstructor() &&
1148 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1149 // Turn this into a "standard" conversion sequence, so that it
1150 // gets ranked with standard conversion sequences.
1151 ICS.setStandard();
1152 ICS.Standard.setAsIdentityConversion();
1153 ICS.Standard.setFromType(From->getType());
1154 ICS.Standard.setAllToTypes(ToType);
1155 ICS.Standard.CopyConstructor = Constructor;
1156 if (ToCanon != FromCanon)
1157 ICS.Standard.Second = ICK_Derived_To_Base;
1158 }
1159 }
1160
1161 // C++ [over.best.ics]p4:
1162 // However, when considering the argument of a user-defined
1163 // conversion function that is a candidate by 13.3.1.3 when
1164 // invoked for the copying of the temporary in the second step
1165 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1166 // 13.3.1.6 in all cases, only standard conversion sequences and
1167 // ellipsis conversion sequences are allowed.
1168 if (SuppressUserConversions && ICS.isUserDefined()) {
1169 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1170 }
1171 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1172 ICS.setAmbiguous();
1173 ICS.Ambiguous.setFromType(From->getType());
1174 ICS.Ambiguous.setToType(ToType);
1175 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1176 Cand != Conversions.end(); ++Cand)
1177 if (Cand->Viable)
1178 ICS.Ambiguous.addConversion(Cand->Function);
1179 } else {
1180 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1181 }
1182
1183 return ICS;
1184}
1185
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001186/// TryImplicitConversion - Attempt to perform an implicit conversion
1187/// from the given expression (Expr) to the given type (ToType). This
1188/// function returns an implicit conversion sequence that can be used
1189/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001190///
1191/// void f(float f);
1192/// void g(int i) { f(i); }
1193///
1194/// this routine would produce an implicit conversion sequence to
1195/// describe the initialization of f from i, which will be a standard
1196/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1197/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1198//
1199/// Note that this routine only determines how the conversion can be
1200/// performed; it does not actually perform the conversion. As such,
1201/// it will not produce any diagnostics if no conversion is available,
1202/// but will instead return an implicit conversion sequence of kind
1203/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001204///
1205/// If @p SuppressUserConversions, then user-defined conversions are
1206/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001207/// If @p AllowExplicit, then explicit user-defined conversions are
1208/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001209///
1210/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1211/// writeback conversion, which allows __autoreleasing id* parameters to
1212/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001213static ImplicitConversionSequence
1214TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1215 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001216 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001217 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001218 bool CStyle,
1219 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001220 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001221 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001222 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001223 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001224 return ICS;
1225 }
1226
David Blaikie4e4d0842012-03-11 07:00:24 +00001227 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001229 return ICS;
1230 }
1231
Douglas Gregor604eb652010-08-11 02:15:33 +00001232 // C++ [over.ics.user]p4:
1233 // A conversion of an expression of class type to the same class
1234 // type is given Exact Match rank, and a conversion of an
1235 // expression of class type to a base class of that type is
1236 // given Conversion rank, in spite of the fact that a copy/move
1237 // constructor (i.e., a user-defined conversion function) is
1238 // called for those cases.
1239 QualType FromType = From->getType();
1240 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001241 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1242 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001243 ICS.setStandard();
1244 ICS.Standard.setAsIdentityConversion();
1245 ICS.Standard.setFromType(FromType);
1246 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001247
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001248 // We don't actually check at this point whether there is a valid
1249 // copy/move constructor, since overloading just assumes that it
1250 // exists. When we actually perform initialization, we'll find the
1251 // appropriate constructor to copy the returned object, if needed.
1252 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001253
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001254 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001255 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001256 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001257
Douglas Gregor604eb652010-08-11 02:15:33 +00001258 return ICS;
1259 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001260
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001261 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1262 AllowExplicit, InOverloadResolution, CStyle,
1263 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001264}
1265
John McCallf85e1932011-06-15 23:02:42 +00001266ImplicitConversionSequence
1267Sema::TryImplicitConversion(Expr *From, QualType ToType,
1268 bool SuppressUserConversions,
1269 bool AllowExplicit,
1270 bool InOverloadResolution,
1271 bool CStyle,
1272 bool AllowObjCWritebackConversion) {
1273 return clang::TryImplicitConversion(*this, From, ToType,
1274 SuppressUserConversions, AllowExplicit,
1275 InOverloadResolution, CStyle,
1276 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001277}
1278
Douglas Gregor575c63a2010-04-16 22:27:05 +00001279/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001280/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001281/// converted expression. Flavor is the kind of conversion we're
1282/// performing, used in the error message. If @p AllowExplicit,
1283/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001284ExprResult
1285Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001286 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001287 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001288 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001289}
1290
John Wiegley429bb272011-04-08 18:41:53 +00001291ExprResult
1292Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001293 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001294 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001295 if (checkPlaceholderForOverload(*this, From))
1296 return ExprError();
1297
John McCallf85e1932011-06-15 23:02:42 +00001298 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1299 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001300 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001301 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001302
John McCall120d63c2010-08-24 20:38:10 +00001303 ICS = clang::TryImplicitConversion(*this, From, ToType,
1304 /*SuppressUserConversions=*/false,
1305 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001306 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001307 /*CStyle=*/false,
1308 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001309 return PerformImplicitConversion(From, ToType, ICS, Action);
1310}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001311
1312/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001313/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001314bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1315 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001316 if (Context.hasSameUnqualifiedType(FromType, ToType))
1317 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001318
John McCall00ccbef2010-12-21 00:44:39 +00001319 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1320 // where F adds one of the following at most once:
1321 // - a pointer
1322 // - a member pointer
1323 // - a block pointer
1324 CanQualType CanTo = Context.getCanonicalType(ToType);
1325 CanQualType CanFrom = Context.getCanonicalType(FromType);
1326 Type::TypeClass TyClass = CanTo->getTypeClass();
1327 if (TyClass != CanFrom->getTypeClass()) return false;
1328 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1329 if (TyClass == Type::Pointer) {
1330 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1331 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1332 } else if (TyClass == Type::BlockPointer) {
1333 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1334 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1335 } else if (TyClass == Type::MemberPointer) {
1336 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1337 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1338 } else {
1339 return false;
1340 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001341
John McCall00ccbef2010-12-21 00:44:39 +00001342 TyClass = CanTo->getTypeClass();
1343 if (TyClass != CanFrom->getTypeClass()) return false;
1344 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1345 return false;
1346 }
1347
1348 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1349 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1350 if (!EInfo.getNoReturn()) return false;
1351
1352 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1353 assert(QualType(FromFn, 0).isCanonical());
1354 if (QualType(FromFn, 0) != CanTo) return false;
1355
1356 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001357 return true;
1358}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001360/// \brief Determine whether the conversion from FromType to ToType is a valid
1361/// vector conversion.
1362///
1363/// \param ICK Will be set to the vector conversion kind, if this is a vector
1364/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1366 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001367 // We need at least one of these types to be a vector type to have a vector
1368 // conversion.
1369 if (!ToType->isVectorType() && !FromType->isVectorType())
1370 return false;
1371
1372 // Identical types require no conversions.
1373 if (Context.hasSameUnqualifiedType(FromType, ToType))
1374 return false;
1375
1376 // There are no conversions between extended vector types, only identity.
1377 if (ToType->isExtVectorType()) {
1378 // There are no conversions between extended vector types other than the
1379 // identity conversion.
1380 if (FromType->isExtVectorType())
1381 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001382
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001383 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001384 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001385 ICK = ICK_Vector_Splat;
1386 return true;
1387 }
1388 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001389
1390 // We can perform the conversion between vector types in the following cases:
1391 // 1)vector types are equivalent AltiVec and GCC vector types
1392 // 2)lax vector conversions are permitted and the vector types are of the
1393 // same size
1394 if (ToType->isVectorType() && FromType->isVectorType()) {
1395 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001396 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001397 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001398 ICK = ICK_Vector_Conversion;
1399 return true;
1400 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001401 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001402
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001403 return false;
1404}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001405
Douglas Gregor7d000652012-04-12 20:48:09 +00001406static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1407 bool InOverloadResolution,
1408 StandardConversionSequence &SCS,
1409 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001410
Douglas Gregor60d62c22008-10-31 16:23:19 +00001411/// IsStandardConversion - Determines whether there is a standard
1412/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1413/// expression From to the type ToType. Standard conversion sequences
1414/// only consider non-class types; for conversions that involve class
1415/// types, use TryImplicitConversion. If a conversion exists, SCS will
1416/// contain the standard conversion sequence required to perform this
1417/// conversion and this routine will return true. Otherwise, this
1418/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001419static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1420 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001421 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001422 bool CStyle,
1423 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001425
Douglas Gregor60d62c22008-10-31 16:23:19 +00001426 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001427 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001428 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001429 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001430 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001431 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001432
Douglas Gregorf9201e02009-02-11 23:02:49 +00001433 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001434 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001435 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001436 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001437 return false;
1438
Mike Stump1eb44332009-09-09 15:08:12 +00001439 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001440 }
1441
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442 // The first conversion can be an lvalue-to-rvalue conversion,
1443 // array-to-pointer conversion, or function-to-pointer conversion
1444 // (C++ 4p1).
1445
John McCall120d63c2010-08-24 20:38:10 +00001446 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001447 DeclAccessPair AccessPair;
1448 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001450 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001451 // We were able to resolve the address of the overloaded function,
1452 // so we can convert to the type of that function.
1453 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001454
1455 // we can sometimes resolve &foo<int> regardless of ToType, so check
1456 // if the type matches (identity) or we are converting to bool
1457 if (!S.Context.hasSameUnqualifiedType(
1458 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1459 QualType resultTy;
1460 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001461 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001462 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1463 // otherwise, only a boolean conversion is standard
1464 if (!ToType->isBooleanType())
1465 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001467
Chandler Carruth90434232011-03-29 08:08:18 +00001468 // Check if the "from" expression is taking the address of an overloaded
1469 // function and recompute the FromType accordingly. Take advantage of the
1470 // fact that non-static member functions *must* have such an address-of
1471 // expression.
1472 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1473 if (Method && !Method->isStatic()) {
1474 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1475 "Non-unary operator on non-static member address");
1476 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1477 == UO_AddrOf &&
1478 "Non-address-of operator on non-static member address");
1479 const Type *ClassType
1480 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1481 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001482 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1484 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001485 "Non-address-of operator for overloaded function expression");
1486 FromType = S.Context.getPointerType(FromType);
1487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001488
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001489 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001490 assert(S.Context.hasSameType(
1491 FromType,
1492 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001493 } else {
1494 return false;
1495 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001496 }
John McCall21480112011-08-30 00:57:29 +00001497 // Lvalue-to-rvalue conversion (C++11 4.1):
1498 // A glvalue (3.10) of a non-function, non-array type T can
1499 // be converted to a prvalue.
1500 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001501 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001502 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001503 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001506 // C11 6.3.2.1p2:
1507 // ... if the lvalue has atomic type, the value has the non-atomic version
1508 // of the type of the lvalue ...
1509 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1510 FromType = Atomic->getValueType();
1511
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001512 // If T is a non-class type, the type of the rvalue is the
1513 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001514 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1515 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001516 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001517 } else if (FromType->isArrayType()) {
1518 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001519 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001520
1521 // An lvalue or rvalue of type "array of N T" or "array of unknown
1522 // bound of T" can be converted to an rvalue of type "pointer to
1523 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001524 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001525
John McCall120d63c2010-08-24 20:38:10 +00001526 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001528 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001529
1530 // For the purpose of ranking in overload resolution
1531 // (13.3.3.1.1), this conversion is considered an
1532 // array-to-pointer conversion followed by a qualification
1533 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001534 SCS.Second = ICK_Identity;
1535 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001536 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001537 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001538 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001540 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001541 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001542 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001543
1544 // An lvalue of function type T can be converted to an rvalue of
1545 // type "pointer to T." The result is a pointer to the
1546 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001547 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001548 } else {
1549 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001550 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001551 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001552 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553
1554 // The second conversion can be an integral promotion, floating
1555 // point promotion, integral conversion, floating point conversion,
1556 // floating-integral conversion, pointer conversion,
1557 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001558 // For overloading in C, this can also be a "compatible-type"
1559 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001560 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001561 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001562 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001563 // The unqualified versions of the types are the same: there's no
1564 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001565 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001566 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001567 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001568 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001569 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001570 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001571 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001572 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001574 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001575 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001576 SCS.Second = ICK_Complex_Promotion;
1577 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001578 } else if (ToType->isBooleanType() &&
1579 (FromType->isArithmeticType() ||
1580 FromType->isAnyPointerType() ||
1581 FromType->isBlockPointerType() ||
1582 FromType->isMemberPointerType() ||
1583 FromType->isNullPtrType())) {
1584 // Boolean conversions (C++ 4.12).
1585 SCS.Second = ICK_Boolean_Conversion;
1586 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001587 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001588 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001589 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001590 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001592 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001593 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001594 SCS.Second = ICK_Complex_Conversion;
1595 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001596 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1597 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001598 // Complex-real conversions (C99 6.3.1.7)
1599 SCS.Second = ICK_Complex_Real;
1600 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001601 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001602 // Floating point conversions (C++ 4.8).
1603 SCS.Second = ICK_Floating_Conversion;
1604 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001605 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001606 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001607 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001608 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001609 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001610 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001611 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001612 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001613 SCS.Second = ICK_Block_Pointer_Conversion;
1614 } else if (AllowObjCWritebackConversion &&
1615 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1616 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001617 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1618 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001619 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001620 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001621 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001622 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001624 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001625 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001626 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001627 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001628 SCS.Second = SecondICK;
1629 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001630 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001631 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001632 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001633 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001634 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001635 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001636 // Treat a conversion that strips "noreturn" as an identity conversion.
1637 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001638 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1639 InOverloadResolution,
1640 SCS, CStyle)) {
1641 SCS.Second = ICK_TransparentUnionConversion;
1642 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001643 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1644 CStyle)) {
1645 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001646 // appropriately.
1647 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001648 } else if (ToType->isEventT() &&
1649 From->isIntegerConstantExpr(S.getASTContext()) &&
1650 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1651 SCS.Second = ICK_Zero_Event_Conversion;
1652 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001653 } else {
1654 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001655 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001656 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001657 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001658
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001659 QualType CanonFrom;
1660 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001661 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001662 bool ObjCLifetimeConversion;
1663 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1664 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001665 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001666 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001668 CanonFrom = S.Context.getCanonicalType(FromType);
1669 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670 } else {
1671 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001672 SCS.Third = ICK_Identity;
1673
Mike Stump1eb44332009-09-09 15:08:12 +00001674 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001675 // [...] Any difference in top-level cv-qualification is
1676 // subsumed by the initialization itself and does not constitute
1677 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001678 CanonFrom = S.Context.getCanonicalType(FromType);
1679 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001681 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001682 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001683 FromType = ToType;
1684 CanonFrom = CanonTo;
1685 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001686 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001687 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001688
1689 // If we have not converted the argument type to the parameter type,
1690 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001691 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001692 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001693
Douglas Gregor60d62c22008-10-31 16:23:19 +00001694 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001695}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001696
1697static bool
1698IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1699 QualType &ToType,
1700 bool InOverloadResolution,
1701 StandardConversionSequence &SCS,
1702 bool CStyle) {
1703
1704 const RecordType *UT = ToType->getAsUnionType();
1705 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1706 return false;
1707 // The field to initialize within the transparent union.
1708 RecordDecl *UD = UT->getDecl();
1709 // It's compatible if the expression matches any of the fields.
1710 for (RecordDecl::field_iterator it = UD->field_begin(),
1711 itend = UD->field_end();
1712 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001713 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1714 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001715 ToType = it->getType();
1716 return true;
1717 }
1718 }
1719 return false;
1720}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001721
1722/// IsIntegralPromotion - Determines whether the conversion from the
1723/// expression From (whose potentially-adjusted type is FromType) to
1724/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1725/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001726bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001727 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001728 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001729 if (!To) {
1730 return false;
1731 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001732
1733 // An rvalue of type char, signed char, unsigned char, short int, or
1734 // unsigned short int can be converted to an rvalue of type int if
1735 // int can represent all the values of the source type; otherwise,
1736 // the source rvalue can be converted to an rvalue of type unsigned
1737 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001738 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1739 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001740 if (// We can promote any signed, promotable integer type to an int
1741 (FromType->isSignedIntegerType() ||
1742 // We can promote any unsigned integer type whose size is
1743 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001744 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001745 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001746 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001747 }
1748
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001749 return To->getKind() == BuiltinType::UInt;
1750 }
1751
Richard Smithe7ff9192012-09-13 21:18:54 +00001752 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001753 // A prvalue of an unscoped enumeration type whose underlying type is not
1754 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1755 // following types that can represent all the values of the enumeration
1756 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1757 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001758 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001759 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001760 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001761 // with lowest integer conversion rank (4.13) greater than the rank of long
1762 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001763 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001764 // C++11 [conv.prom]p4:
1765 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1766 // can be converted to a prvalue of its underlying type. Moreover, if
1767 // integral promotion can be applied to its underlying type, a prvalue of an
1768 // unscoped enumeration type whose underlying type is fixed can also be
1769 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001770 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1771 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1772 // provided for a scoped enumeration.
1773 if (FromEnumType->getDecl()->isScoped())
1774 return false;
1775
Richard Smithe7ff9192012-09-13 21:18:54 +00001776 // We can perform an integral promotion to the underlying type of the enum,
1777 // even if that's not the promoted type.
1778 if (FromEnumType->getDecl()->isFixed()) {
1779 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1780 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1781 IsIntegralPromotion(From, Underlying, ToType);
1782 }
1783
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001784 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001786 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001787 return Context.hasSameUnqualifiedType(ToType,
1788 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001789 }
John McCall842aef82009-12-09 09:09:27 +00001790
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001791 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001792 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1793 // to an rvalue a prvalue of the first of the following types that can
1794 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001795 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001796 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001797 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001799 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001800 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001801 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001802 // Determine whether the type we're converting from is signed or
1803 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001804 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001805 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807 // The types we'll try to promote to, in the appropriate
1808 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001809 QualType PromoteTypes[6] = {
1810 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001811 Context.LongTy, Context.UnsignedLongTy ,
1812 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001813 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001814 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1816 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001817 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001818 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1819 // We found the type that we can promote to. If this is the
1820 // type we wanted, we have a promotion. Otherwise, no
1821 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001822 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001823 }
1824 }
1825 }
1826
1827 // An rvalue for an integral bit-field (9.6) can be converted to an
1828 // rvalue of type int if int can represent all the values of the
1829 // bit-field; otherwise, it can be converted to unsigned int if
1830 // unsigned int can represent all the values of the bit-field. If
1831 // the bit-field is larger yet, no integral promotion applies to
1832 // it. If the bit-field has an enumerated type, it is treated as any
1833 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001834 // FIXME: We should delay checking of bit-fields until we actually perform the
1835 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001836 using llvm::APSInt;
1837 if (From)
1838 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001839 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001840 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001841 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1842 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1843 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregor86f19402008-12-20 23:49:58 +00001845 // Are we promoting to an int from a bitfield that fits in an int?
1846 if (BitWidth < ToSize ||
1847 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1848 return To->getKind() == BuiltinType::Int;
1849 }
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Douglas Gregor86f19402008-12-20 23:49:58 +00001851 // Are we promoting to an unsigned int from an unsigned bitfield
1852 // that fits into an unsigned int?
1853 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1854 return To->getKind() == BuiltinType::UInt;
1855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor86f19402008-12-20 23:49:58 +00001857 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001858 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001861 // An rvalue of type bool can be converted to an rvalue of type int,
1862 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001863 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001864 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001865 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001866
1867 return false;
1868}
1869
1870/// IsFloatingPointPromotion - Determines whether the conversion from
1871/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1872/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001873bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001874 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1875 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001876 /// An rvalue of type float can be converted to an rvalue of type
1877 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001878 if (FromBuiltin->getKind() == BuiltinType::Float &&
1879 ToBuiltin->getKind() == BuiltinType::Double)
1880 return true;
1881
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001882 // C99 6.3.1.5p1:
1883 // When a float is promoted to double or long double, or a
1884 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001885 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001886 (FromBuiltin->getKind() == BuiltinType::Float ||
1887 FromBuiltin->getKind() == BuiltinType::Double) &&
1888 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1889 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001890
1891 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001892 if (!getLangOpts().NativeHalfType &&
1893 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001894 ToBuiltin->getKind() == BuiltinType::Float)
1895 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001896 }
1897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001898 return false;
1899}
1900
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001901/// \brief Determine if a conversion is a complex promotion.
1902///
1903/// A complex promotion is defined as a complex -> complex conversion
1904/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001905/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001907 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001908 if (!FromComplex)
1909 return false;
1910
John McCall183700f2009-09-21 23:43:11 +00001911 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001912 if (!ToComplex)
1913 return false;
1914
1915 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001916 ToComplex->getElementType()) ||
1917 IsIntegralPromotion(0, FromComplex->getElementType(),
1918 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001919}
1920
Douglas Gregorcb7de522008-11-26 23:31:11 +00001921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1922/// the pointer type FromPtr to a pointer to type ToPointee, with the
1923/// same type qualifiers as FromPtr has on its pointee type. ToType,
1924/// if non-empty, will be a pointer to ToType that may or may not have
1925/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001926///
Mike Stump1eb44332009-09-09 15:08:12 +00001927static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001928BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001929 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001930 ASTContext &Context,
1931 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001932 assert((FromPtr->getTypeClass() == Type::Pointer ||
1933 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1934 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001935
John McCallf85e1932011-06-15 23:02:42 +00001936 /// Conversions to 'id' subsume cv-qualifier conversions.
1937 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001938 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001939
1940 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001941 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001942 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001943 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001944
John McCallf85e1932011-06-15 23:02:42 +00001945 if (StripObjCLifetime)
1946 Quals.removeObjCLifetime();
1947
Mike Stump1eb44332009-09-09 15:08:12 +00001948 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001949 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001950 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001951 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001952 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001953
1954 // Build a pointer to ToPointee. It has the right qualifiers
1955 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001956 if (isa<ObjCObjectPointerType>(ToType))
1957 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001958 return Context.getPointerType(ToPointee);
1959 }
1960
1961 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001962 QualType QualifiedCanonToPointee
1963 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001964
Douglas Gregorda80f742010-12-01 21:43:58 +00001965 if (isa<ObjCObjectPointerType>(ToType))
1966 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1967 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001968}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001969
Mike Stump1eb44332009-09-09 15:08:12 +00001970static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001971 bool InOverloadResolution,
1972 ASTContext &Context) {
1973 // Handle value-dependent integral null pointer constants correctly.
1974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1975 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001976 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001977 return !InOverloadResolution;
1978
Douglas Gregorce940492009-09-25 04:25:58 +00001979 return Expr->isNullPointerConstant(Context,
1980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1981 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001982}
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001984/// IsPointerConversion - Determines whether the conversion of the
1985/// expression From, which has the (possibly adjusted) type FromType,
1986/// can be converted to the type ToType via a pointer conversion (C++
1987/// 4.10). If so, returns true and places the converted type (that
1988/// might differ from ToType in its cv-qualifiers at some level) into
1989/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001990///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001991/// This routine also supports conversions to and from block pointers
1992/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1993/// pointers to interfaces. FIXME: Once we've determined the
1994/// appropriate overloading rules for Objective-C, we may want to
1995/// split the Objective-C checks into a different routine; however,
1996/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001997/// conversions, so for now they live here. IncompatibleObjC will be
1998/// set if the conversion is an allowed Objective-C conversion that
1999/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00002001 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00002002 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00002003 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002004 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002005 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2006 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002007 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002008
Mike Stump1eb44332009-09-09 15:08:12 +00002009 // Conversion from a null pointer constant to any Objective-C pointer type.
2010 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002012 ConvertedType = ToType;
2013 return true;
2014 }
2015
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002016 // Blocks: Block pointers can be converted to void*.
2017 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002018 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002019 ConvertedType = ToType;
2020 return true;
2021 }
2022 // Blocks: A null pointer constant can be converted to a block
2023 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002024 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002025 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002026 ConvertedType = ToType;
2027 return true;
2028 }
2029
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002030 // If the left-hand-side is nullptr_t, the right side can be a null
2031 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002033 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002034 ConvertedType = ToType;
2035 return true;
2036 }
2037
Ted Kremenek6217b802009-07-29 21:53:49 +00002038 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002039 if (!ToTypePtr)
2040 return false;
2041
2042 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002043 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002044 ConvertedType = ToType;
2045 return true;
2046 }
Sebastian Redl07779722008-10-31 14:43:28 +00002047
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002048 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002049 // , including objective-c pointers.
2050 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002051 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002052 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002053 ConvertedType = BuildSimilarlyQualifiedPointerType(
2054 FromType->getAs<ObjCObjectPointerType>(),
2055 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002056 ToType, Context);
2057 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002058 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002059 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002060 if (!FromTypePtr)
2061 return false;
2062
2063 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002064
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002065 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002066 // pointer conversion, so don't do all of the work below.
2067 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2068 return false;
2069
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002070 // An rvalue of type "pointer to cv T," where T is an object type,
2071 // can be converted to an rvalue of type "pointer to cv void" (C++
2072 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002073 if (FromPointeeType->isIncompleteOrObjectType() &&
2074 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002076 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002077 ToType, Context,
2078 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002079 return true;
2080 }
2081
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002082 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002083 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002084 ToPointeeType->isVoidType()) {
2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2086 ToPointeeType,
2087 ToType, Context);
2088 return true;
2089 }
2090
Douglas Gregorf9201e02009-02-11 23:02:49 +00002091 // When we're overloading in C, we allow a special kind of pointer
2092 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002093 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002094 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002096 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002097 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002098 return true;
2099 }
2100
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002101 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002102 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002103 // An rvalue of type "pointer to cv D," where D is a class type,
2104 // can be converted to an rvalue of type "pointer to cv B," where
2105 // B is a base class (clause 10) of D. If B is an inaccessible
2106 // (clause 11) or ambiguous (10.2) base class of D, a program that
2107 // necessitates this conversion is ill-formed. The result of the
2108 // conversion is a pointer to the base class sub-object of the
2109 // derived class object. The null pointer value is converted to
2110 // the null pointer value of the destination type.
2111 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002112 // Note that we do not check for ambiguity or inaccessibility
2113 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002114 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002115 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002116 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002117 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002118 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002120 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002121 ToType, Context);
2122 return true;
2123 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002124
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002125 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2126 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2128 ToPointeeType,
2129 ToType, Context);
2130 return true;
2131 }
2132
Douglas Gregorc7887512008-12-19 19:13:09 +00002133 return false;
2134}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002135
2136/// \brief Adopt the given qualifiers for the given type.
2137static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2138 Qualifiers TQs = T.getQualifiers();
2139
2140 // Check whether qualifiers already match.
2141 if (TQs == Qs)
2142 return T;
2143
2144 if (Qs.compatiblyIncludes(TQs))
2145 return Context.getQualifiedType(T, Qs);
2146
2147 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2148}
Douglas Gregorc7887512008-12-19 19:13:09 +00002149
2150/// isObjCPointerConversion - Determines whether this is an
2151/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2152/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002153bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002154 QualType& ConvertedType,
2155 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002156 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002157 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002158
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002159 // The set of qualifiers on the type we're converting from.
2160 Qualifiers FromQualifiers = FromType.getQualifiers();
2161
Steve Naroff14108da2009-07-10 23:34:53 +00002162 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002163 const ObjCObjectPointerType* ToObjCPtr =
2164 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002165 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002166 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002167
Steve Naroff14108da2009-07-10 23:34:53 +00002168 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002169 // If the pointee types are the same (ignoring qualifications),
2170 // then this is not a pointer conversion.
2171 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2172 FromObjCPtr->getPointeeType()))
2173 return false;
2174
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002175 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002176 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002177 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002178 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002180 return true;
2181 }
2182 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002183 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002184 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002185 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002186 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002187 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002188 return true;
2189 }
2190 // Objective C++: We're able to convert from a pointer to an
2191 // interface to a pointer to a different interface.
2192 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002193 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2194 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002195 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002196 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2197 FromObjCPtr->getPointeeType()))
2198 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002200 ToObjCPtr->getPointeeType(),
2201 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002203 return true;
2204 }
2205
2206 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2207 // Okay: this is some kind of implicit downcast of Objective-C
2208 // interfaces, which is permitted. However, we're going to
2209 // complain about it.
2210 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002211 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002212 ToObjCPtr->getPointeeType(),
2213 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002214 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002215 return true;
2216 }
Mike Stump1eb44332009-09-09 15:08:12 +00002217 }
Steve Naroff14108da2009-07-10 23:34:53 +00002218 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002219 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002220 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002221 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002222 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002223 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002224 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002225 // to a block pointer type.
2226 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002227 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002228 return true;
2229 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002230 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002232 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002233 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002234 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002235 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002237 return true;
2238 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002239 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002240 return false;
2241
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002242 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002243 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002244 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002245 else if (const BlockPointerType *FromBlockPtr =
2246 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002247 FromPointeeType = FromBlockPtr->getPointeeType();
2248 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002249 return false;
2250
Douglas Gregorc7887512008-12-19 19:13:09 +00002251 // If we have pointers to pointers, recursively check whether this
2252 // is an Objective-C conversion.
2253 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2255 IncompatibleObjC)) {
2256 // We always complain about this conversion.
2257 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002258 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002259 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002260 return true;
2261 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002262 // Allow conversion of pointee being objective-c pointer to another one;
2263 // as in I* to id.
2264 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2265 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2266 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2267 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002268
Douglas Gregorda80f742010-12-01 21:43:58 +00002269 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002270 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002271 return true;
2272 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002273
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002274 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002275 // differences in the argument and result types are in Objective-C
2276 // pointer conversions. If so, we permit the conversion (but
2277 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002278 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002279 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002280 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002281 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002282 if (FromFunctionType && ToFunctionType) {
2283 // If the function types are exactly the same, this isn't an
2284 // Objective-C pointer conversion.
2285 if (Context.getCanonicalType(FromPointeeType)
2286 == Context.getCanonicalType(ToPointeeType))
2287 return false;
2288
2289 // Perform the quick checks that will tell us whether these
2290 // function types are obviously different.
2291 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2292 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2293 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2294 return false;
2295
2296 bool HasObjCConversion = false;
2297 if (Context.getCanonicalType(FromFunctionType->getResultType())
2298 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2299 // Okay, the types match exactly. Nothing to do.
2300 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2301 ToFunctionType->getResultType(),
2302 ConvertedType, IncompatibleObjC)) {
2303 // Okay, we have an Objective-C pointer conversion.
2304 HasObjCConversion = true;
2305 } else {
2306 // Function types are too different. Abort.
2307 return false;
2308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Douglas Gregorc7887512008-12-19 19:13:09 +00002310 // Check argument types.
2311 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2312 ArgIdx != NumArgs; ++ArgIdx) {
2313 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2314 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2315 if (Context.getCanonicalType(FromArgType)
2316 == Context.getCanonicalType(ToArgType)) {
2317 // Okay, the types match exactly. Nothing to do.
2318 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2319 ConvertedType, IncompatibleObjC)) {
2320 // Okay, we have an Objective-C pointer conversion.
2321 HasObjCConversion = true;
2322 } else {
2323 // Argument types are too different. Abort.
2324 return false;
2325 }
2326 }
2327
2328 if (HasObjCConversion) {
2329 // We had an Objective-C conversion. Allow this pointer
2330 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002331 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002332 IncompatibleObjC = true;
2333 return true;
2334 }
2335 }
2336
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002337 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002338}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002339
John McCallf85e1932011-06-15 23:02:42 +00002340/// \brief Determine whether this is an Objective-C writeback conversion,
2341/// used for parameter passing when performing automatic reference counting.
2342///
2343/// \param FromType The type we're converting form.
2344///
2345/// \param ToType The type we're converting to.
2346///
2347/// \param ConvertedType The type that will be produced after applying
2348/// this conversion.
2349bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2350 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002351 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002352 Context.hasSameUnqualifiedType(FromType, ToType))
2353 return false;
2354
2355 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2356 QualType ToPointee;
2357 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2358 ToPointee = ToPointer->getPointeeType();
2359 else
2360 return false;
2361
2362 Qualifiers ToQuals = ToPointee.getQualifiers();
2363 if (!ToPointee->isObjCLifetimeType() ||
2364 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002365 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002366 return false;
2367
2368 // Argument must be a pointer to __strong to __weak.
2369 QualType FromPointee;
2370 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2371 FromPointee = FromPointer->getPointeeType();
2372 else
2373 return false;
2374
2375 Qualifiers FromQuals = FromPointee.getQualifiers();
2376 if (!FromPointee->isObjCLifetimeType() ||
2377 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2378 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2379 return false;
2380
2381 // Make sure that we have compatible qualifiers.
2382 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2383 if (!ToQuals.compatiblyIncludes(FromQuals))
2384 return false;
2385
2386 // Remove qualifiers from the pointee type we're converting from; they
2387 // aren't used in the compatibility check belong, and we'll be adding back
2388 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2389 FromPointee = FromPointee.getUnqualifiedType();
2390
2391 // The unqualified form of the pointee types must be compatible.
2392 ToPointee = ToPointee.getUnqualifiedType();
2393 bool IncompatibleObjC;
2394 if (Context.typesAreCompatible(FromPointee, ToPointee))
2395 FromPointee = ToPointee;
2396 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2397 IncompatibleObjC))
2398 return false;
2399
2400 /// \brief Construct the type we're converting to, which is a pointer to
2401 /// __autoreleasing pointee.
2402 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2403 ConvertedType = Context.getPointerType(FromPointee);
2404 return true;
2405}
2406
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002407bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2408 QualType& ConvertedType) {
2409 QualType ToPointeeType;
2410 if (const BlockPointerType *ToBlockPtr =
2411 ToType->getAs<BlockPointerType>())
2412 ToPointeeType = ToBlockPtr->getPointeeType();
2413 else
2414 return false;
2415
2416 QualType FromPointeeType;
2417 if (const BlockPointerType *FromBlockPtr =
2418 FromType->getAs<BlockPointerType>())
2419 FromPointeeType = FromBlockPtr->getPointeeType();
2420 else
2421 return false;
2422 // We have pointer to blocks, check whether the only
2423 // differences in the argument and result types are in Objective-C
2424 // pointer conversions. If so, we permit the conversion.
2425
2426 const FunctionProtoType *FromFunctionType
2427 = FromPointeeType->getAs<FunctionProtoType>();
2428 const FunctionProtoType *ToFunctionType
2429 = ToPointeeType->getAs<FunctionProtoType>();
2430
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002431 if (!FromFunctionType || !ToFunctionType)
2432 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002433
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002434 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002435 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002436
2437 // Perform the quick checks that will tell us whether these
2438 // function types are obviously different.
2439 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2440 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2441 return false;
2442
2443 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2444 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2445 if (FromEInfo != ToEInfo)
2446 return false;
2447
2448 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002449 if (Context.hasSameType(FromFunctionType->getResultType(),
2450 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002451 // Okay, the types match exactly. Nothing to do.
2452 } else {
2453 QualType RHS = FromFunctionType->getResultType();
2454 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002455 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002456 !RHS.hasQualifiers() && LHS.hasQualifiers())
2457 LHS = LHS.getUnqualifiedType();
2458
2459 if (Context.hasSameType(RHS,LHS)) {
2460 // OK exact match.
2461 } else if (isObjCPointerConversion(RHS, LHS,
2462 ConvertedType, IncompatibleObjC)) {
2463 if (IncompatibleObjC)
2464 return false;
2465 // Okay, we have an Objective-C pointer conversion.
2466 }
2467 else
2468 return false;
2469 }
2470
2471 // Check argument types.
2472 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2473 ArgIdx != NumArgs; ++ArgIdx) {
2474 IncompatibleObjC = false;
2475 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2476 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2477 if (Context.hasSameType(FromArgType, ToArgType)) {
2478 // Okay, the types match exactly. Nothing to do.
2479 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2480 ConvertedType, IncompatibleObjC)) {
2481 if (IncompatibleObjC)
2482 return false;
2483 // Okay, we have an Objective-C pointer conversion.
2484 } else
2485 // Argument types are too different. Abort.
2486 return false;
2487 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002488 if (LangOpts.ObjCAutoRefCount &&
2489 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2490 ToFunctionType))
2491 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002492
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002493 ConvertedType = ToType;
2494 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002495}
2496
Richard Trieu6efd4c52011-11-23 22:32:32 +00002497enum {
2498 ft_default,
2499 ft_different_class,
2500 ft_parameter_arity,
2501 ft_parameter_mismatch,
2502 ft_return_type,
2503 ft_qualifer_mismatch
2504};
2505
2506/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2507/// function types. Catches different number of parameter, mismatch in
2508/// parameter types, and different return types.
2509void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2510 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002511 // If either type is not valid, include no extra info.
2512 if (FromType.isNull() || ToType.isNull()) {
2513 PDiag << ft_default;
2514 return;
2515 }
2516
Richard Trieu6efd4c52011-11-23 22:32:32 +00002517 // Get the function type from the pointers.
2518 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2519 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2520 *ToMember = ToType->getAs<MemberPointerType>();
2521 if (FromMember->getClass() != ToMember->getClass()) {
2522 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2523 << QualType(FromMember->getClass(), 0);
2524 return;
2525 }
2526 FromType = FromMember->getPointeeType();
2527 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002528 }
2529
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002530 if (FromType->isPointerType())
2531 FromType = FromType->getPointeeType();
2532 if (ToType->isPointerType())
2533 ToType = ToType->getPointeeType();
2534
2535 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002536 FromType = FromType.getNonReferenceType();
2537 ToType = ToType.getNonReferenceType();
2538
Richard Trieu6efd4c52011-11-23 22:32:32 +00002539 // Don't print extra info for non-specialized template functions.
2540 if (FromType->isInstantiationDependentType() &&
2541 !FromType->getAs<TemplateSpecializationType>()) {
2542 PDiag << ft_default;
2543 return;
2544 }
2545
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002546 // No extra info for same types.
2547 if (Context.hasSameType(FromType, ToType)) {
2548 PDiag << ft_default;
2549 return;
2550 }
2551
Richard Trieu6efd4c52011-11-23 22:32:32 +00002552 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2553 *ToFunction = ToType->getAs<FunctionProtoType>();
2554
2555 // Both types need to be function types.
2556 if (!FromFunction || !ToFunction) {
2557 PDiag << ft_default;
2558 return;
2559 }
2560
2561 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2562 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2563 << FromFunction->getNumArgs();
2564 return;
2565 }
2566
2567 // Handle different parameter types.
2568 unsigned ArgPos;
2569 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2570 PDiag << ft_parameter_mismatch << ArgPos + 1
2571 << ToFunction->getArgType(ArgPos)
2572 << FromFunction->getArgType(ArgPos);
2573 return;
2574 }
2575
2576 // Handle different return type.
2577 if (!Context.hasSameType(FromFunction->getResultType(),
2578 ToFunction->getResultType())) {
2579 PDiag << ft_return_type << ToFunction->getResultType()
2580 << FromFunction->getResultType();
2581 return;
2582 }
2583
2584 unsigned FromQuals = FromFunction->getTypeQuals(),
2585 ToQuals = ToFunction->getTypeQuals();
2586 if (FromQuals != ToQuals) {
2587 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2588 return;
2589 }
2590
2591 // Unable to find a difference, so add no extra info.
2592 PDiag << ft_default;
2593}
2594
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002595/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002596/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002597/// they have same number of arguments. This routine assumes that Objective-C
2598/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002599/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002600/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002601bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002602 const FunctionProtoType *NewType,
2603 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002604 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002605 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2606 N = NewType->arg_type_begin(),
2607 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2608 if (!Context.hasSameType(*O, *N)) {
2609 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2610 return false;
2611 }
2612 }
2613 return true;
2614 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002615
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002616 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2617 N = NewType->arg_type_begin(),
2618 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2619 QualType ToType = (*O);
2620 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002621 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002622 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2623 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002624 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2625 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2626 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2627 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002628 continue;
2629 }
John McCallc12c5bb2010-05-15 11:32:37 +00002630 else if (const ObjCObjectPointerType *PTTo =
2631 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002632 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002633 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002634 if (Context.hasSameUnqualifiedType(
2635 PTTo->getObjectType()->getBaseType(),
2636 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002637 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002638 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002639 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002640 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002641 }
2642 }
2643 return true;
2644}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002645
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002646/// CheckPointerConversion - Check the pointer conversion from the
2647/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002648/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002649/// conversions for which IsPointerConversion has already returned
2650/// true. It returns true and produces a diagnostic if there was an
2651/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002652bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002653 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002654 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002655 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002656 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002657 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002658
John McCalldaa8e4e2010-11-15 09:13:47 +00002659 Kind = CK_BitCast;
2660
David Blaikie50800fc2012-08-08 17:33:31 +00002661 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2662 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2663 Expr::NPCK_ZeroExpression) {
2664 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2665 DiagRuntimeBehavior(From->getExprLoc(), From,
2666 PDiag(diag::warn_impcast_bool_to_null_pointer)
2667 << ToType << From->getSourceRange());
2668 else if (!isUnevaluatedContext())
2669 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2670 << ToType << From->getSourceRange();
2671 }
John McCall1d9b3b22011-09-09 05:25:32 +00002672 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2673 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002674 QualType FromPointeeType = FromPtrType->getPointeeType(),
2675 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002676
Douglas Gregor5fccd362010-03-03 23:55:11 +00002677 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2678 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002679 // We must have a derived-to-base conversion. Check an
2680 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002681 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2682 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002683 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002684 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002685 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002686
Anders Carlsson61faec12009-09-12 04:46:44 +00002687 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002688 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002689 }
2690 }
John McCall1d9b3b22011-09-09 05:25:32 +00002691 } else if (const ObjCObjectPointerType *ToPtrType =
2692 ToType->getAs<ObjCObjectPointerType>()) {
2693 if (const ObjCObjectPointerType *FromPtrType =
2694 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002695 // Objective-C++ conversions are always okay.
2696 // FIXME: We should have a different class of conversions for the
2697 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002698 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002699 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002700 } else if (FromType->isBlockPointerType()) {
2701 Kind = CK_BlockPointerToObjCPointerCast;
2702 } else {
2703 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002704 }
John McCall1d9b3b22011-09-09 05:25:32 +00002705 } else if (ToType->isBlockPointerType()) {
2706 if (!FromType->isBlockPointerType())
2707 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002708 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002709
2710 // We shouldn't fall into this case unless it's valid for other
2711 // reasons.
2712 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2713 Kind = CK_NullToPointer;
2714
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002715 return false;
2716}
2717
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002718/// IsMemberPointerConversion - Determines whether the conversion of the
2719/// expression From, which has the (possibly adjusted) type FromType, can be
2720/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2721/// If so, returns true and places the converted type (that might differ from
2722/// ToType in its cv-qualifiers at some level) into ConvertedType.
2723bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002724 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002725 bool InOverloadResolution,
2726 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002727 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002728 if (!ToTypePtr)
2729 return false;
2730
2731 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002732 if (From->isNullPointerConstant(Context,
2733 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2734 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002735 ConvertedType = ToType;
2736 return true;
2737 }
2738
2739 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002740 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002741 if (!FromTypePtr)
2742 return false;
2743
2744 // A pointer to member of B can be converted to a pointer to member of D,
2745 // where D is derived from B (C++ 4.11p2).
2746 QualType FromClass(FromTypePtr->getClass(), 0);
2747 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002748
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002749 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002750 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002751 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002752 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2753 ToClass.getTypePtr());
2754 return true;
2755 }
2756
2757 return false;
2758}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002760/// CheckMemberPointerConversion - Check the member pointer conversion from the
2761/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002762/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002763/// for which IsMemberPointerConversion has already returned true. It returns
2764/// true and produces a diagnostic if there was an error, or returns false
2765/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002766bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002767 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002768 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002769 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002770 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002771 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002772 if (!FromPtrType) {
2773 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002774 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002775 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002776 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002777 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002778 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002779 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002780
Ted Kremenek6217b802009-07-29 21:53:49 +00002781 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002782 assert(ToPtrType && "No member pointer cast has a target type "
2783 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002784
Sebastian Redl21593ac2009-01-28 18:33:18 +00002785 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2786 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002787
Sebastian Redl21593ac2009-01-28 18:33:18 +00002788 // FIXME: What about dependent types?
2789 assert(FromClass->isRecordType() && "Pointer into non-class.");
2790 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002791
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002792 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002793 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002794 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2795 assert(DerivationOkay &&
2796 "Should not have been called if derivation isn't OK.");
2797 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002798
Sebastian Redl21593ac2009-01-28 18:33:18 +00002799 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2800 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2802 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2803 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2804 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002805 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002806
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002807 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002808 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2809 << FromClass << ToClass << QualType(VBase, 0)
2810 << From->getSourceRange();
2811 return true;
2812 }
2813
John McCall6b2accb2010-02-10 09:31:12 +00002814 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002815 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2816 Paths.front(),
2817 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002818
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002819 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002820 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002821 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002822 return false;
2823}
2824
Douglas Gregor98cd5992008-10-21 23:43:52 +00002825/// IsQualificationConversion - Determines whether the conversion from
2826/// an rvalue of type FromType to ToType is a qualification conversion
2827/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002828///
2829/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2830/// when the qualification conversion involves a change in the Objective-C
2831/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002832bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002834 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002835 FromType = Context.getCanonicalType(FromType);
2836 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002837 ObjCLifetimeConversion = false;
2838
Douglas Gregor98cd5992008-10-21 23:43:52 +00002839 // If FromType and ToType are the same type, this is not a
2840 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002841 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002842 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002843
Douglas Gregor98cd5992008-10-21 23:43:52 +00002844 // (C++ 4.4p4):
2845 // A conversion can add cv-qualifiers at levels other than the first
2846 // in multi-level pointers, subject to the following rules: [...]
2847 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002848 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002849 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002850 // Within each iteration of the loop, we check the qualifiers to
2851 // determine if this still looks like a qualification
2852 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002853 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002854 // until there are no more pointers or pointers-to-members left to
2855 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002856 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002857
Douglas Gregor621c92a2011-04-25 18:40:17 +00002858 Qualifiers FromQuals = FromType.getQualifiers();
2859 Qualifiers ToQuals = ToType.getQualifiers();
2860
John McCallf85e1932011-06-15 23:02:42 +00002861 // Objective-C ARC:
2862 // Check Objective-C lifetime conversions.
2863 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2864 UnwrappedAnyPointer) {
2865 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2866 ObjCLifetimeConversion = true;
2867 FromQuals.removeObjCLifetime();
2868 ToQuals.removeObjCLifetime();
2869 } else {
2870 // Qualification conversions cannot cast between different
2871 // Objective-C lifetime qualifiers.
2872 return false;
2873 }
2874 }
2875
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002876 // Allow addition/removal of GC attributes but not changing GC attributes.
2877 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2878 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2879 FromQuals.removeObjCGCAttr();
2880 ToQuals.removeObjCGCAttr();
2881 }
2882
Douglas Gregor98cd5992008-10-21 23:43:52 +00002883 // -- for every j > 0, if const is in cv 1,j then const is in cv
2884 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002885 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002886 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Douglas Gregor98cd5992008-10-21 23:43:52 +00002888 // -- if the cv 1,j and cv 2,j are different, then const is in
2889 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002890 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002891 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002892 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Douglas Gregor98cd5992008-10-21 23:43:52 +00002894 // Keep track of whether all prior cv-qualifiers in the "to" type
2895 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002896 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002897 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002898 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002899
2900 // We are left with FromType and ToType being the pointee types
2901 // after unwrapping the original FromType and ToType the same number
2902 // of types. If we unwrapped any pointers, and if FromType and
2903 // ToType have the same unqualified type (since we checked
2904 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002905 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002906}
2907
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002908/// \brief - Determine whether this is a conversion from a scalar type to an
2909/// atomic type.
2910///
2911/// If successful, updates \c SCS's second and third steps in the conversion
2912/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002913static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2914 bool InOverloadResolution,
2915 StandardConversionSequence &SCS,
2916 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002917 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2918 if (!ToAtomic)
2919 return false;
2920
2921 StandardConversionSequence InnerSCS;
2922 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2923 InOverloadResolution, InnerSCS,
2924 CStyle, /*AllowObjCWritebackConversion=*/false))
2925 return false;
2926
2927 SCS.Second = InnerSCS.Second;
2928 SCS.setToType(1, InnerSCS.getToType(1));
2929 SCS.Third = InnerSCS.Third;
2930 SCS.QualificationIncludesObjCLifetime
2931 = InnerSCS.QualificationIncludesObjCLifetime;
2932 SCS.setToType(2, InnerSCS.getToType(2));
2933 return true;
2934}
2935
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002936static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2937 CXXConstructorDecl *Constructor,
2938 QualType Type) {
2939 const FunctionProtoType *CtorType =
2940 Constructor->getType()->getAs<FunctionProtoType>();
2941 if (CtorType->getNumArgs() > 0) {
2942 QualType FirstArg = CtorType->getArgType(0);
2943 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2944 return true;
2945 }
2946 return false;
2947}
2948
Sebastian Redl56a04282012-02-11 23:51:08 +00002949static OverloadingResult
2950IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2951 CXXRecordDecl *To,
2952 UserDefinedConversionSequence &User,
2953 OverloadCandidateSet &CandidateSet,
2954 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002955 DeclContext::lookup_result R = S.LookupConstructors(To);
2956 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002957 Con != ConEnd; ++Con) {
2958 NamedDecl *D = *Con;
2959 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2960
2961 // Find the constructor (which may be a template).
2962 CXXConstructorDecl *Constructor = 0;
2963 FunctionTemplateDecl *ConstructorTmpl
2964 = dyn_cast<FunctionTemplateDecl>(D);
2965 if (ConstructorTmpl)
2966 Constructor
2967 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2968 else
2969 Constructor = cast<CXXConstructorDecl>(D);
2970
2971 bool Usable = !Constructor->isInvalidDecl() &&
2972 S.isInitListConstructor(Constructor) &&
2973 (AllowExplicit || !Constructor->isExplicit());
2974 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002975 // If the first argument is (a reference to) the target type,
2976 // suppress conversions.
2977 bool SuppressUserConversions =
2978 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002979 if (ConstructorTmpl)
2980 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2981 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002982 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002983 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002984 else
2985 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002986 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002987 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002988 }
2989 }
2990
2991 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2992
2993 OverloadCandidateSet::iterator Best;
2994 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2995 case OR_Success: {
2996 // Record the standard conversion we used and the conversion function.
2997 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002998 QualType ThisType = Constructor->getThisType(S.Context);
2999 // Initializer lists don't have conversions as such.
3000 User.Before.setAsIdentityConversion();
3001 User.HadMultipleCandidates = HadMultipleCandidates;
3002 User.ConversionFunction = Constructor;
3003 User.FoundConversionFunction = Best->FoundDecl;
3004 User.After.setAsIdentityConversion();
3005 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3006 User.After.setAllToTypes(ToType);
3007 return OR_Success;
3008 }
3009
3010 case OR_No_Viable_Function:
3011 return OR_No_Viable_Function;
3012 case OR_Deleted:
3013 return OR_Deleted;
3014 case OR_Ambiguous:
3015 return OR_Ambiguous;
3016 }
3017
3018 llvm_unreachable("Invalid OverloadResult!");
3019}
3020
Douglas Gregor734d9862009-01-30 23:27:23 +00003021/// Determines whether there is a user-defined conversion sequence
3022/// (C++ [over.ics.user]) that converts expression From to the type
3023/// ToType. If such a conversion exists, User will contain the
3024/// user-defined conversion sequence that performs such a conversion
3025/// and this routine will return true. Otherwise, this routine returns
3026/// false and User is unspecified.
3027///
Douglas Gregor734d9862009-01-30 23:27:23 +00003028/// \param AllowExplicit true if the conversion should consider C++0x
3029/// "explicit" conversion functions as well as non-explicit conversion
3030/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003031static OverloadingResult
3032IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003033 UserDefinedConversionSequence &User,
3034 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003035 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003036 // Whether we will only visit constructors.
3037 bool ConstructorsOnly = false;
3038
3039 // If the type we are conversion to is a class type, enumerate its
3040 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003041 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003042 // C++ [over.match.ctor]p1:
3043 // When objects of class type are direct-initialized (8.5), or
3044 // copy-initialized from an expression of the same or a
3045 // derived class type (8.5), overload resolution selects the
3046 // constructor. [...] For copy-initialization, the candidate
3047 // functions are all the converting constructors (12.3.1) of
3048 // that class. The argument list is the expression-list within
3049 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003050 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003051 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003052 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003053 ConstructorsOnly = true;
3054
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003055 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003056 // RequireCompleteType may have returned true due to some invalid decl
3057 // during template instantiation, but ToType may be complete enough now
3058 // to try to recover.
3059 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003060 // We're not going to find any constructors.
3061 } else if (CXXRecordDecl *ToRecordDecl
3062 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003063
3064 Expr **Args = &From;
3065 unsigned NumArgs = 1;
3066 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003067 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003068 // But first, see if there is an init-list-contructor that will work.
3069 OverloadingResult Result = IsInitializerListConstructorConversion(
3070 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3071 if (Result != OR_No_Viable_Function)
3072 return Result;
3073 // Never mind.
3074 CandidateSet.clear();
3075
3076 // If we're list-initializing, we pass the individual elements as
3077 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003078 Args = InitList->getInits();
3079 NumArgs = InitList->getNumInits();
3080 ListInitializing = true;
3081 }
3082
David Blaikie3bc93e32012-12-19 00:45:41 +00003083 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3084 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003085 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003086 NamedDecl *D = *Con;
3087 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3088
Douglas Gregordec06662009-08-21 18:42:58 +00003089 // Find the constructor (which may be a template).
3090 CXXConstructorDecl *Constructor = 0;
3091 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003092 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003093 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003094 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003095 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3096 else
John McCall9aa472c2010-03-19 07:35:19 +00003097 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003099 bool Usable = !Constructor->isInvalidDecl();
3100 if (ListInitializing)
3101 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3102 else
3103 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3104 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003105 bool SuppressUserConversions = !ConstructorsOnly;
3106 if (SuppressUserConversions && ListInitializing) {
3107 SuppressUserConversions = false;
3108 if (NumArgs == 1) {
3109 // If the first argument is (a reference to) the target type,
3110 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003111 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3112 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003113 }
3114 }
Douglas Gregordec06662009-08-21 18:42:58 +00003115 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003116 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3117 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003118 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003119 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003120 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003121 // Allow one user-defined conversion when user specifies a
3122 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003123 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003124 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003125 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003126 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003127 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003128 }
3129 }
3130
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003131 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003132 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003133 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003134 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003135 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003136 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003137 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003138 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3139 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003140 std::pair<CXXRecordDecl::conversion_iterator,
3141 CXXRecordDecl::conversion_iterator>
3142 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3143 for (CXXRecordDecl::conversion_iterator
3144 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003145 DeclAccessPair FoundDecl = I.getPair();
3146 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003147 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3148 if (isa<UsingShadowDecl>(D))
3149 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3150
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003151 CXXConversionDecl *Conv;
3152 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003153 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3154 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003155 else
John McCall32daa422010-03-31 01:36:47 +00003156 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003157
3158 if (AllowExplicit || !Conv->isExplicit()) {
3159 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003160 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3161 ActingContext, From, ToType,
3162 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003163 else
John McCall120d63c2010-08-24 20:38:10 +00003164 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3165 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003166 }
3167 }
3168 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003169 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003170
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003171 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3172
Douglas Gregor60d62c22008-10-31 16:23:19 +00003173 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003174 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003175 case OR_Success:
3176 // Record the standard conversion we used and the conversion function.
3177 if (CXXConstructorDecl *Constructor
3178 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3179 // C++ [over.ics.user]p1:
3180 // If the user-defined conversion is specified by a
3181 // constructor (12.3.1), the initial standard conversion
3182 // sequence converts the source type to the type required by
3183 // the argument of the constructor.
3184 //
3185 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003186 if (isa<InitListExpr>(From)) {
3187 // Initializer lists don't have conversions as such.
3188 User.Before.setAsIdentityConversion();
3189 } else {
3190 if (Best->Conversions[0].isEllipsis())
3191 User.EllipsisConversion = true;
3192 else {
3193 User.Before = Best->Conversions[0].Standard;
3194 User.EllipsisConversion = false;
3195 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003196 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003197 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003198 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003199 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003200 User.After.setAsIdentityConversion();
3201 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3202 User.After.setAllToTypes(ToType);
3203 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003204 }
3205 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003206 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3207 // C++ [over.ics.user]p1:
3208 //
3209 // [...] If the user-defined conversion is specified by a
3210 // conversion function (12.3.2), the initial standard
3211 // conversion sequence converts the source type to the
3212 // implicit object parameter of the conversion function.
3213 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003214 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003215 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003216 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003217 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003218
John McCall120d63c2010-08-24 20:38:10 +00003219 // C++ [over.ics.user]p2:
3220 // The second standard conversion sequence converts the
3221 // result of the user-defined conversion to the target type
3222 // for the sequence. Since an implicit conversion sequence
3223 // is an initialization, the special rules for
3224 // initialization by user-defined conversion apply when
3225 // selecting the best user-defined conversion for a
3226 // user-defined conversion sequence (see 13.3.3 and
3227 // 13.3.3.1).
3228 User.After = Best->FinalConversion;
3229 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003230 }
David Blaikie7530c032012-01-17 06:56:22 +00003231 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003232
John McCall120d63c2010-08-24 20:38:10 +00003233 case OR_No_Viable_Function:
3234 return OR_No_Viable_Function;
3235 case OR_Deleted:
3236 // No conversion here! We're done.
3237 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003238
John McCall120d63c2010-08-24 20:38:10 +00003239 case OR_Ambiguous:
3240 return OR_Ambiguous;
3241 }
3242
David Blaikie7530c032012-01-17 06:56:22 +00003243 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003244}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003245
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003246bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003247Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003248 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003249 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003250 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003251 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003252 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003253 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003254 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003255 diag::err_typecheck_ambiguous_condition)
3256 << From->getType() << ToType << From->getSourceRange();
3257 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003258 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003259 diag::err_typecheck_nonviable_condition)
3260 << From->getType() << ToType << From->getSourceRange();
3261 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003262 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003263 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003265}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003266
Douglas Gregorb734e242012-02-22 17:32:19 +00003267/// \brief Compare the user-defined conversion functions or constructors
3268/// of two user-defined conversion sequences to determine whether any ordering
3269/// is possible.
3270static ImplicitConversionSequence::CompareKind
3271compareConversionFunctions(Sema &S,
3272 FunctionDecl *Function1,
3273 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003274 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003275 return ImplicitConversionSequence::Indistinguishable;
3276
3277 // Objective-C++:
3278 // If both conversion functions are implicitly-declared conversions from
3279 // a lambda closure type to a function pointer and a block pointer,
3280 // respectively, always prefer the conversion to a function pointer,
3281 // because the function pointer is more lightweight and is more likely
3282 // to keep code working.
3283 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3284 if (!Conv1)
3285 return ImplicitConversionSequence::Indistinguishable;
3286
3287 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3288 if (!Conv2)
3289 return ImplicitConversionSequence::Indistinguishable;
3290
3291 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3292 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3293 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3294 if (Block1 != Block2)
3295 return Block1? ImplicitConversionSequence::Worse
3296 : ImplicitConversionSequence::Better;
3297 }
3298
3299 return ImplicitConversionSequence::Indistinguishable;
3300}
3301
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003302/// CompareImplicitConversionSequences - Compare two implicit
3303/// conversion sequences to determine whether one is better than the
3304/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003305static ImplicitConversionSequence::CompareKind
3306CompareImplicitConversionSequences(Sema &S,
3307 const ImplicitConversionSequence& ICS1,
3308 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003309{
3310 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3311 // conversion sequences (as defined in 13.3.3.1)
3312 // -- a standard conversion sequence (13.3.3.1.1) is a better
3313 // conversion sequence than a user-defined conversion sequence or
3314 // an ellipsis conversion sequence, and
3315 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3316 // conversion sequence than an ellipsis conversion sequence
3317 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003318 //
John McCall1d318332010-01-12 00:44:57 +00003319 // C++0x [over.best.ics]p10:
3320 // For the purpose of ranking implicit conversion sequences as
3321 // described in 13.3.3.2, the ambiguous conversion sequence is
3322 // treated as a user-defined sequence that is indistinguishable
3323 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003324 if (ICS1.getKindRank() < ICS2.getKindRank())
3325 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003326 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003327 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003328
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003329 // The following checks require both conversion sequences to be of
3330 // the same kind.
3331 if (ICS1.getKind() != ICS2.getKind())
3332 return ImplicitConversionSequence::Indistinguishable;
3333
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003334 ImplicitConversionSequence::CompareKind Result =
3335 ImplicitConversionSequence::Indistinguishable;
3336
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003337 // Two implicit conversion sequences of the same form are
3338 // indistinguishable conversion sequences unless one of the
3339 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003340 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003341 Result = CompareStandardConversionSequences(S,
3342 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003343 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003344 // User-defined conversion sequence U1 is a better conversion
3345 // sequence than another user-defined conversion sequence U2 if
3346 // they contain the same user-defined conversion function or
3347 // constructor and if the second standard conversion sequence of
3348 // U1 is better than the second standard conversion sequence of
3349 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003350 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003351 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003352 Result = CompareStandardConversionSequences(S,
3353 ICS1.UserDefined.After,
3354 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003355 else
3356 Result = compareConversionFunctions(S,
3357 ICS1.UserDefined.ConversionFunction,
3358 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003359 }
3360
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003361 // List-initialization sequence L1 is a better conversion sequence than
3362 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3363 // for some X and L2 does not.
3364 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003365 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003366 ICS1.isListInitializationSequence() &&
3367 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003368 if (ICS1.isStdInitializerListElement() &&
3369 !ICS2.isStdInitializerListElement())
3370 return ImplicitConversionSequence::Better;
3371 if (!ICS1.isStdInitializerListElement() &&
3372 ICS2.isStdInitializerListElement())
3373 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003374 }
3375
3376 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003377}
3378
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003379static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3380 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3381 Qualifiers Quals;
3382 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003383 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003384 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003386 return Context.hasSameUnqualifiedType(T1, T2);
3387}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregorad323a82010-01-27 03:51:04 +00003389// Per 13.3.3.2p3, compare the given standard conversion sequences to
3390// determine if one is a proper subset of the other.
3391static ImplicitConversionSequence::CompareKind
3392compareStandardConversionSubsets(ASTContext &Context,
3393 const StandardConversionSequence& SCS1,
3394 const StandardConversionSequence& SCS2) {
3395 ImplicitConversionSequence::CompareKind Result
3396 = ImplicitConversionSequence::Indistinguishable;
3397
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003398 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003399 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003400 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3401 return ImplicitConversionSequence::Better;
3402 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3403 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003404
Douglas Gregorad323a82010-01-27 03:51:04 +00003405 if (SCS1.Second != SCS2.Second) {
3406 if (SCS1.Second == ICK_Identity)
3407 Result = ImplicitConversionSequence::Better;
3408 else if (SCS2.Second == ICK_Identity)
3409 Result = ImplicitConversionSequence::Worse;
3410 else
3411 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003412 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003413 return ImplicitConversionSequence::Indistinguishable;
3414
3415 if (SCS1.Third == SCS2.Third) {
3416 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3417 : ImplicitConversionSequence::Indistinguishable;
3418 }
3419
3420 if (SCS1.Third == ICK_Identity)
3421 return Result == ImplicitConversionSequence::Worse
3422 ? ImplicitConversionSequence::Indistinguishable
3423 : ImplicitConversionSequence::Better;
3424
3425 if (SCS2.Third == ICK_Identity)
3426 return Result == ImplicitConversionSequence::Better
3427 ? ImplicitConversionSequence::Indistinguishable
3428 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003429
Douglas Gregorad323a82010-01-27 03:51:04 +00003430 return ImplicitConversionSequence::Indistinguishable;
3431}
3432
Douglas Gregor440a4832011-01-26 14:52:12 +00003433/// \brief Determine whether one of the given reference bindings is better
3434/// than the other based on what kind of bindings they are.
3435static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3436 const StandardConversionSequence &SCS2) {
3437 // C++0x [over.ics.rank]p3b4:
3438 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3439 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003441 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003442 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003443 // reference*.
3444 //
3445 // FIXME: Rvalue references. We're going rogue with the above edits,
3446 // because the semantics in the current C++0x working paper (N3225 at the
3447 // time of this writing) break the standard definition of std::forward
3448 // and std::reference_wrapper when dealing with references to functions.
3449 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003450 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3451 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3452 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003453
Douglas Gregor440a4832011-01-26 14:52:12 +00003454 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3455 SCS2.IsLvalueReference) ||
3456 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3457 !SCS2.IsLvalueReference);
3458}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003459
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003460/// CompareStandardConversionSequences - Compare two standard
3461/// conversion sequences to determine whether one is better than the
3462/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003463static ImplicitConversionSequence::CompareKind
3464CompareStandardConversionSequences(Sema &S,
3465 const StandardConversionSequence& SCS1,
3466 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003467{
3468 // Standard conversion sequence S1 is a better conversion sequence
3469 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3470
3471 // -- S1 is a proper subsequence of S2 (comparing the conversion
3472 // sequences in the canonical form defined by 13.3.3.1.1,
3473 // excluding any Lvalue Transformation; the identity conversion
3474 // sequence is considered to be a subsequence of any
3475 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003476 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003477 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003478 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003479
3480 // -- the rank of S1 is better than the rank of S2 (by the rules
3481 // defined below), or, if not that,
3482 ImplicitConversionRank Rank1 = SCS1.getRank();
3483 ImplicitConversionRank Rank2 = SCS2.getRank();
3484 if (Rank1 < Rank2)
3485 return ImplicitConversionSequence::Better;
3486 else if (Rank2 < Rank1)
3487 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003488
Douglas Gregor57373262008-10-22 14:17:15 +00003489 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3490 // are indistinguishable unless one of the following rules
3491 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003492
Douglas Gregor57373262008-10-22 14:17:15 +00003493 // A conversion that is not a conversion of a pointer, or
3494 // pointer to member, to bool is better than another conversion
3495 // that is such a conversion.
3496 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3497 return SCS2.isPointerConversionToBool()
3498 ? ImplicitConversionSequence::Better
3499 : ImplicitConversionSequence::Worse;
3500
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003501 // C++ [over.ics.rank]p4b2:
3502 //
3503 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003504 // conversion of B* to A* is better than conversion of B* to
3505 // void*, and conversion of A* to void* is better than conversion
3506 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003507 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003508 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003509 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003510 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003511 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3512 // Exactly one of the conversion sequences is a conversion to
3513 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003514 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3515 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003516 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3517 // Neither conversion sequence converts to a void pointer; compare
3518 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003519 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003520 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003521 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003522 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3523 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003524 // Both conversion sequences are conversions to void
3525 // pointers. Compare the source types to determine if there's an
3526 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003527 QualType FromType1 = SCS1.getFromType();
3528 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003529
3530 // Adjust the types we're converting from via the array-to-pointer
3531 // conversion, if we need to.
3532 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003533 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003534 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003535 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003536
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003537 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3538 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003539
John McCall120d63c2010-08-24 20:38:10 +00003540 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003541 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003542 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003543 return ImplicitConversionSequence::Worse;
3544
3545 // Objective-C++: If one interface is more specific than the
3546 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003547 const ObjCObjectPointerType* FromObjCPtr1
3548 = FromType1->getAs<ObjCObjectPointerType>();
3549 const ObjCObjectPointerType* FromObjCPtr2
3550 = FromType2->getAs<ObjCObjectPointerType>();
3551 if (FromObjCPtr1 && FromObjCPtr2) {
3552 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3553 FromObjCPtr2);
3554 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3555 FromObjCPtr1);
3556 if (AssignLeft != AssignRight) {
3557 return AssignLeft? ImplicitConversionSequence::Better
3558 : ImplicitConversionSequence::Worse;
3559 }
Douglas Gregor01919692009-12-13 21:37:05 +00003560 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003561 }
Douglas Gregor57373262008-10-22 14:17:15 +00003562
3563 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3564 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003565 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003566 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003567 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003568
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003569 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003570 // Check for a better reference binding based on the kind of bindings.
3571 if (isBetterReferenceBindingKind(SCS1, SCS2))
3572 return ImplicitConversionSequence::Better;
3573 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3574 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003576 // C++ [over.ics.rank]p3b4:
3577 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3578 // which the references refer are the same type except for
3579 // top-level cv-qualifiers, and the type to which the reference
3580 // initialized by S2 refers is more cv-qualified than the type
3581 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003582 QualType T1 = SCS1.getToType(2);
3583 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003584 T1 = S.Context.getCanonicalType(T1);
3585 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003586 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003587 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3588 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003589 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003590 // Objective-C++ ARC: If the references refer to objects with different
3591 // lifetimes, prefer bindings that don't change lifetime.
3592 if (SCS1.ObjCLifetimeConversionBinding !=
3593 SCS2.ObjCLifetimeConversionBinding) {
3594 return SCS1.ObjCLifetimeConversionBinding
3595 ? ImplicitConversionSequence::Worse
3596 : ImplicitConversionSequence::Better;
3597 }
3598
Chandler Carruth6df868e2010-12-12 08:17:55 +00003599 // If the type is an array type, promote the element qualifiers to the
3600 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003601 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003602 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003603 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003604 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003605 if (T2.isMoreQualifiedThan(T1))
3606 return ImplicitConversionSequence::Better;
3607 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003608 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003609 }
3610 }
Douglas Gregor57373262008-10-22 14:17:15 +00003611
Francois Pichet1c98d622011-09-18 21:37:37 +00003612 // In Microsoft mode, prefer an integral conversion to a
3613 // floating-to-integral conversion if the integral conversion
3614 // is between types of the same size.
3615 // For example:
3616 // void f(float);
3617 // void f(int);
3618 // int main {
3619 // long a;
3620 // f(a);
3621 // }
3622 // Here, MSVC will call f(int) instead of generating a compile error
3623 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003624 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003625 SCS1.Second == ICK_Integral_Conversion &&
3626 SCS2.Second == ICK_Floating_Integral &&
3627 S.Context.getTypeSize(SCS1.getFromType()) ==
3628 S.Context.getTypeSize(SCS1.getToType(2)))
3629 return ImplicitConversionSequence::Better;
3630
Douglas Gregor57373262008-10-22 14:17:15 +00003631 return ImplicitConversionSequence::Indistinguishable;
3632}
3633
3634/// CompareQualificationConversions - Compares two standard conversion
3635/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003636/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3637ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003638CompareQualificationConversions(Sema &S,
3639 const StandardConversionSequence& SCS1,
3640 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003641 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003642 // -- S1 and S2 differ only in their qualification conversion and
3643 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3644 // cv-qualification signature of type T1 is a proper subset of
3645 // the cv-qualification signature of type T2, and S1 is not the
3646 // deprecated string literal array-to-pointer conversion (4.2).
3647 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3648 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3649 return ImplicitConversionSequence::Indistinguishable;
3650
3651 // FIXME: the example in the standard doesn't use a qualification
3652 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003653 QualType T1 = SCS1.getToType(2);
3654 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003655 T1 = S.Context.getCanonicalType(T1);
3656 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003657 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003658 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3659 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003660
3661 // If the types are the same, we won't learn anything by unwrapped
3662 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003663 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003664 return ImplicitConversionSequence::Indistinguishable;
3665
Chandler Carruth28e318c2009-12-29 07:16:59 +00003666 // If the type is an array type, promote the element qualifiers to the type
3667 // for comparison.
3668 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003669 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003670 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003671 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003672
Mike Stump1eb44332009-09-09 15:08:12 +00003673 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003674 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003675
3676 // Objective-C++ ARC:
3677 // Prefer qualification conversions not involving a change in lifetime
3678 // to qualification conversions that do not change lifetime.
3679 if (SCS1.QualificationIncludesObjCLifetime !=
3680 SCS2.QualificationIncludesObjCLifetime) {
3681 Result = SCS1.QualificationIncludesObjCLifetime
3682 ? ImplicitConversionSequence::Worse
3683 : ImplicitConversionSequence::Better;
3684 }
3685
John McCall120d63c2010-08-24 20:38:10 +00003686 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003687 // Within each iteration of the loop, we check the qualifiers to
3688 // determine if this still looks like a qualification
3689 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003690 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003691 // until there are no more pointers or pointers-to-members left
3692 // to unwrap. This essentially mimics what
3693 // IsQualificationConversion does, but here we're checking for a
3694 // strict subset of qualifiers.
3695 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3696 // The qualifiers are the same, so this doesn't tell us anything
3697 // about how the sequences rank.
3698 ;
3699 else if (T2.isMoreQualifiedThan(T1)) {
3700 // T1 has fewer qualifiers, so it could be the better sequence.
3701 if (Result == ImplicitConversionSequence::Worse)
3702 // Neither has qualifiers that are a subset of the other's
3703 // qualifiers.
3704 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Douglas Gregor57373262008-10-22 14:17:15 +00003706 Result = ImplicitConversionSequence::Better;
3707 } else if (T1.isMoreQualifiedThan(T2)) {
3708 // T2 has fewer qualifiers, so it could be the better sequence.
3709 if (Result == ImplicitConversionSequence::Better)
3710 // Neither has qualifiers that are a subset of the other's
3711 // qualifiers.
3712 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Douglas Gregor57373262008-10-22 14:17:15 +00003714 Result = ImplicitConversionSequence::Worse;
3715 } else {
3716 // Qualifiers are disjoint.
3717 return ImplicitConversionSequence::Indistinguishable;
3718 }
3719
3720 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003721 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003722 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003723 }
3724
Douglas Gregor57373262008-10-22 14:17:15 +00003725 // Check that the winning standard conversion sequence isn't using
3726 // the deprecated string literal array to pointer conversion.
3727 switch (Result) {
3728 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003729 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003730 Result = ImplicitConversionSequence::Indistinguishable;
3731 break;
3732
3733 case ImplicitConversionSequence::Indistinguishable:
3734 break;
3735
3736 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003737 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003738 Result = ImplicitConversionSequence::Indistinguishable;
3739 break;
3740 }
3741
3742 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003743}
3744
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003745/// CompareDerivedToBaseConversions - Compares two standard conversion
3746/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003747/// various kinds of derived-to-base conversions (C++
3748/// [over.ics.rank]p4b3). As part of these checks, we also look at
3749/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003750ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003751CompareDerivedToBaseConversions(Sema &S,
3752 const StandardConversionSequence& SCS1,
3753 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003754 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003755 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003756 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003757 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003758
3759 // Adjust the types we're converting from via the array-to-pointer
3760 // conversion, if we need to.
3761 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003762 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003763 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003764 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003765
3766 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003767 FromType1 = S.Context.getCanonicalType(FromType1);
3768 ToType1 = S.Context.getCanonicalType(ToType1);
3769 FromType2 = S.Context.getCanonicalType(FromType2);
3770 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003771
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003772 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003773 //
3774 // If class B is derived directly or indirectly from class A and
3775 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003776 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003777 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003778 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003779 SCS2.Second == ICK_Pointer_Conversion &&
3780 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3781 FromType1->isPointerType() && FromType2->isPointerType() &&
3782 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003783 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003784 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003785 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003786 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003787 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003788 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003789 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003790 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003791
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003792 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003793 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003794 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003795 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003796 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003797 return ImplicitConversionSequence::Worse;
3798 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003799
3800 // -- conversion of B* to A* is better than conversion of C* to A*,
3801 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003802 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003803 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003804 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003805 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003806 }
3807 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3808 SCS2.Second == ICK_Pointer_Conversion) {
3809 const ObjCObjectPointerType *FromPtr1
3810 = FromType1->getAs<ObjCObjectPointerType>();
3811 const ObjCObjectPointerType *FromPtr2
3812 = FromType2->getAs<ObjCObjectPointerType>();
3813 const ObjCObjectPointerType *ToPtr1
3814 = ToType1->getAs<ObjCObjectPointerType>();
3815 const ObjCObjectPointerType *ToPtr2
3816 = ToType2->getAs<ObjCObjectPointerType>();
3817
3818 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3819 // Apply the same conversion ranking rules for Objective-C pointer types
3820 // that we do for C++ pointers to class types. However, we employ the
3821 // Objective-C pseudo-subtyping relationship used for assignment of
3822 // Objective-C pointer types.
3823 bool FromAssignLeft
3824 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3825 bool FromAssignRight
3826 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3827 bool ToAssignLeft
3828 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3829 bool ToAssignRight
3830 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3831
3832 // A conversion to an a non-id object pointer type or qualified 'id'
3833 // type is better than a conversion to 'id'.
3834 if (ToPtr1->isObjCIdType() &&
3835 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3836 return ImplicitConversionSequence::Worse;
3837 if (ToPtr2->isObjCIdType() &&
3838 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3839 return ImplicitConversionSequence::Better;
3840
3841 // A conversion to a non-id object pointer type is better than a
3842 // conversion to a qualified 'id' type
3843 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3844 return ImplicitConversionSequence::Worse;
3845 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3846 return ImplicitConversionSequence::Better;
3847
3848 // A conversion to an a non-Class object pointer type or qualified 'Class'
3849 // type is better than a conversion to 'Class'.
3850 if (ToPtr1->isObjCClassType() &&
3851 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3852 return ImplicitConversionSequence::Worse;
3853 if (ToPtr2->isObjCClassType() &&
3854 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3855 return ImplicitConversionSequence::Better;
3856
3857 // A conversion to a non-Class object pointer type is better than a
3858 // conversion to a qualified 'Class' type.
3859 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3860 return ImplicitConversionSequence::Worse;
3861 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3862 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Douglas Gregor395cc372011-01-31 18:51:41 +00003864 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3865 if (S.Context.hasSameType(FromType1, FromType2) &&
3866 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3867 (ToAssignLeft != ToAssignRight))
3868 return ToAssignLeft? ImplicitConversionSequence::Worse
3869 : ImplicitConversionSequence::Better;
3870
3871 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3872 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3873 (FromAssignLeft != FromAssignRight))
3874 return FromAssignLeft? ImplicitConversionSequence::Better
3875 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003876 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003877 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003878
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003879 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003880 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3881 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3882 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003883 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003884 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003886 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003888 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003889 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003890 ToType2->getAs<MemberPointerType>();
3891 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3892 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3893 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3894 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3895 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3896 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3897 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3898 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003899 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003900 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003901 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003902 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003903 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003904 return ImplicitConversionSequence::Better;
3905 }
3906 // conversion of B::* to C::* is better than conversion of A::* to C::*
3907 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003908 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003909 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003910 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003911 return ImplicitConversionSequence::Worse;
3912 }
3913 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003915 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003916 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003917 // -- binding of an expression of type C to a reference of type
3918 // B& is better than binding an expression of type C to a
3919 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003920 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3921 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3922 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003923 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003924 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003925 return ImplicitConversionSequence::Worse;
3926 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003927
Douglas Gregor225c41e2008-11-03 19:09:14 +00003928 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003929 // -- binding of an expression of type B to a reference of type
3930 // A& is better than binding an expression of type C to a
3931 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003932 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3933 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3934 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003935 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003936 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003937 return ImplicitConversionSequence::Worse;
3938 }
3939 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003940
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003941 return ImplicitConversionSequence::Indistinguishable;
3942}
3943
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003944/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3945/// C++ class.
3946static bool isTypeValid(QualType T) {
3947 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3948 return !Record->isInvalidDecl();
3949
3950 return true;
3951}
3952
Douglas Gregorabe183d2010-04-13 16:31:36 +00003953/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3954/// determine whether they are reference-related,
3955/// reference-compatible, reference-compatible with added
3956/// qualification, or incompatible, for use in C++ initialization by
3957/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3958/// type, and the first type (T1) is the pointee type of the reference
3959/// type being initialized.
3960Sema::ReferenceCompareResult
3961Sema::CompareReferenceRelationship(SourceLocation Loc,
3962 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003963 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003964 bool &ObjCConversion,
3965 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003966 assert(!OrigT1->isReferenceType() &&
3967 "T1 must be the pointee type of the reference type");
3968 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3969
3970 QualType T1 = Context.getCanonicalType(OrigT1);
3971 QualType T2 = Context.getCanonicalType(OrigT2);
3972 Qualifiers T1Quals, T2Quals;
3973 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3974 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3975
3976 // C++ [dcl.init.ref]p4:
3977 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3978 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3979 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003980 DerivedToBase = false;
3981 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003982 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003983 if (UnqualT1 == UnqualT2) {
3984 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003985 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003986 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3987 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003988 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003989 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3990 UnqualT2->isObjCObjectOrInterfaceType() &&
3991 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3992 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003993 else
3994 return Ref_Incompatible;
3995
3996 // At this point, we know that T1 and T2 are reference-related (at
3997 // least).
3998
3999 // If the type is an array type, promote the element qualifiers to the type
4000 // for comparison.
4001 if (isa<ArrayType>(T1) && T1Quals)
4002 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4003 if (isa<ArrayType>(T2) && T2Quals)
4004 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4005
4006 // C++ [dcl.init.ref]p4:
4007 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4008 // reference-related to T2 and cv1 is the same cv-qualification
4009 // as, or greater cv-qualification than, cv2. For purposes of
4010 // overload resolution, cases for which cv1 is greater
4011 // cv-qualification than cv2 are identified as
4012 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004013 //
4014 // Note that we also require equivalence of Objective-C GC and address-space
4015 // qualifiers when performing these computations, so that e.g., an int in
4016 // address space 1 is not reference-compatible with an int in address
4017 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00004018 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4019 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4020 T1Quals.removeObjCLifetime();
4021 T2Quals.removeObjCLifetime();
4022 ObjCLifetimeConversion = true;
4023 }
4024
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004025 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004026 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004027 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004028 return Ref_Compatible_With_Added_Qualification;
4029 else
4030 return Ref_Related;
4031}
4032
Douglas Gregor604eb652010-08-11 02:15:33 +00004033/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004034/// with DeclType. Return true if something definite is found.
4035static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004036FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4037 QualType DeclType, SourceLocation DeclLoc,
4038 Expr *Init, QualType T2, bool AllowRvalues,
4039 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004040 assert(T2->isRecordType() && "Can only find conversions of record types.");
4041 CXXRecordDecl *T2RecordDecl
4042 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4043
4044 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004045 std::pair<CXXRecordDecl::conversion_iterator,
4046 CXXRecordDecl::conversion_iterator>
4047 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4048 for (CXXRecordDecl::conversion_iterator
4049 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004050 NamedDecl *D = *I;
4051 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4052 if (isa<UsingShadowDecl>(D))
4053 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4054
4055 FunctionTemplateDecl *ConvTemplate
4056 = dyn_cast<FunctionTemplateDecl>(D);
4057 CXXConversionDecl *Conv;
4058 if (ConvTemplate)
4059 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4060 else
4061 Conv = cast<CXXConversionDecl>(D);
4062
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004064 // explicit conversions, skip it.
4065 if (!AllowExplicit && Conv->isExplicit())
4066 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004067
Douglas Gregor604eb652010-08-11 02:15:33 +00004068 if (AllowRvalues) {
4069 bool DerivedToBase = false;
4070 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004071 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004072
4073 // If we are initializing an rvalue reference, don't permit conversion
4074 // functions that return lvalues.
4075 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4076 const ReferenceType *RefType
4077 = Conv->getConversionType()->getAs<LValueReferenceType>();
4078 if (RefType && !RefType->getPointeeType()->isFunctionType())
4079 continue;
4080 }
4081
Douglas Gregor604eb652010-08-11 02:15:33 +00004082 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004083 S.CompareReferenceRelationship(
4084 DeclLoc,
4085 Conv->getConversionType().getNonReferenceType()
4086 .getUnqualifiedType(),
4087 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004088 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004089 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004090 continue;
4091 } else {
4092 // If the conversion function doesn't return a reference type,
4093 // it can't be considered for this conversion. An rvalue reference
4094 // is only acceptable if its referencee is a function type.
4095
4096 const ReferenceType *RefType =
4097 Conv->getConversionType()->getAs<ReferenceType>();
4098 if (!RefType ||
4099 (!RefType->isLValueReferenceType() &&
4100 !RefType->getPointeeType()->isFunctionType()))
4101 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004102 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004103
Douglas Gregor604eb652010-08-11 02:15:33 +00004104 if (ConvTemplate)
4105 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004106 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004107 else
4108 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004109 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004110 }
4111
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004112 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4113
Sebastian Redl4680bf22010-06-30 18:13:39 +00004114 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004115 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004116 case OR_Success:
4117 // C++ [over.ics.ref]p1:
4118 //
4119 // [...] If the parameter binds directly to the result of
4120 // applying a conversion function to the argument
4121 // expression, the implicit conversion sequence is a
4122 // user-defined conversion sequence (13.3.3.1.2), with the
4123 // second standard conversion sequence either an identity
4124 // conversion or, if the conversion function returns an
4125 // entity of a type that is a derived class of the parameter
4126 // type, a derived-to-base Conversion.
4127 if (!Best->FinalConversion.DirectBinding)
4128 return false;
4129
4130 ICS.setUserDefined();
4131 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4132 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004133 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004134 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004135 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004136 ICS.UserDefined.EllipsisConversion = false;
4137 assert(ICS.UserDefined.After.ReferenceBinding &&
4138 ICS.UserDefined.After.DirectBinding &&
4139 "Expected a direct reference binding!");
4140 return true;
4141
4142 case OR_Ambiguous:
4143 ICS.setAmbiguous();
4144 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4145 Cand != CandidateSet.end(); ++Cand)
4146 if (Cand->Viable)
4147 ICS.Ambiguous.addConversion(Cand->Function);
4148 return true;
4149
4150 case OR_No_Viable_Function:
4151 case OR_Deleted:
4152 // There was no suitable conversion, or we found a deleted
4153 // conversion; continue with other checks.
4154 return false;
4155 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004156
David Blaikie7530c032012-01-17 06:56:22 +00004157 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004158}
4159
Douglas Gregorabe183d2010-04-13 16:31:36 +00004160/// \brief Compute an implicit conversion sequence for reference
4161/// initialization.
4162static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004163TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004164 SourceLocation DeclLoc,
4165 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004166 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004167 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4168
4169 // Most paths end in a failed conversion.
4170 ImplicitConversionSequence ICS;
4171 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4172
4173 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4174 QualType T2 = Init->getType();
4175
4176 // If the initializer is the address of an overloaded function, try
4177 // to resolve the overloaded function. If all goes well, T2 is the
4178 // type of the resulting function.
4179 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4180 DeclAccessPair Found;
4181 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4182 false, Found))
4183 T2 = Fn->getType();
4184 }
4185
4186 // Compute some basic properties of the types and the initializer.
4187 bool isRValRef = DeclType->isRValueReferenceType();
4188 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004189 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004190 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004191 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004192 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004193 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004194 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004195
Douglas Gregorabe183d2010-04-13 16:31:36 +00004196
Sebastian Redl4680bf22010-06-30 18:13:39 +00004197 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004198 // A reference to type "cv1 T1" is initialized by an expression
4199 // of type "cv2 T2" as follows:
4200
Sebastian Redl4680bf22010-06-30 18:13:39 +00004201 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004202 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004203 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4204 // reference-compatible with "cv2 T2," or
4205 //
4206 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4207 if (InitCategory.isLValue() &&
4208 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004209 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004210 // When a parameter of reference type binds directly (8.5.3)
4211 // to an argument expression, the implicit conversion sequence
4212 // is the identity conversion, unless the argument expression
4213 // has a type that is a derived class of the parameter type,
4214 // in which case the implicit conversion sequence is a
4215 // derived-to-base Conversion (13.3.3.1).
4216 ICS.setStandard();
4217 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004218 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4219 : ObjCConversion? ICK_Compatible_Conversion
4220 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004221 ICS.Standard.Third = ICK_Identity;
4222 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4223 ICS.Standard.setToType(0, T2);
4224 ICS.Standard.setToType(1, T1);
4225 ICS.Standard.setToType(2, T1);
4226 ICS.Standard.ReferenceBinding = true;
4227 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004228 ICS.Standard.IsLvalueReference = !isRValRef;
4229 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4230 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004231 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004232 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004233 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004234
Sebastian Redl4680bf22010-06-30 18:13:39 +00004235 // Nothing more to do: the inaccessibility/ambiguity check for
4236 // derived-to-base conversions is suppressed when we're
4237 // computing the implicit conversion sequence (C++
4238 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004239 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004240 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004241
Sebastian Redl4680bf22010-06-30 18:13:39 +00004242 // -- has a class type (i.e., T2 is a class type), where T1 is
4243 // not reference-related to T2, and can be implicitly
4244 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4245 // is reference-compatible with "cv3 T3" 92) (this
4246 // conversion is selected by enumerating the applicable
4247 // conversion functions (13.3.1.6) and choosing the best
4248 // one through overload resolution (13.3)),
4249 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004250 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004251 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004252 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4253 Init, T2, /*AllowRvalues=*/false,
4254 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004255 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004256 }
4257 }
4258
Sebastian Redl4680bf22010-06-30 18:13:39 +00004259 // -- Otherwise, the reference shall be an lvalue reference to a
4260 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004261 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004262 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004263 // We actually handle one oddity of C++ [over.ics.ref] at this
4264 // point, which is that, due to p2 (which short-circuits reference
4265 // binding by only attempting a simple conversion for non-direct
4266 // bindings) and p3's strange wording, we allow a const volatile
4267 // reference to bind to an rvalue. Hence the check for the presence
4268 // of "const" rather than checking for "const" being the only
4269 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004270 // This is also the point where rvalue references and lvalue inits no longer
4271 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004272 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004273 return ICS;
4274
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004275 // -- If the initializer expression
4276 //
4277 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004278 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004279 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4280 (InitCategory.isXValue() ||
4281 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4282 (InitCategory.isLValue() && T2->isFunctionType()))) {
4283 ICS.setStandard();
4284 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004286 : ObjCConversion? ICK_Compatible_Conversion
4287 : ICK_Identity;
4288 ICS.Standard.Third = ICK_Identity;
4289 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4290 ICS.Standard.setToType(0, T2);
4291 ICS.Standard.setToType(1, T1);
4292 ICS.Standard.setToType(2, T1);
4293 ICS.Standard.ReferenceBinding = true;
4294 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4295 // binding unless we're binding to a class prvalue.
4296 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4297 // allow the use of rvalue references in C++98/03 for the benefit of
4298 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004299 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004300 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004301 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004302 ICS.Standard.IsLvalueReference = !isRValRef;
4303 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004304 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004305 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004306 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004307 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004309 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004310
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004311 // -- has a class type (i.e., T2 is a class type), where T1 is not
4312 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313 // an xvalue, class prvalue, or function lvalue of type
4314 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004315 // "cv3 T3",
4316 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004317 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004318 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004319 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004320 // class subobject).
4321 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004322 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004323 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4324 Init, T2, /*AllowRvalues=*/true,
4325 AllowExplicit)) {
4326 // In the second case, if the reference is an rvalue reference
4327 // and the second standard conversion sequence of the
4328 // user-defined conversion sequence includes an lvalue-to-rvalue
4329 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004330 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004331 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4332 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4333
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004334 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004335 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004336
Douglas Gregorabe183d2010-04-13 16:31:36 +00004337 // -- Otherwise, a temporary of type "cv1 T1" is created and
4338 // initialized from the initializer expression using the
4339 // rules for a non-reference copy initialization (8.5). The
4340 // reference is then bound to the temporary. If T1 is
4341 // reference-related to T2, cv1 must be the same
4342 // cv-qualification as, or greater cv-qualification than,
4343 // cv2; otherwise, the program is ill-formed.
4344 if (RefRelationship == Sema::Ref_Related) {
4345 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4346 // we would be reference-compatible or reference-compatible with
4347 // added qualification. But that wasn't the case, so the reference
4348 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004349 //
4350 // Note that we only want to check address spaces and cvr-qualifiers here.
4351 // ObjC GC and lifetime qualifiers aren't important.
4352 Qualifiers T1Quals = T1.getQualifiers();
4353 Qualifiers T2Quals = T2.getQualifiers();
4354 T1Quals.removeObjCGCAttr();
4355 T1Quals.removeObjCLifetime();
4356 T2Quals.removeObjCGCAttr();
4357 T2Quals.removeObjCLifetime();
4358 if (!T1Quals.compatiblyIncludes(T2Quals))
4359 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004360 }
4361
4362 // If at least one of the types is a class type, the types are not
4363 // related, and we aren't allowed any user conversions, the
4364 // reference binding fails. This case is important for breaking
4365 // recursion, since TryImplicitConversion below will attempt to
4366 // create a temporary through the use of a copy constructor.
4367 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4368 (T1->isRecordType() || T2->isRecordType()))
4369 return ICS;
4370
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004371 // If T1 is reference-related to T2 and the reference is an rvalue
4372 // reference, the initializer expression shall not be an lvalue.
4373 if (RefRelationship >= Sema::Ref_Related &&
4374 isRValRef && Init->Classify(S.Context).isLValue())
4375 return ICS;
4376
Douglas Gregorabe183d2010-04-13 16:31:36 +00004377 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004378 // When a parameter of reference type is not bound directly to
4379 // an argument expression, the conversion sequence is the one
4380 // required to convert the argument expression to the
4381 // underlying type of the reference according to
4382 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4383 // to copy-initializing a temporary of the underlying type with
4384 // the argument expression. Any difference in top-level
4385 // cv-qualification is subsumed by the initialization itself
4386 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004387 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4388 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004389 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004390 /*CStyle=*/false,
4391 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004392
4393 // Of course, that's still a reference binding.
4394 if (ICS.isStandard()) {
4395 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004396 ICS.Standard.IsLvalueReference = !isRValRef;
4397 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4398 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004399 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004400 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004401 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004402 // Don't allow rvalue references to bind to lvalues.
4403 if (DeclType->isRValueReferenceType()) {
4404 if (const ReferenceType *RefType
4405 = ICS.UserDefined.ConversionFunction->getResultType()
4406 ->getAs<LValueReferenceType>()) {
4407 if (!RefType->getPointeeType()->isFunctionType()) {
4408 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4409 DeclType);
4410 return ICS;
4411 }
4412 }
4413 }
4414
Douglas Gregorabe183d2010-04-13 16:31:36 +00004415 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004416 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4417 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4418 ICS.UserDefined.After.BindsToRvalue = true;
4419 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4420 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004421 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004422
Douglas Gregorabe183d2010-04-13 16:31:36 +00004423 return ICS;
4424}
4425
Sebastian Redl5405b812011-10-16 18:19:34 +00004426static ImplicitConversionSequence
4427TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4428 bool SuppressUserConversions,
4429 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004430 bool AllowObjCWritebackConversion,
4431 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004432
4433/// TryListConversion - Try to copy-initialize a value of type ToType from the
4434/// initializer list From.
4435static ImplicitConversionSequence
4436TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4437 bool SuppressUserConversions,
4438 bool InOverloadResolution,
4439 bool AllowObjCWritebackConversion) {
4440 // C++11 [over.ics.list]p1:
4441 // When an argument is an initializer list, it is not an expression and
4442 // special rules apply for converting it to a parameter type.
4443
4444 ImplicitConversionSequence Result;
4445 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004446 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004447
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004448 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004449 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004450 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004451 return Result;
4452
Sebastian Redl5405b812011-10-16 18:19:34 +00004453 // C++11 [over.ics.list]p2:
4454 // If the parameter type is std::initializer_list<X> or "array of X" and
4455 // all the elements can be implicitly converted to X, the implicit
4456 // conversion sequence is the worst conversion necessary to convert an
4457 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004458 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004459 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004460 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004461 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004462 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004463 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004464 if (!X.isNull()) {
4465 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4466 Expr *Init = From->getInit(i);
4467 ImplicitConversionSequence ICS =
4468 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4469 InOverloadResolution,
4470 AllowObjCWritebackConversion);
4471 // If a single element isn't convertible, fail.
4472 if (ICS.isBad()) {
4473 Result = ICS;
4474 break;
4475 }
4476 // Otherwise, look for the worst conversion.
4477 if (Result.isBad() ||
4478 CompareImplicitConversionSequences(S, ICS, Result) ==
4479 ImplicitConversionSequence::Worse)
4480 Result = ICS;
4481 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004482
4483 // For an empty list, we won't have computed any conversion sequence.
4484 // Introduce the identity conversion sequence.
4485 if (From->getNumInits() == 0) {
4486 Result.setStandard();
4487 Result.Standard.setAsIdentityConversion();
4488 Result.Standard.setFromType(ToType);
4489 Result.Standard.setAllToTypes(ToType);
4490 }
4491
Sebastian Redlfe592282012-01-17 22:49:48 +00004492 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004493 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004494 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004495 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004496
4497 // C++11 [over.ics.list]p3:
4498 // Otherwise, if the parameter is a non-aggregate class X and overload
4499 // resolution chooses a single best constructor [...] the implicit
4500 // conversion sequence is a user-defined conversion sequence. If multiple
4501 // constructors are viable but none is better than the others, the
4502 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004503 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4504 // This function can deal with initializer lists.
4505 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4506 /*AllowExplicit=*/false,
4507 InOverloadResolution, /*CStyle=*/false,
4508 AllowObjCWritebackConversion);
4509 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004510 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004511 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004512
4513 // C++11 [over.ics.list]p4:
4514 // Otherwise, if the parameter has an aggregate type which can be
4515 // initialized from the initializer list [...] the implicit conversion
4516 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004517 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004518 // Type is an aggregate, argument is an init list. At this point it comes
4519 // down to checking whether the initialization works.
4520 // FIXME: Find out whether this parameter is consumed or not.
4521 InitializedEntity Entity =
4522 InitializedEntity::InitializeParameter(S.Context, ToType,
4523 /*Consumed=*/false);
4524 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4525 Result.setUserDefined();
4526 Result.UserDefined.Before.setAsIdentityConversion();
4527 // Initializer lists don't have a type.
4528 Result.UserDefined.Before.setFromType(QualType());
4529 Result.UserDefined.Before.setAllToTypes(QualType());
4530
4531 Result.UserDefined.After.setAsIdentityConversion();
4532 Result.UserDefined.After.setFromType(ToType);
4533 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004534 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004535 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004536 return Result;
4537 }
4538
4539 // C++11 [over.ics.list]p5:
4540 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004541 if (ToType->isReferenceType()) {
4542 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4543 // mention initializer lists in any way. So we go by what list-
4544 // initialization would do and try to extrapolate from that.
4545
4546 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4547
4548 // If the initializer list has a single element that is reference-related
4549 // to the parameter type, we initialize the reference from that.
4550 if (From->getNumInits() == 1) {
4551 Expr *Init = From->getInit(0);
4552
4553 QualType T2 = Init->getType();
4554
4555 // If the initializer is the address of an overloaded function, try
4556 // to resolve the overloaded function. If all goes well, T2 is the
4557 // type of the resulting function.
4558 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4559 DeclAccessPair Found;
4560 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4561 Init, ToType, false, Found))
4562 T2 = Fn->getType();
4563 }
4564
4565 // Compute some basic properties of the types and the initializer.
4566 bool dummy1 = false;
4567 bool dummy2 = false;
4568 bool dummy3 = false;
4569 Sema::ReferenceCompareResult RefRelationship
4570 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4571 dummy2, dummy3);
4572
4573 if (RefRelationship >= Sema::Ref_Related)
4574 return TryReferenceInit(S, Init, ToType,
4575 /*FIXME:*/From->getLocStart(),
4576 SuppressUserConversions,
4577 /*AllowExplicit=*/false);
4578 }
4579
4580 // Otherwise, we bind the reference to a temporary created from the
4581 // initializer list.
4582 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4583 InOverloadResolution,
4584 AllowObjCWritebackConversion);
4585 if (Result.isFailure())
4586 return Result;
4587 assert(!Result.isEllipsis() &&
4588 "Sub-initialization cannot result in ellipsis conversion.");
4589
4590 // Can we even bind to a temporary?
4591 if (ToType->isRValueReferenceType() ||
4592 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4593 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4594 Result.UserDefined.After;
4595 SCS.ReferenceBinding = true;
4596 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4597 SCS.BindsToRvalue = true;
4598 SCS.BindsToFunctionLvalue = false;
4599 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4600 SCS.ObjCLifetimeConversionBinding = false;
4601 } else
4602 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4603 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004604 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004605 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004606
4607 // C++11 [over.ics.list]p6:
4608 // Otherwise, if the parameter type is not a class:
4609 if (!ToType->isRecordType()) {
4610 // - if the initializer list has one element, the implicit conversion
4611 // sequence is the one required to convert the element to the
4612 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004613 unsigned NumInits = From->getNumInits();
4614 if (NumInits == 1)
4615 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4616 SuppressUserConversions,
4617 InOverloadResolution,
4618 AllowObjCWritebackConversion);
4619 // - if the initializer list has no elements, the implicit conversion
4620 // sequence is the identity conversion.
4621 else if (NumInits == 0) {
4622 Result.setStandard();
4623 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004624 Result.Standard.setFromType(ToType);
4625 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004626 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004627 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004628 return Result;
4629 }
4630
4631 // C++11 [over.ics.list]p7:
4632 // In all cases other than those enumerated above, no conversion is possible
4633 return Result;
4634}
4635
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004636/// TryCopyInitialization - Try to copy-initialize a value of type
4637/// ToType from the expression From. Return the implicit conversion
4638/// sequence required to pass this argument, which may be a bad
4639/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004640/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004641/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004642static ImplicitConversionSequence
4643TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004644 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004645 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004646 bool AllowObjCWritebackConversion,
4647 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004648 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4649 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4650 InOverloadResolution,AllowObjCWritebackConversion);
4651
Douglas Gregorabe183d2010-04-13 16:31:36 +00004652 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004653 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004654 /*FIXME:*/From->getLocStart(),
4655 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004656 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004657
John McCall120d63c2010-08-24 20:38:10 +00004658 return TryImplicitConversion(S, From, ToType,
4659 SuppressUserConversions,
4660 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004661 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004662 /*CStyle=*/false,
4663 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004664}
4665
Anna Zaksf3546ee2011-07-28 19:46:48 +00004666static bool TryCopyInitialization(const CanQualType FromQTy,
4667 const CanQualType ToQTy,
4668 Sema &S,
4669 SourceLocation Loc,
4670 ExprValueKind FromVK) {
4671 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4672 ImplicitConversionSequence ICS =
4673 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4674
4675 return !ICS.isBad();
4676}
4677
Douglas Gregor96176b32008-11-18 23:14:02 +00004678/// TryObjectArgumentInitialization - Try to initialize the object
4679/// parameter of the given member function (@c Method) from the
4680/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004681static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004682TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004683 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004684 CXXMethodDecl *Method,
4685 CXXRecordDecl *ActingContext) {
4686 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004687 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4688 // const volatile object.
4689 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4690 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004691 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004692
4693 // Set up the conversion sequence as a "bad" conversion, to allow us
4694 // to exit early.
4695 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004696
4697 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004698 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004699 FromType = PT->getPointeeType();
4700
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004701 // When we had a pointer, it's implicitly dereferenced, so we
4702 // better have an lvalue.
4703 assert(FromClassification.isLValue());
4704 }
4705
Anders Carlssona552f7c2009-05-01 18:34:30 +00004706 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004707
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004708 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004709 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004710 // parameter is
4711 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004712 // - "lvalue reference to cv X" for functions declared without a
4713 // ref-qualifier or with the & ref-qualifier
4714 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004715 // ref-qualifier
4716 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004718 // cv-qualification on the member function declaration.
4719 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004720 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004721 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004722 // (C++ [over.match.funcs]p5). We perform a simplified version of
4723 // reference binding here, that allows class rvalues to bind to
4724 // non-constant references.
4725
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004726 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004727 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004729 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004730 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004731 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004732 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004733 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004734 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004735
4736 // Check that we have either the same type or a derived type. It
4737 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004738 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004739 ImplicitConversionKind SecondKind;
4740 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4741 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004742 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004743 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004744 else {
John McCallb1bdc622010-02-25 01:37:24 +00004745 ICS.setBad(BadConversionSequence::unrelated_class,
4746 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004747 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004748 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004749
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004750 // Check the ref-qualifier.
4751 switch (Method->getRefQualifier()) {
4752 case RQ_None:
4753 // Do nothing; we don't care about lvalueness or rvalueness.
4754 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004755
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004756 case RQ_LValue:
4757 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4758 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004759 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004760 ImplicitParamType);
4761 return ICS;
4762 }
4763 break;
4764
4765 case RQ_RValue:
4766 if (!FromClassification.isRValue()) {
4767 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004768 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004769 ImplicitParamType);
4770 return ICS;
4771 }
4772 break;
4773 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004774
Douglas Gregor96176b32008-11-18 23:14:02 +00004775 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004776 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004777 ICS.Standard.setAsIdentityConversion();
4778 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004779 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004780 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004781 ICS.Standard.ReferenceBinding = true;
4782 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004783 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004784 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004785 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4786 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4787 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004788 return ICS;
4789}
4790
4791/// PerformObjectArgumentInitialization - Perform initialization of
4792/// the implicit object parameter for the given Method with the given
4793/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004794ExprResult
4795Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004796 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004797 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004798 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004799 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004800 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004801 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004803 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004804 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004805 FromRecordType = PT->getPointeeType();
4806 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004807 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004808 } else {
4809 FromRecordType = From->getType();
4810 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004811 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004812 }
4813
John McCall701c89e2009-12-03 04:06:58 +00004814 // Note that we always use the true parent context when performing
4815 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004816 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004817 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4818 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004819 if (ICS.isBad()) {
4820 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4821 Qualifiers FromQs = FromRecordType.getQualifiers();
4822 Qualifiers ToQs = DestType.getQualifiers();
4823 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4824 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004825 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004826 diag::err_member_function_call_bad_cvr)
4827 << Method->getDeclName() << FromRecordType << (CVR - 1)
4828 << From->getSourceRange();
4829 Diag(Method->getLocation(), diag::note_previous_decl)
4830 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004831 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004832 }
4833 }
4834
Daniel Dunbar96a00142012-03-09 18:35:03 +00004835 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004836 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004837 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004838 }
Mike Stump1eb44332009-09-09 15:08:12 +00004839
John Wiegley429bb272011-04-08 18:41:53 +00004840 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4841 ExprResult FromRes =
4842 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4843 if (FromRes.isInvalid())
4844 return ExprError();
4845 From = FromRes.take();
4846 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004847
Douglas Gregor5fccd362010-03-03 23:55:11 +00004848 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004849 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004850 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004851 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004852}
4853
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004854/// TryContextuallyConvertToBool - Attempt to contextually convert the
4855/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004856static ImplicitConversionSequence
4857TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004858 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004859 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004860 // FIXME: Are these flags correct?
4861 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004862 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004863 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004864 /*CStyle=*/false,
4865 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004866}
4867
4868/// PerformContextuallyConvertToBool - Perform a contextual conversion
4869/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004870ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004871 if (checkPlaceholderForOverload(*this, From))
4872 return ExprError();
4873
John McCall120d63c2010-08-24 20:38:10 +00004874 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004875 if (!ICS.isBad())
4876 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004877
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004878 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004879 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004880 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004881 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004882 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004883}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004884
Richard Smith8ef7b202012-01-18 23:55:52 +00004885/// Check that the specified conversion is permitted in a converted constant
4886/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4887/// is acceptable.
4888static bool CheckConvertedConstantConversions(Sema &S,
4889 StandardConversionSequence &SCS) {
4890 // Since we know that the target type is an integral or unscoped enumeration
4891 // type, most conversion kinds are impossible. All possible First and Third
4892 // conversions are fine.
4893 switch (SCS.Second) {
4894 case ICK_Identity:
4895 case ICK_Integral_Promotion:
4896 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004897 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004898 return true;
4899
4900 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004901 // Conversion from an integral or unscoped enumeration type to bool is
4902 // classified as ICK_Boolean_Conversion, but it's also an integral
4903 // conversion, so it's permitted in a converted constant expression.
4904 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4905 SCS.getToType(2)->isBooleanType();
4906
Richard Smith8ef7b202012-01-18 23:55:52 +00004907 case ICK_Floating_Integral:
4908 case ICK_Complex_Real:
4909 return false;
4910
4911 case ICK_Lvalue_To_Rvalue:
4912 case ICK_Array_To_Pointer:
4913 case ICK_Function_To_Pointer:
4914 case ICK_NoReturn_Adjustment:
4915 case ICK_Qualification:
4916 case ICK_Compatible_Conversion:
4917 case ICK_Vector_Conversion:
4918 case ICK_Vector_Splat:
4919 case ICK_Derived_To_Base:
4920 case ICK_Pointer_Conversion:
4921 case ICK_Pointer_Member:
4922 case ICK_Block_Pointer_Conversion:
4923 case ICK_Writeback_Conversion:
4924 case ICK_Floating_Promotion:
4925 case ICK_Complex_Promotion:
4926 case ICK_Complex_Conversion:
4927 case ICK_Floating_Conversion:
4928 case ICK_TransparentUnionConversion:
4929 llvm_unreachable("unexpected second conversion kind");
4930
4931 case ICK_Num_Conversion_Kinds:
4932 break;
4933 }
4934
4935 llvm_unreachable("unknown conversion kind");
4936}
4937
4938/// CheckConvertedConstantExpression - Check that the expression From is a
4939/// converted constant expression of type T, perform the conversion and produce
4940/// the converted expression, per C++11 [expr.const]p3.
4941ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4942 llvm::APSInt &Value,
4943 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004944 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004945 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4946
4947 if (checkPlaceholderForOverload(*this, From))
4948 return ExprError();
4949
4950 // C++11 [expr.const]p3 with proposed wording fixes:
4951 // A converted constant expression of type T is a core constant expression,
4952 // implicitly converted to a prvalue of type T, where the converted
4953 // expression is a literal constant expression and the implicit conversion
4954 // sequence contains only user-defined conversions, lvalue-to-rvalue
4955 // conversions, integral promotions, and integral conversions other than
4956 // narrowing conversions.
4957 ImplicitConversionSequence ICS =
4958 TryImplicitConversion(From, T,
4959 /*SuppressUserConversions=*/false,
4960 /*AllowExplicit=*/false,
4961 /*InOverloadResolution=*/false,
4962 /*CStyle=*/false,
4963 /*AllowObjcWritebackConversion=*/false);
4964 StandardConversionSequence *SCS = 0;
4965 switch (ICS.getKind()) {
4966 case ImplicitConversionSequence::StandardConversion:
4967 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004968 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004969 diag::err_typecheck_converted_constant_expression_disallowed)
4970 << From->getType() << From->getSourceRange() << T;
4971 SCS = &ICS.Standard;
4972 break;
4973 case ImplicitConversionSequence::UserDefinedConversion:
4974 // We are converting from class type to an integral or enumeration type, so
4975 // the Before sequence must be trivial.
4976 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004977 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004978 diag::err_typecheck_converted_constant_expression_disallowed)
4979 << From->getType() << From->getSourceRange() << T;
4980 SCS = &ICS.UserDefined.After;
4981 break;
4982 case ImplicitConversionSequence::AmbiguousConversion:
4983 case ImplicitConversionSequence::BadConversion:
4984 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004985 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004986 diag::err_typecheck_converted_constant_expression)
4987 << From->getType() << From->getSourceRange() << T;
4988 return ExprError();
4989
4990 case ImplicitConversionSequence::EllipsisConversion:
4991 llvm_unreachable("ellipsis conversion in converted constant expression");
4992 }
4993
4994 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4995 if (Result.isInvalid())
4996 return Result;
4997
4998 // Check for a narrowing implicit conversion.
4999 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00005000 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00005001 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5002 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005003 case NK_Variable_Narrowing:
5004 // Implicit conversion to a narrower type, and the value is not a constant
5005 // expression. We'll diagnose this in a moment.
5006 case NK_Not_Narrowing:
5007 break;
5008
5009 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005010 Diag(From->getLocStart(),
5011 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5012 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005013 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00005014 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00005015 break;
5016
5017 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005018 Diag(From->getLocStart(),
5019 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5020 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005021 << CCE << /*Constant*/0 << From->getType() << T;
5022 break;
5023 }
5024
5025 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005026 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005027 Expr::EvalResult Eval;
5028 Eval.Diag = &Notes;
5029
Douglas Gregor484f6fa2013-04-08 23:24:07 +00005030 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005031 // The expression can't be folded, so we can't keep it at this position in
5032 // the AST.
5033 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005034 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005035 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005036
5037 if (Notes.empty()) {
5038 // It's a constant expression.
5039 return Result;
5040 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005041 }
5042
5043 // It's not a constant expression. Produce an appropriate diagnostic.
5044 if (Notes.size() == 1 &&
5045 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5046 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5047 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005048 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005049 << CCE << From->getSourceRange();
5050 for (unsigned I = 0; I < Notes.size(); ++I)
5051 Diag(Notes[I].first, Notes[I].second);
5052 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005053 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005054}
5055
John McCall0bcc9bc2011-09-09 06:11:02 +00005056/// dropPointerConversions - If the given standard conversion sequence
5057/// involves any pointer conversions, remove them. This may change
5058/// the result type of the conversion sequence.
5059static void dropPointerConversion(StandardConversionSequence &SCS) {
5060 if (SCS.Second == ICK_Pointer_Conversion) {
5061 SCS.Second = ICK_Identity;
5062 SCS.Third = ICK_Identity;
5063 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5064 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005065}
John McCall120d63c2010-08-24 20:38:10 +00005066
John McCall0bcc9bc2011-09-09 06:11:02 +00005067/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5068/// convert the expression From to an Objective-C pointer type.
5069static ImplicitConversionSequence
5070TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5071 // Do an implicit conversion to 'id'.
5072 QualType Ty = S.Context.getObjCIdType();
5073 ImplicitConversionSequence ICS
5074 = TryImplicitConversion(S, From, Ty,
5075 // FIXME: Are these flags correct?
5076 /*SuppressUserConversions=*/false,
5077 /*AllowExplicit=*/true,
5078 /*InOverloadResolution=*/false,
5079 /*CStyle=*/false,
5080 /*AllowObjCWritebackConversion=*/false);
5081
5082 // Strip off any final conversions to 'id'.
5083 switch (ICS.getKind()) {
5084 case ImplicitConversionSequence::BadConversion:
5085 case ImplicitConversionSequence::AmbiguousConversion:
5086 case ImplicitConversionSequence::EllipsisConversion:
5087 break;
5088
5089 case ImplicitConversionSequence::UserDefinedConversion:
5090 dropPointerConversion(ICS.UserDefined.After);
5091 break;
5092
5093 case ImplicitConversionSequence::StandardConversion:
5094 dropPointerConversion(ICS.Standard);
5095 break;
5096 }
5097
5098 return ICS;
5099}
5100
5101/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5102/// conversion of the expression From to an Objective-C pointer type.
5103ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005104 if (checkPlaceholderForOverload(*this, From))
5105 return ExprError();
5106
John McCallc12c5bb2010-05-15 11:32:37 +00005107 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005108 ImplicitConversionSequence ICS =
5109 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005110 if (!ICS.isBad())
5111 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005112 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005113}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005114
Richard Smithf39aec12012-02-04 07:07:42 +00005115/// Determine whether the provided type is an integral type, or an enumeration
5116/// type of a permitted flavor.
5117static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5118 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5119 : T->isIntegralOrUnscopedEnumerationType();
5120}
5121
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005123/// enumeration type.
5124///
5125/// This routine will attempt to convert an expression of class type to an
5126/// integral or enumeration type, if that class type only has a single
5127/// conversion to an integral or enumeration type.
5128///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005129/// \param Loc The source location of the construct that requires the
5130/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005131///
James Dennett40ae6662012-06-22 08:52:37 +00005132/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005133///
James Dennett40ae6662012-06-22 08:52:37 +00005134/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005135///
Richard Smithf39aec12012-02-04 07:07:42 +00005136/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5137/// enumerations should be considered.
5138///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005139/// \returns The expression, converted to an integral or enumeration type if
5140/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005141ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005142Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005143 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005144 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005145 // We can't perform any more checking for type-dependent expressions.
5146 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005147 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005148
Eli Friedmanceccab92012-01-26 00:26:18 +00005149 // Process placeholders immediately.
5150 if (From->hasPlaceholderType()) {
5151 ExprResult result = CheckPlaceholderExpr(From);
5152 if (result.isInvalid()) return result;
5153 From = result.take();
5154 }
5155
Douglas Gregorc30614b2010-06-29 23:17:37 +00005156 // If the expression already has integral or enumeration type, we're golden.
5157 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005158 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005159 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005160
5161 // FIXME: Check for missing '()' if T is a function type?
5162
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005163 // 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 +00005164 // expression of integral or enumeration type.
5165 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005166 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005167 if (!Diagnoser.Suppress)
5168 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005169 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005170 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005171
Douglas Gregorc30614b2010-06-29 23:17:37 +00005172 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005173 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005174 ICEConvertDiagnoser &Diagnoser;
5175 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005176
Douglas Gregorab41fe92012-05-04 22:38:52 +00005177 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5178 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005179
5180 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005181 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005182 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005183 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005184
5185 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005186 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005187
Douglas Gregorc30614b2010-06-29 23:17:37 +00005188 // Look for a conversion to an integral or enumeration type.
5189 UnresolvedSet<4> ViableConversions;
5190 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005191 std::pair<CXXRecordDecl::conversion_iterator,
5192 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005193 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005194
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005195 bool HadMultipleCandidates
5196 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005197
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005198 for (CXXRecordDecl::conversion_iterator
5199 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005200 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005201 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5202 if (isIntegralOrEnumerationType(
5203 Conversion->getConversionType().getNonReferenceType(),
5204 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005205 if (Conversion->isExplicit())
5206 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5207 else
5208 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5209 }
Richard Smithf39aec12012-02-04 07:07:42 +00005210 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005211 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005212
Douglas Gregorc30614b2010-06-29 23:17:37 +00005213 switch (ViableConversions.size()) {
5214 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005215 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005216 DeclAccessPair Found = ExplicitConversions[0];
5217 CXXConversionDecl *Conversion
5218 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005219
Douglas Gregorc30614b2010-06-29 23:17:37 +00005220 // The user probably meant to invoke the given explicit
5221 // conversion; use it.
5222 QualType ConvTy
5223 = Conversion->getConversionType().getNonReferenceType();
5224 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005225 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005226
Douglas Gregorab41fe92012-05-04 22:38:52 +00005227 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005228 << FixItHint::CreateInsertion(From->getLocStart(),
5229 "static_cast<" + TypeStr + ">(")
5230 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5231 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005232 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005233
5234 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005235 // explicit conversion function.
5236 if (isSFINAEContext())
5237 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005238
Douglas Gregorc30614b2010-06-29 23:17:37 +00005239 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005240 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5241 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005242 if (Result.isInvalid())
5243 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005244 // Record usage of conversion in an implicit cast.
5245 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5246 CK_UserDefinedConversion,
5247 Result.get(), 0,
5248 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005249 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005250
Douglas Gregorc30614b2010-06-29 23:17:37 +00005251 // We'll complain below about a non-integral condition type.
5252 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005253
Douglas Gregorc30614b2010-06-29 23:17:37 +00005254 case 1: {
5255 // Apply this conversion.
5256 DeclAccessPair Found = ViableConversions[0];
5257 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005259 CXXConversionDecl *Conversion
5260 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5261 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005263 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005264 if (isSFINAEContext())
5265 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005266
Douglas Gregorab41fe92012-05-04 22:38:52 +00005267 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5268 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005271 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5272 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005273 if (Result.isInvalid())
5274 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005275 // Record usage of conversion in an implicit cast.
5276 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5277 CK_UserDefinedConversion,
5278 Result.get(), 0,
5279 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005280 break;
5281 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005282
Douglas Gregorc30614b2010-06-29 23:17:37 +00005283 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005284 if (Diagnoser.Suppress)
5285 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005286
Douglas Gregorab41fe92012-05-04 22:38:52 +00005287 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005288 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5289 CXXConversionDecl *Conv
5290 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5291 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005292 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005293 }
John McCall9ae2f072010-08-23 23:25:46 +00005294 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005295 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005296
Richard Smith282e7e62012-02-04 09:53:13 +00005297 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005298 !Diagnoser.Suppress) {
5299 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5300 << From->getSourceRange();
5301 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005302
Eli Friedmanceccab92012-01-26 00:26:18 +00005303 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005304}
5305
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005306/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005307/// candidate functions, using the given function call arguments. If
5308/// @p SuppressUserConversions, then don't allow user-defined
5309/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005310///
James Dennett699c9042012-06-15 07:13:21 +00005311/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005312/// based on an incomplete set of function arguments. This feature is used by
5313/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005314void
5315Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005316 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005317 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005318 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005319 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005320 bool PartialOverloading,
5321 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005322 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005323 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005324 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005325 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005326 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005327
Douglas Gregor88a35142008-12-22 05:46:06 +00005328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005329 if (!isa<CXXConstructorDecl>(Method)) {
5330 // If we get here, it's because we're calling a member function
5331 // that is named without a member access expression (e.g.,
5332 // "this->f") that was either written explicitly or created
5333 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005334 // function, e.g., X::f(). We use an empty type for the implied
5335 // object argument (C++ [over.call.func]p3), and the acting context
5336 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005337 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005338 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005339 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005340 return;
5341 }
5342 // We treat a constructor like a non-member function, since its object
5343 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005344 }
5345
Douglas Gregorfd476482009-11-13 23:59:09 +00005346 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005347 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005348
Douglas Gregor7edfb692009-11-23 12:27:39 +00005349 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005350 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005351
Douglas Gregor66724ea2009-11-14 01:20:54 +00005352 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5353 // C++ [class.copy]p3:
5354 // A member function template is never instantiated to perform the copy
5355 // of a class object to an object of its class type.
5356 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005357 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005358 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005359 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5360 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005361 return;
5362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005363
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005364 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005365 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005366 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005367 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005368 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005369 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005370 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005371 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005372
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005373 unsigned NumArgsInProto = Proto->getNumArgs();
5374
5375 // (C++ 13.3.2p2): A candidate function having fewer than m
5376 // parameters is viable only if it has an ellipsis in its parameter
5377 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005378 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005379 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005380 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005381 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005382 return;
5383 }
5384
5385 // (C++ 13.3.2p2): A candidate function having more than m parameters
5386 // is viable only if the (m+1)st parameter has a default argument
5387 // (8.3.6). For the purposes of overload resolution, the
5388 // parameter list is truncated on the right, so that there are
5389 // exactly m parameters.
5390 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005391 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005392 // Not enough arguments.
5393 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005394 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005395 return;
5396 }
5397
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005398 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005399 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005400 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5401 if (CheckCUDATarget(Caller, Function)) {
5402 Candidate.Viable = false;
5403 Candidate.FailureKind = ovl_fail_bad_target;
5404 return;
5405 }
5406
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005407 // Determine the implicit conversion sequences for each of the
5408 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005409 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005410 if (ArgIdx < NumArgsInProto) {
5411 // (C++ 13.3.2p3): for F to be a viable function, there shall
5412 // exist for each argument an implicit conversion sequence
5413 // (13.3.3.1) that converts that argument to the corresponding
5414 // parameter of F.
5415 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005416 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005417 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005418 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005419 /*InOverloadResolution=*/true,
5420 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005421 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005422 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005423 if (Candidate.Conversions[ArgIdx].isBad()) {
5424 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005425 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005426 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005427 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005428 } else {
5429 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5430 // argument for which there is no corresponding parameter is
5431 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005432 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005433 }
5434 }
5435}
5436
Douglas Gregor063daf62009-03-13 18:40:31 +00005437/// \brief Add all of the function declarations in the given function set to
5438/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005439void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005440 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005441 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005442 bool SuppressUserConversions,
5443 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005444 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005445 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5446 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005447 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005448 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005449 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005450 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005451 Args.slice(1), CandidateSet,
5452 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005453 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005454 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005455 SuppressUserConversions);
5456 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005457 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005458 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5459 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005460 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005461 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005462 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005463 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005464 Args[0]->Classify(Context), Args.slice(1),
5465 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005466 else
John McCall9aa472c2010-03-19 07:35:19 +00005467 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005468 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005469 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005470 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005471 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005472}
5473
John McCall314be4e2009-11-17 07:50:12 +00005474/// AddMethodCandidate - Adds a named decl (which is some kind of
5475/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005476void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005477 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005478 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005479 Expr **Args, unsigned NumArgs,
5480 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005481 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005482 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005483 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005484
5485 if (isa<UsingShadowDecl>(Decl))
5486 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005487
John McCall314be4e2009-11-17 07:50:12 +00005488 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5489 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5490 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005491 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5492 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005493 ObjectType, ObjectClassification,
5494 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005495 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005496 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005497 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005498 ObjectType, ObjectClassification,
5499 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005500 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005501 }
5502}
5503
Douglas Gregor96176b32008-11-18 23:14:02 +00005504/// AddMethodCandidate - Adds the given C++ member function to the set
5505/// of candidate functions, using the given function call arguments
5506/// and the object argument (@c Object). For example, in a call
5507/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5508/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5509/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005510/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005511void
John McCall9aa472c2010-03-19 07:35:19 +00005512Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005513 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005514 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005515 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005516 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005517 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005518 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005519 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005520 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005521 assert(!isa<CXXConstructorDecl>(Method) &&
5522 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005523
Douglas Gregor3f396022009-09-28 04:47:19 +00005524 if (!CandidateSet.isNewCandidate(Method))
5525 return;
5526
Douglas Gregor7edfb692009-11-23 12:27:39 +00005527 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005528 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005529
Douglas Gregor96176b32008-11-18 23:14:02 +00005530 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005531 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005532 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005533 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005534 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005535 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005536 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005537
5538 unsigned NumArgsInProto = Proto->getNumArgs();
5539
5540 // (C++ 13.3.2p2): A candidate function having fewer than m
5541 // parameters is viable only if it has an ellipsis in its parameter
5542 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005543 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005544 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005545 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005546 return;
5547 }
5548
5549 // (C++ 13.3.2p2): A candidate function having more than m parameters
5550 // is viable only if the (m+1)st parameter has a default argument
5551 // (8.3.6). For the purposes of overload resolution, the
5552 // parameter list is truncated on the right, so that there are
5553 // exactly m parameters.
5554 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005555 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005556 // Not enough arguments.
5557 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005558 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005559 return;
5560 }
5561
5562 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005563
John McCall701c89e2009-12-03 04:06:58 +00005564 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005565 // The implicit object argument is ignored.
5566 Candidate.IgnoreObjectArgument = true;
5567 else {
5568 // Determine the implicit conversion sequence for the object
5569 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005570 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005571 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5572 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005573 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005574 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005575 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005576 return;
5577 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005578 }
5579
5580 // Determine the implicit conversion sequences for each of the
5581 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005582 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005583 if (ArgIdx < NumArgsInProto) {
5584 // (C++ 13.3.2p3): for F to be a viable function, there shall
5585 // exist for each argument an implicit conversion sequence
5586 // (13.3.3.1) that converts that argument to the corresponding
5587 // parameter of F.
5588 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005589 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005590 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005591 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005592 /*InOverloadResolution=*/true,
5593 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005594 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005595 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005596 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005597 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005598 break;
5599 }
5600 } else {
5601 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5602 // argument for which there is no corresponding parameter is
5603 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005604 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005605 }
5606 }
5607}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005608
Douglas Gregor6b906862009-08-21 00:16:32 +00005609/// \brief Add a C++ member function template as a candidate to the candidate
5610/// set, using template argument deduction to produce an appropriate member
5611/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005612void
Douglas Gregor6b906862009-08-21 00:16:32 +00005613Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005614 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005615 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005616 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005617 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005618 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005619 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005620 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005621 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005622 if (!CandidateSet.isNewCandidate(MethodTmpl))
5623 return;
5624
Douglas Gregor6b906862009-08-21 00:16:32 +00005625 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005626 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005627 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005628 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005629 // candidate functions in the usual way.113) A given name can refer to one
5630 // or more function templates and also to a set of overloaded non-template
5631 // functions. In such a case, the candidate functions generated from each
5632 // function template are combined with the set of non-template candidate
5633 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005634 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005635 FunctionDecl *Specialization = 0;
5636 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005637 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5638 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005639 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005640 Candidate.FoundDecl = FoundDecl;
5641 Candidate.Function = MethodTmpl->getTemplatedDecl();
5642 Candidate.Viable = false;
5643 Candidate.FailureKind = ovl_fail_bad_deduction;
5644 Candidate.IsSurrogate = false;
5645 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005646 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005647 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005648 Info);
5649 return;
5650 }
Mike Stump1eb44332009-09-09 15:08:12 +00005651
Douglas Gregor6b906862009-08-21 00:16:32 +00005652 // Add the function template specialization produced by template argument
5653 // deduction as a candidate.
5654 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005655 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005656 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005657 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005658 ActingContext, ObjectType, ObjectClassification, Args,
5659 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005660}
5661
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005662/// \brief Add a C++ function template specialization as a candidate
5663/// in the candidate set, using template argument deduction to produce
5664/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005665void
Douglas Gregore53060f2009-06-25 22:08:12 +00005666Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005667 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005668 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005669 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005670 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005671 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005672 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5673 return;
5674
Douglas Gregore53060f2009-06-25 22:08:12 +00005675 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005676 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005677 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005678 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005679 // candidate functions in the usual way.113) A given name can refer to one
5680 // or more function templates and also to a set of overloaded non-template
5681 // functions. In such a case, the candidate functions generated from each
5682 // function template are combined with the set of non-template candidate
5683 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005684 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005685 FunctionDecl *Specialization = 0;
5686 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005687 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5688 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005689 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005690 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005691 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5692 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005693 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005694 Candidate.IsSurrogate = false;
5695 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005696 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005697 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005698 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005699 return;
5700 }
Mike Stump1eb44332009-09-09 15:08:12 +00005701
Douglas Gregore53060f2009-06-25 22:08:12 +00005702 // Add the function template specialization produced by template argument
5703 // deduction as a candidate.
5704 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005705 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005706 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005707}
Mike Stump1eb44332009-09-09 15:08:12 +00005708
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005709/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005710/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005711/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005712/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005713/// (which may or may not be the same type as the type that the
5714/// conversion function produces).
5715void
5716Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005717 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005718 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005719 Expr *From, QualType ToType,
5720 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005721 assert(!Conversion->getDescribedFunctionTemplate() &&
5722 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005723 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005724 if (!CandidateSet.isNewCandidate(Conversion))
5725 return;
5726
Douglas Gregor7edfb692009-11-23 12:27:39 +00005727 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005728 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005729
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005730 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005731 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005732 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005733 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005734 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005735 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005736 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005737 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005738 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005739 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005740 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005741
Douglas Gregorbca39322010-08-19 15:37:02 +00005742 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005743 // For conversion functions, the function is considered to be a member of
5744 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005745 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005746 //
5747 // Determine the implicit conversion sequence for the implicit
5748 // object parameter.
5749 QualType ImplicitParamType = From->getType();
5750 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5751 ImplicitParamType = FromPtrType->getPointeeType();
5752 CXXRecordDecl *ConversionContext
5753 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005754
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005755 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005756 = TryObjectArgumentInitialization(*this, From->getType(),
5757 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005758 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005759
John McCall1d318332010-01-12 00:44:57 +00005760 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005761 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005762 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005763 return;
5764 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005765
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005766 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005767 // derived to base as such conversions are given Conversion Rank. They only
5768 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5769 QualType FromCanon
5770 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5771 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5772 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5773 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005774 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005775 return;
5776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005777
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005778 // To determine what the conversion from the result of calling the
5779 // conversion function to the type we're eventually trying to
5780 // convert to (ToType), we need to synthesize a call to the
5781 // conversion function and attempt copy initialization from it. This
5782 // makes sure that we get the right semantics with respect to
5783 // lvalues/rvalues and the type. Fortunately, we can allocate this
5784 // call on the stack and we don't need its arguments to be
5785 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005786 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005787 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005788 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5789 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005790 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005791 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005792
Richard Smith87c1f1f2011-07-13 22:53:21 +00005793 QualType ConversionType = Conversion->getConversionType();
5794 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005795 Candidate.Viable = false;
5796 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5797 return;
5798 }
5799
Richard Smith87c1f1f2011-07-13 22:53:21 +00005800 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005801
Mike Stump1eb44332009-09-09 15:08:12 +00005802 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005803 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5804 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005805 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005806 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005807 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005808 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005809 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005810 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005811 /*InOverloadResolution=*/false,
5812 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005813
John McCall1d318332010-01-12 00:44:57 +00005814 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005815 case ImplicitConversionSequence::StandardConversion:
5816 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005817
Douglas Gregorc520c842010-04-12 23:42:09 +00005818 // C++ [over.ics.user]p3:
5819 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005820 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005821 // shall have exact match rank.
5822 if (Conversion->getPrimaryTemplate() &&
5823 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5824 Candidate.Viable = false;
5825 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005827
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005828 // C++0x [dcl.init.ref]p5:
5829 // In the second case, if the reference is an rvalue reference and
5830 // the second standard conversion sequence of the user-defined
5831 // conversion sequence includes an lvalue-to-rvalue conversion, the
5832 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005833 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005834 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5835 Candidate.Viable = false;
5836 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5837 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005838 break;
5839
5840 case ImplicitConversionSequence::BadConversion:
5841 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005842 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005843 break;
5844
5845 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005846 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005847 "Can only end up with a standard conversion sequence or failure");
5848 }
5849}
5850
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005851/// \brief Adds a conversion function template specialization
5852/// candidate to the overload set, using template argument deduction
5853/// to deduce the template arguments of the conversion function
5854/// template from the type that we are converting to (C++
5855/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005856void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005857Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005858 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005859 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005860 Expr *From, QualType ToType,
5861 OverloadCandidateSet &CandidateSet) {
5862 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5863 "Only conversion function templates permitted here");
5864
Douglas Gregor3f396022009-09-28 04:47:19 +00005865 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5866 return;
5867
Craig Topper93e45992012-09-19 02:26:47 +00005868 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005869 CXXConversionDecl *Specialization = 0;
5870 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005871 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005872 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005873 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005874 Candidate.FoundDecl = FoundDecl;
5875 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5876 Candidate.Viable = false;
5877 Candidate.FailureKind = ovl_fail_bad_deduction;
5878 Candidate.IsSurrogate = false;
5879 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005880 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005881 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005882 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005883 return;
5884 }
Mike Stump1eb44332009-09-09 15:08:12 +00005885
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005886 // Add the conversion function template specialization produced by
5887 // template argument deduction as a candidate.
5888 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005889 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005890 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005891}
5892
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005893/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5894/// converts the given @c Object to a function pointer via the
5895/// conversion function @c Conversion, and then attempts to call it
5896/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5897/// the type of function that we'll eventually be calling.
5898void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005899 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005900 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005901 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005902 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005903 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005904 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005905 if (!CandidateSet.isNewCandidate(Conversion))
5906 return;
5907
Douglas Gregor7edfb692009-11-23 12:27:39 +00005908 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005909 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005910
Ahmed Charles13a140c2012-02-25 11:00:22 +00005911 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005912 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005913 Candidate.Function = 0;
5914 Candidate.Surrogate = Conversion;
5915 Candidate.Viable = true;
5916 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005917 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005918 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005919
5920 // Determine the implicit conversion sequence for the implicit
5921 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005922 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005923 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005924 Object->Classify(Context),
5925 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005926 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005927 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005928 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005929 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005930 return;
5931 }
5932
5933 // The first conversion is actually a user-defined conversion whose
5934 // first conversion is ObjectInit's standard conversion (which is
5935 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005936 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005937 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005938 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005939 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005940 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005941 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005942 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005943 = Candidate.Conversions[0].UserDefined.Before;
5944 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5945
Mike Stump1eb44332009-09-09 15:08:12 +00005946 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005947 unsigned NumArgsInProto = Proto->getNumArgs();
5948
5949 // (C++ 13.3.2p2): A candidate function having fewer than m
5950 // parameters is viable only if it has an ellipsis in its parameter
5951 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005952 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005953 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005954 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005955 return;
5956 }
5957
5958 // Function types don't have any default arguments, so just check if
5959 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005960 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005961 // Not enough arguments.
5962 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005963 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005964 return;
5965 }
5966
5967 // Determine the implicit conversion sequences for each of the
5968 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005969 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005970 if (ArgIdx < NumArgsInProto) {
5971 // (C++ 13.3.2p3): for F to be a viable function, there shall
5972 // exist for each argument an implicit conversion sequence
5973 // (13.3.3.1) that converts that argument to the corresponding
5974 // parameter of F.
5975 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005976 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005977 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005978 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005979 /*InOverloadResolution=*/false,
5980 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005981 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005982 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005983 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005984 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005985 break;
5986 }
5987 } else {
5988 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5989 // argument for which there is no corresponding parameter is
5990 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005991 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005992 }
5993 }
5994}
5995
Douglas Gregor063daf62009-03-13 18:40:31 +00005996/// \brief Add overload candidates for overloaded operators that are
5997/// member functions.
5998///
5999/// Add the overloaded operator candidates that are member functions
6000/// for the operator Op that was used in an operator expression such
6001/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6002/// CandidateSet will store the added overload candidates. (C++
6003/// [over.match.oper]).
6004void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6005 SourceLocation OpLoc,
6006 Expr **Args, unsigned NumArgs,
6007 OverloadCandidateSet& CandidateSet,
6008 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006009 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6010
6011 // C++ [over.match.oper]p3:
6012 // For a unary operator @ with an operand of a type whose
6013 // cv-unqualified version is T1, and for a binary operator @ with
6014 // a left operand of a type whose cv-unqualified version is T1 and
6015 // a right operand of a type whose cv-unqualified version is T2,
6016 // three sets of candidate functions, designated member
6017 // candidates, non-member candidates and built-in candidates, are
6018 // constructed as follows:
6019 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006020
6021 // -- If T1 is a class type, the set of member candidates is the
6022 // result of the qualified lookup of T1::operator@
6023 // (13.3.1.1.1); otherwise, the set of member candidates is
6024 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006025 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006026 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00006027 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006028 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006029
John McCalla24dc2e2009-11-17 02:14:36 +00006030 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6031 LookupQualifiedName(Operators, T1Rec->getDecl());
6032 Operators.suppressDiagnostics();
6033
Mike Stump1eb44332009-09-09 15:08:12 +00006034 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006035 OperEnd = Operators.end();
6036 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006037 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006038 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006039 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006040 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006041 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006042 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006043}
6044
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006045/// AddBuiltinCandidate - Add a candidate for a built-in
6046/// operator. ResultTy and ParamTys are the result and parameter types
6047/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006048/// arguments being passed to the candidate. IsAssignmentOperator
6049/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006050/// operator. NumContextualBoolArguments is the number of arguments
6051/// (at the beginning of the argument list) that will be contextually
6052/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006053void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006054 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006055 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006056 bool IsAssignmentOperator,
6057 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006058 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006059 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006060
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006061 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006062 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00006063 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006064 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006065 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006066 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006067 Candidate.BuiltinTypes.ResultTy = ResultTy;
6068 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6069 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6070
6071 // Determine the implicit conversion sequences for each of the
6072 // arguments.
6073 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006074 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006075 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006076 // C++ [over.match.oper]p4:
6077 // For the built-in assignment operators, conversions of the
6078 // left operand are restricted as follows:
6079 // -- no temporaries are introduced to hold the left operand, and
6080 // -- no user-defined conversions are applied to the left
6081 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006082 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006083 //
6084 // We block these conversions by turning off user-defined
6085 // conversions, since that is the only way that initialization of
6086 // a reference to a non-class type can occur from something that
6087 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006088 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006089 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006090 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006091 Candidate.Conversions[ArgIdx]
6092 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006093 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006094 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006095 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006096 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006097 /*InOverloadResolution=*/false,
6098 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006099 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006100 }
John McCall1d318332010-01-12 00:44:57 +00006101 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006102 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006103 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006104 break;
6105 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006106 }
6107}
6108
6109/// BuiltinCandidateTypeSet - A set of types that will be used for the
6110/// candidate operator functions for built-in operators (C++
6111/// [over.built]). The types are separated into pointer types and
6112/// enumeration types.
6113class BuiltinCandidateTypeSet {
6114 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006115 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006116
6117 /// PointerTypes - The set of pointer types that will be used in the
6118 /// built-in candidates.
6119 TypeSet PointerTypes;
6120
Sebastian Redl78eb8742009-04-19 21:53:20 +00006121 /// MemberPointerTypes - The set of member pointer types that will be
6122 /// used in the built-in candidates.
6123 TypeSet MemberPointerTypes;
6124
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006125 /// EnumerationTypes - The set of enumeration types that will be
6126 /// used in the built-in candidates.
6127 TypeSet EnumerationTypes;
6128
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006129 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006130 /// candidates.
6131 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006132
6133 /// \brief A flag indicating non-record types are viable candidates
6134 bool HasNonRecordTypes;
6135
6136 /// \brief A flag indicating whether either arithmetic or enumeration types
6137 /// were present in the candidate set.
6138 bool HasArithmeticOrEnumeralTypes;
6139
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006140 /// \brief A flag indicating whether the nullptr type was present in the
6141 /// candidate set.
6142 bool HasNullPtrType;
6143
Douglas Gregor5842ba92009-08-24 15:23:48 +00006144 /// Sema - The semantic analysis instance where we are building the
6145 /// candidate type set.
6146 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006147
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006148 /// Context - The AST context in which we will build the type sets.
6149 ASTContext &Context;
6150
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006151 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6152 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006153 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006154
6155public:
6156 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006157 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006158
Mike Stump1eb44332009-09-09 15:08:12 +00006159 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006160 : HasNonRecordTypes(false),
6161 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006162 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006163 SemaRef(SemaRef),
6164 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006165
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006166 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006167 SourceLocation Loc,
6168 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006169 bool AllowExplicitConversions,
6170 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006171
6172 /// pointer_begin - First pointer type found;
6173 iterator pointer_begin() { return PointerTypes.begin(); }
6174
Sebastian Redl78eb8742009-04-19 21:53:20 +00006175 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006176 iterator pointer_end() { return PointerTypes.end(); }
6177
Sebastian Redl78eb8742009-04-19 21:53:20 +00006178 /// member_pointer_begin - First member pointer type found;
6179 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6180
6181 /// member_pointer_end - Past the last member pointer type found;
6182 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6183
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006184 /// enumeration_begin - First enumeration type found;
6185 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6186
Sebastian Redl78eb8742009-04-19 21:53:20 +00006187 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006188 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006189
Douglas Gregor26bcf672010-05-19 03:21:00 +00006190 iterator vector_begin() { return VectorTypes.begin(); }
6191 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006192
6193 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6194 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006195 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006196};
6197
Sebastian Redl78eb8742009-04-19 21:53:20 +00006198/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006199/// the set of pointer types along with any more-qualified variants of
6200/// that type. For example, if @p Ty is "int const *", this routine
6201/// will add "int const *", "int const volatile *", "int const
6202/// restrict *", and "int const volatile restrict *" to the set of
6203/// pointer types. Returns true if the add of @p Ty itself succeeded,
6204/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006205///
6206/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006207bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006208BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6209 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006210
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006211 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006212 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006213 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006214
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006215 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006216 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006217 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006218 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006219 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6220 PointeeTy = PTy->getPointeeType();
6221 buildObjCPtr = true;
6222 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006223 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006224 }
6225
Sebastian Redla9efada2009-11-18 20:39:26 +00006226 // Don't add qualified variants of arrays. For one, they're not allowed
6227 // (the qualifier would sink to the element type), and for another, the
6228 // only overload situation where it matters is subscript or pointer +- int,
6229 // and those shouldn't have qualifier variants anyway.
6230 if (PointeeTy->isArrayType())
6231 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006232
John McCall0953e762009-09-24 19:53:00 +00006233 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006234 bool hasVolatile = VisibleQuals.hasVolatile();
6235 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006236
John McCall0953e762009-09-24 19:53:00 +00006237 // Iterate through all strict supersets of BaseCVR.
6238 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6239 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006240 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006241 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006242
6243 // Skip over restrict if no restrict found anywhere in the types, or if
6244 // the type cannot be restrict-qualified.
6245 if ((CVR & Qualifiers::Restrict) &&
6246 (!hasRestrict ||
6247 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6248 continue;
6249
6250 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006251 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006252
6253 // Build qualified pointer type.
6254 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006255 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006256 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006257 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006258 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6259
6260 // Insert qualified pointer type.
6261 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006262 }
6263
6264 return true;
6265}
6266
Sebastian Redl78eb8742009-04-19 21:53:20 +00006267/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6268/// to the set of pointer types along with any more-qualified variants of
6269/// that type. For example, if @p Ty is "int const *", this routine
6270/// will add "int const *", "int const volatile *", "int const
6271/// restrict *", and "int const volatile restrict *" to the set of
6272/// pointer types. Returns true if the add of @p Ty itself succeeded,
6273/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006274///
6275/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006276bool
6277BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6278 QualType Ty) {
6279 // Insert this type.
6280 if (!MemberPointerTypes.insert(Ty))
6281 return false;
6282
John McCall0953e762009-09-24 19:53:00 +00006283 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6284 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006285
John McCall0953e762009-09-24 19:53:00 +00006286 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006287 // Don't add qualified variants of arrays. For one, they're not allowed
6288 // (the qualifier would sink to the element type), and for another, the
6289 // only overload situation where it matters is subscript or pointer +- int,
6290 // and those shouldn't have qualifier variants anyway.
6291 if (PointeeTy->isArrayType())
6292 return true;
John McCall0953e762009-09-24 19:53:00 +00006293 const Type *ClassTy = PointerTy->getClass();
6294
6295 // Iterate through all strict supersets of the pointee type's CVR
6296 // qualifiers.
6297 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6298 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6299 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006300
John McCall0953e762009-09-24 19:53:00 +00006301 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006302 MemberPointerTypes.insert(
6303 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006304 }
6305
6306 return true;
6307}
6308
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006309/// AddTypesConvertedFrom - Add each of the types to which the type @p
6310/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006311/// primarily interested in pointer types and enumeration types. We also
6312/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006313/// AllowUserConversions is true if we should look at the conversion
6314/// functions of a class type, and AllowExplicitConversions if we
6315/// should also include the explicit conversion functions of a class
6316/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006317void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006318BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006319 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006320 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006321 bool AllowExplicitConversions,
6322 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006323 // Only deal with canonical types.
6324 Ty = Context.getCanonicalType(Ty);
6325
6326 // Look through reference types; they aren't part of the type of an
6327 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006328 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006329 Ty = RefTy->getPointeeType();
6330
John McCall3b657512011-01-19 10:06:00 +00006331 // If we're dealing with an array type, decay to the pointer.
6332 if (Ty->isArrayType())
6333 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6334
6335 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006336 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006337
Chandler Carruth6a577462010-12-13 01:44:01 +00006338 // Flag if we ever add a non-record type.
6339 const RecordType *TyRec = Ty->getAs<RecordType>();
6340 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6341
Chandler Carruth6a577462010-12-13 01:44:01 +00006342 // Flag if we encounter an arithmetic type.
6343 HasArithmeticOrEnumeralTypes =
6344 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6345
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006346 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6347 PointerTypes.insert(Ty);
6348 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006349 // Insert our type, and its more-qualified variants, into the set
6350 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006351 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006352 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006353 } else if (Ty->isMemberPointerType()) {
6354 // Member pointers are far easier, since the pointee can't be converted.
6355 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6356 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006357 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006358 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006359 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006360 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006361 // We treat vector types as arithmetic types in many contexts as an
6362 // extension.
6363 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006364 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006365 } else if (Ty->isNullPtrType()) {
6366 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006367 } else if (AllowUserConversions && TyRec) {
6368 // No conversion functions in incomplete types.
6369 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6370 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006371
Chandler Carruth6a577462010-12-13 01:44:01 +00006372 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006373 std::pair<CXXRecordDecl::conversion_iterator,
6374 CXXRecordDecl::conversion_iterator>
6375 Conversions = ClassDecl->getVisibleConversionFunctions();
6376 for (CXXRecordDecl::conversion_iterator
6377 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006378 NamedDecl *D = I.getDecl();
6379 if (isa<UsingShadowDecl>(D))
6380 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006381
Chandler Carruth6a577462010-12-13 01:44:01 +00006382 // Skip conversion function templates; they don't tell us anything
6383 // about which builtin types we can convert to.
6384 if (isa<FunctionTemplateDecl>(D))
6385 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006386
Chandler Carruth6a577462010-12-13 01:44:01 +00006387 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6388 if (AllowExplicitConversions || !Conv->isExplicit()) {
6389 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6390 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006391 }
6392 }
6393 }
6394}
6395
Douglas Gregor19b7b152009-08-24 13:43:27 +00006396/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6397/// the volatile- and non-volatile-qualified assignment operators for the
6398/// given type to the candidate set.
6399static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6400 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006401 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006402 unsigned NumArgs,
6403 OverloadCandidateSet &CandidateSet) {
6404 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006405
Douglas Gregor19b7b152009-08-24 13:43:27 +00006406 // T& operator=(T&, T)
6407 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6408 ParamTypes[1] = T;
6409 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6410 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006411
Douglas Gregor19b7b152009-08-24 13:43:27 +00006412 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6413 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006414 ParamTypes[0]
6415 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006416 ParamTypes[1] = T;
6417 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006418 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006419 }
6420}
Mike Stump1eb44332009-09-09 15:08:12 +00006421
Sebastian Redl9994a342009-10-25 17:03:50 +00006422/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6423/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006424static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6425 Qualifiers VRQuals;
6426 const RecordType *TyRec;
6427 if (const MemberPointerType *RHSMPType =
6428 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006429 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006430 else
6431 TyRec = ArgExpr->getType()->getAs<RecordType>();
6432 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006433 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006434 VRQuals.addVolatile();
6435 VRQuals.addRestrict();
6436 return VRQuals;
6437 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006438
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006439 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006440 if (!ClassDecl->hasDefinition())
6441 return VRQuals;
6442
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006443 std::pair<CXXRecordDecl::conversion_iterator,
6444 CXXRecordDecl::conversion_iterator>
6445 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006446
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006447 for (CXXRecordDecl::conversion_iterator
6448 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006449 NamedDecl *D = I.getDecl();
6450 if (isa<UsingShadowDecl>(D))
6451 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6452 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006453 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6454 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6455 CanTy = ResTypeRef->getPointeeType();
6456 // Need to go down the pointer/mempointer chain and add qualifiers
6457 // as see them.
6458 bool done = false;
6459 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006460 if (CanTy.isRestrictQualified())
6461 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006462 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6463 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006464 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006465 CanTy->getAs<MemberPointerType>())
6466 CanTy = ResTypeMPtr->getPointeeType();
6467 else
6468 done = true;
6469 if (CanTy.isVolatileQualified())
6470 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006471 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6472 return VRQuals;
6473 }
6474 }
6475 }
6476 return VRQuals;
6477}
John McCall00071ec2010-11-13 05:51:15 +00006478
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006479namespace {
John McCall00071ec2010-11-13 05:51:15 +00006480
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006481/// \brief Helper class to manage the addition of builtin operator overload
6482/// candidates. It provides shared state and utility methods used throughout
6483/// the process, as well as a helper method to add each group of builtin
6484/// operator overloads from the standard to a candidate set.
6485class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006486 // Common instance state available to all overload candidate addition methods.
6487 Sema &S;
6488 Expr **Args;
6489 unsigned NumArgs;
6490 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006491 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006492 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006493 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006494
Chandler Carruth6d695582010-12-12 10:35:00 +00006495 // Define some constants used to index and iterate over the arithemetic types
6496 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006497 // The "promoted arithmetic types" are the arithmetic
6498 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006499 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006500 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006501 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006502 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006503 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006504 LastPromotedArithmeticType = 11;
6505 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006506
Chandler Carruth6d695582010-12-12 10:35:00 +00006507 /// \brief Get the canonical type for a given arithmetic type index.
6508 CanQualType getArithmeticType(unsigned index) {
6509 assert(index < NumArithmeticTypes);
6510 static CanQualType ASTContext::* const
6511 ArithmeticTypes[NumArithmeticTypes] = {
6512 // Start of promoted types.
6513 &ASTContext::FloatTy,
6514 &ASTContext::DoubleTy,
6515 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006516
Chandler Carruth6d695582010-12-12 10:35:00 +00006517 // Start of integral types.
6518 &ASTContext::IntTy,
6519 &ASTContext::LongTy,
6520 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006521 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006522 &ASTContext::UnsignedIntTy,
6523 &ASTContext::UnsignedLongTy,
6524 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006525 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006526 // End of promoted types.
6527
6528 &ASTContext::BoolTy,
6529 &ASTContext::CharTy,
6530 &ASTContext::WCharTy,
6531 &ASTContext::Char16Ty,
6532 &ASTContext::Char32Ty,
6533 &ASTContext::SignedCharTy,
6534 &ASTContext::ShortTy,
6535 &ASTContext::UnsignedCharTy,
6536 &ASTContext::UnsignedShortTy,
6537 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006538 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006539 };
6540 return S.Context.*ArithmeticTypes[index];
6541 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006542
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006543 /// \brief Gets the canonical type resulting from the usual arithemetic
6544 /// converions for the given arithmetic types.
6545 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6546 // Accelerator table for performing the usual arithmetic conversions.
6547 // The rules are basically:
6548 // - if either is floating-point, use the wider floating-point
6549 // - if same signedness, use the higher rank
6550 // - if same size, use unsigned of the higher rank
6551 // - use the larger type
6552 // These rules, together with the axiom that higher ranks are
6553 // never smaller, are sufficient to precompute all of these results
6554 // *except* when dealing with signed types of higher rank.
6555 // (we could precompute SLL x UI for all known platforms, but it's
6556 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006557 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006558 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006559 Dep=-1,
6560 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006561 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006562 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006563 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006564/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6565/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6566/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6567/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6568/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6569/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6570/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6571/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6572/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6573/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6574/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006575 };
6576
6577 assert(L < LastPromotedArithmeticType);
6578 assert(R < LastPromotedArithmeticType);
6579 int Idx = ConversionsTable[L][R];
6580
6581 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006582 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006583
6584 // Slow path: we need to compare widths.
6585 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006586 CanQualType LT = getArithmeticType(L),
6587 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006588 unsigned LW = S.Context.getIntWidth(LT),
6589 RW = S.Context.getIntWidth(RT);
6590
6591 // If they're different widths, use the signed type.
6592 if (LW > RW) return LT;
6593 else if (LW < RW) return RT;
6594
6595 // Otherwise, use the unsigned type of the signed type's rank.
6596 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6597 assert(L == SLL || R == SLL);
6598 return S.Context.UnsignedLongLongTy;
6599 }
6600
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006601 /// \brief Helper method to factor out the common pattern of adding overloads
6602 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006603 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006604 bool HasVolatile,
6605 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006606 QualType ParamTypes[2] = {
6607 S.Context.getLValueReferenceType(CandidateTy),
6608 S.Context.IntTy
6609 };
6610
6611 // Non-volatile version.
6612 if (NumArgs == 1)
6613 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6614 else
6615 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6616
6617 // Use a heuristic to reduce number of builtin candidates in the set:
6618 // add volatile version only if there are conversions to a volatile type.
6619 if (HasVolatile) {
6620 ParamTypes[0] =
6621 S.Context.getLValueReferenceType(
6622 S.Context.getVolatileType(CandidateTy));
6623 if (NumArgs == 1)
6624 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6625 else
6626 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6627 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006628
6629 // Add restrict version only if there are conversions to a restrict type
6630 // and our candidate type is a non-restrict-qualified pointer.
6631 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6632 !CandidateTy.isRestrictQualified()) {
6633 ParamTypes[0]
6634 = S.Context.getLValueReferenceType(
6635 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6636 if (NumArgs == 1)
6637 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6638 else
6639 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6640
6641 if (HasVolatile) {
6642 ParamTypes[0]
6643 = S.Context.getLValueReferenceType(
6644 S.Context.getCVRQualifiedType(CandidateTy,
6645 (Qualifiers::Volatile |
6646 Qualifiers::Restrict)));
6647 if (NumArgs == 1)
6648 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6649 CandidateSet);
6650 else
6651 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6652 }
6653 }
6654
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006655 }
6656
6657public:
6658 BuiltinOperatorOverloadBuilder(
6659 Sema &S, Expr **Args, unsigned NumArgs,
6660 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006661 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006662 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006663 OverloadCandidateSet &CandidateSet)
6664 : S(S), Args(Args), NumArgs(NumArgs),
6665 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006666 HasArithmeticOrEnumeralCandidateType(
6667 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006668 CandidateTypes(CandidateTypes),
6669 CandidateSet(CandidateSet) {
6670 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006671 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006672 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006673 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006674 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006675 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006676 assert(getArithmeticType(FirstPromotedArithmeticType)
6677 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006678 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006679 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006680 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006681 "Invalid last promoted arithmetic type");
6682 }
6683
6684 // C++ [over.built]p3:
6685 //
6686 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6687 // is either volatile or empty, there exist candidate operator
6688 // functions of the form
6689 //
6690 // VQ T& operator++(VQ T&);
6691 // T operator++(VQ T&, int);
6692 //
6693 // C++ [over.built]p4:
6694 //
6695 // For every pair (T, VQ), where T is an arithmetic type other
6696 // than bool, and VQ is either volatile or empty, there exist
6697 // candidate operator functions of the form
6698 //
6699 // VQ T& operator--(VQ T&);
6700 // T operator--(VQ T&, int);
6701 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006702 if (!HasArithmeticOrEnumeralCandidateType)
6703 return;
6704
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006705 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6706 Arith < NumArithmeticTypes; ++Arith) {
6707 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006708 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006709 VisibleTypeConversionsQuals.hasVolatile(),
6710 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006711 }
6712 }
6713
6714 // C++ [over.built]p5:
6715 //
6716 // For every pair (T, VQ), where T is a cv-qualified or
6717 // cv-unqualified object type, and VQ is either volatile or
6718 // empty, there exist candidate operator functions of the form
6719 //
6720 // T*VQ& operator++(T*VQ&);
6721 // T*VQ& operator--(T*VQ&);
6722 // T* operator++(T*VQ&, int);
6723 // T* operator--(T*VQ&, int);
6724 void addPlusPlusMinusMinusPointerOverloads() {
6725 for (BuiltinCandidateTypeSet::iterator
6726 Ptr = CandidateTypes[0].pointer_begin(),
6727 PtrEnd = CandidateTypes[0].pointer_end();
6728 Ptr != PtrEnd; ++Ptr) {
6729 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006730 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006731 continue;
6732
6733 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006734 (!(*Ptr).isVolatileQualified() &&
6735 VisibleTypeConversionsQuals.hasVolatile()),
6736 (!(*Ptr).isRestrictQualified() &&
6737 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006738 }
6739 }
6740
6741 // C++ [over.built]p6:
6742 // For every cv-qualified or cv-unqualified object type T, there
6743 // exist candidate operator functions of the form
6744 //
6745 // T& operator*(T*);
6746 //
6747 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006748 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006749 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006750 // T& operator*(T*);
6751 void addUnaryStarPointerOverloads() {
6752 for (BuiltinCandidateTypeSet::iterator
6753 Ptr = CandidateTypes[0].pointer_begin(),
6754 PtrEnd = CandidateTypes[0].pointer_end();
6755 Ptr != PtrEnd; ++Ptr) {
6756 QualType ParamTy = *Ptr;
6757 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006758 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6759 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006760
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006761 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6762 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6763 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006764
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006765 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6766 &ParamTy, Args, 1, CandidateSet);
6767 }
6768 }
6769
6770 // C++ [over.built]p9:
6771 // For every promoted arithmetic type T, there exist candidate
6772 // operator functions of the form
6773 //
6774 // T operator+(T);
6775 // T operator-(T);
6776 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006777 if (!HasArithmeticOrEnumeralCandidateType)
6778 return;
6779
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006780 for (unsigned Arith = FirstPromotedArithmeticType;
6781 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006782 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006783 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6784 }
6785
6786 // Extension: We also add these operators for vector types.
6787 for (BuiltinCandidateTypeSet::iterator
6788 Vec = CandidateTypes[0].vector_begin(),
6789 VecEnd = CandidateTypes[0].vector_end();
6790 Vec != VecEnd; ++Vec) {
6791 QualType VecTy = *Vec;
6792 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6793 }
6794 }
6795
6796 // C++ [over.built]p8:
6797 // For every type T, there exist candidate operator functions of
6798 // the form
6799 //
6800 // T* operator+(T*);
6801 void addUnaryPlusPointerOverloads() {
6802 for (BuiltinCandidateTypeSet::iterator
6803 Ptr = CandidateTypes[0].pointer_begin(),
6804 PtrEnd = CandidateTypes[0].pointer_end();
6805 Ptr != PtrEnd; ++Ptr) {
6806 QualType ParamTy = *Ptr;
6807 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6808 }
6809 }
6810
6811 // C++ [over.built]p10:
6812 // For every promoted integral type T, there exist candidate
6813 // operator functions of the form
6814 //
6815 // T operator~(T);
6816 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006817 if (!HasArithmeticOrEnumeralCandidateType)
6818 return;
6819
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006820 for (unsigned Int = FirstPromotedIntegralType;
6821 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006822 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006823 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6824 }
6825
6826 // Extension: We also add this operator for vector types.
6827 for (BuiltinCandidateTypeSet::iterator
6828 Vec = CandidateTypes[0].vector_begin(),
6829 VecEnd = CandidateTypes[0].vector_end();
6830 Vec != VecEnd; ++Vec) {
6831 QualType VecTy = *Vec;
6832 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6833 }
6834 }
6835
6836 // C++ [over.match.oper]p16:
6837 // For every pointer to member type T, there exist candidate operator
6838 // functions of the form
6839 //
6840 // bool operator==(T,T);
6841 // bool operator!=(T,T);
6842 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6843 /// Set of (canonical) types that we've already handled.
6844 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6845
6846 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6847 for (BuiltinCandidateTypeSet::iterator
6848 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6849 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6850 MemPtr != MemPtrEnd;
6851 ++MemPtr) {
6852 // Don't add the same builtin candidate twice.
6853 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6854 continue;
6855
6856 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6857 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6858 CandidateSet);
6859 }
6860 }
6861 }
6862
6863 // C++ [over.built]p15:
6864 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006865 // For every T, where T is an enumeration type, a pointer type, or
6866 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006867 //
6868 // bool operator<(T, T);
6869 // bool operator>(T, T);
6870 // bool operator<=(T, T);
6871 // bool operator>=(T, T);
6872 // bool operator==(T, T);
6873 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006874 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006875 // C++ [over.match.oper]p3:
6876 // [...]the built-in candidates include all of the candidate operator
6877 // functions defined in 13.6 that, compared to the given operator, [...]
6878 // do not have the same parameter-type-list as any non-template non-member
6879 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006880 //
Eli Friedman97c67392012-09-18 21:52:24 +00006881 // Note that in practice, this only affects enumeration types because there
6882 // aren't any built-in candidates of record type, and a user-defined operator
6883 // must have an operand of record or enumeration type. Also, the only other
6884 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006885 // cannot be overloaded for enumeration types, so this is the only place
6886 // where we must suppress candidates like this.
6887 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6888 UserDefinedBinaryOperators;
6889
6890 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6891 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6892 CandidateTypes[ArgIdx].enumeration_end()) {
6893 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6894 CEnd = CandidateSet.end();
6895 C != CEnd; ++C) {
6896 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6897 continue;
6898
Eli Friedman97c67392012-09-18 21:52:24 +00006899 if (C->Function->isFunctionTemplateSpecialization())
6900 continue;
6901
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006902 QualType FirstParamType =
6903 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6904 QualType SecondParamType =
6905 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6906
6907 // Skip if either parameter isn't of enumeral type.
6908 if (!FirstParamType->isEnumeralType() ||
6909 !SecondParamType->isEnumeralType())
6910 continue;
6911
6912 // Add this operator to the set of known user-defined operators.
6913 UserDefinedBinaryOperators.insert(
6914 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6915 S.Context.getCanonicalType(SecondParamType)));
6916 }
6917 }
6918 }
6919
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006920 /// Set of (canonical) types that we've already handled.
6921 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6922
6923 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6924 for (BuiltinCandidateTypeSet::iterator
6925 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6926 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6927 Ptr != PtrEnd; ++Ptr) {
6928 // Don't add the same builtin candidate twice.
6929 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6930 continue;
6931
6932 QualType ParamTypes[2] = { *Ptr, *Ptr };
6933 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6934 CandidateSet);
6935 }
6936 for (BuiltinCandidateTypeSet::iterator
6937 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6938 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6939 Enum != EnumEnd; ++Enum) {
6940 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6941
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006942 // Don't add the same builtin candidate twice, or if a user defined
6943 // candidate exists.
6944 if (!AddedTypes.insert(CanonType) ||
6945 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6946 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006947 continue;
6948
6949 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006950 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6951 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006952 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006953
6954 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6955 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6956 if (AddedTypes.insert(NullPtrTy) &&
6957 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6958 NullPtrTy))) {
6959 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6960 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6961 CandidateSet);
6962 }
6963 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006964 }
6965 }
6966
6967 // C++ [over.built]p13:
6968 //
6969 // For every cv-qualified or cv-unqualified object type T
6970 // there exist candidate operator functions of the form
6971 //
6972 // T* operator+(T*, ptrdiff_t);
6973 // T& operator[](T*, ptrdiff_t); [BELOW]
6974 // T* operator-(T*, ptrdiff_t);
6975 // T* operator+(ptrdiff_t, T*);
6976 // T& operator[](ptrdiff_t, T*); [BELOW]
6977 //
6978 // C++ [over.built]p14:
6979 //
6980 // For every T, where T is a pointer to object type, there
6981 // exist candidate operator functions of the form
6982 //
6983 // ptrdiff_t operator-(T, T);
6984 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6985 /// Set of (canonical) types that we've already handled.
6986 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6987
6988 for (int Arg = 0; Arg < 2; ++Arg) {
6989 QualType AsymetricParamTypes[2] = {
6990 S.Context.getPointerDiffType(),
6991 S.Context.getPointerDiffType(),
6992 };
6993 for (BuiltinCandidateTypeSet::iterator
6994 Ptr = CandidateTypes[Arg].pointer_begin(),
6995 PtrEnd = CandidateTypes[Arg].pointer_end();
6996 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006997 QualType PointeeTy = (*Ptr)->getPointeeType();
6998 if (!PointeeTy->isObjectType())
6999 continue;
7000
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007001 AsymetricParamTypes[Arg] = *Ptr;
7002 if (Arg == 0 || Op == OO_Plus) {
7003 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7004 // T* operator+(ptrdiff_t, T*);
7005 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
7006 CandidateSet);
7007 }
7008 if (Op == OO_Minus) {
7009 // ptrdiff_t operator-(T, T);
7010 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7011 continue;
7012
7013 QualType ParamTypes[2] = { *Ptr, *Ptr };
7014 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7015 Args, 2, CandidateSet);
7016 }
7017 }
7018 }
7019 }
7020
7021 // C++ [over.built]p12:
7022 //
7023 // For every pair of promoted arithmetic types L and R, there
7024 // exist candidate operator functions of the form
7025 //
7026 // LR operator*(L, R);
7027 // LR operator/(L, R);
7028 // LR operator+(L, R);
7029 // LR operator-(L, R);
7030 // bool operator<(L, R);
7031 // bool operator>(L, R);
7032 // bool operator<=(L, R);
7033 // bool operator>=(L, R);
7034 // bool operator==(L, R);
7035 // bool operator!=(L, R);
7036 //
7037 // where LR is the result of the usual arithmetic conversions
7038 // between types L and R.
7039 //
7040 // C++ [over.built]p24:
7041 //
7042 // For every pair of promoted arithmetic types L and R, there exist
7043 // candidate operator functions of the form
7044 //
7045 // LR operator?(bool, L, R);
7046 //
7047 // where LR is the result of the usual arithmetic conversions
7048 // between types L and R.
7049 // Our candidates ignore the first parameter.
7050 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007051 if (!HasArithmeticOrEnumeralCandidateType)
7052 return;
7053
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007054 for (unsigned Left = FirstPromotedArithmeticType;
7055 Left < LastPromotedArithmeticType; ++Left) {
7056 for (unsigned Right = FirstPromotedArithmeticType;
7057 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007058 QualType LandR[2] = { getArithmeticType(Left),
7059 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007060 QualType Result =
7061 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007062 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007063 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7064 }
7065 }
7066
7067 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7068 // conditional operator for vector types.
7069 for (BuiltinCandidateTypeSet::iterator
7070 Vec1 = CandidateTypes[0].vector_begin(),
7071 Vec1End = CandidateTypes[0].vector_end();
7072 Vec1 != Vec1End; ++Vec1) {
7073 for (BuiltinCandidateTypeSet::iterator
7074 Vec2 = CandidateTypes[1].vector_begin(),
7075 Vec2End = CandidateTypes[1].vector_end();
7076 Vec2 != Vec2End; ++Vec2) {
7077 QualType LandR[2] = { *Vec1, *Vec2 };
7078 QualType Result = S.Context.BoolTy;
7079 if (!isComparison) {
7080 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7081 Result = *Vec1;
7082 else
7083 Result = *Vec2;
7084 }
7085
7086 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7087 }
7088 }
7089 }
7090
7091 // C++ [over.built]p17:
7092 //
7093 // For every pair of promoted integral types L and R, there
7094 // exist candidate operator functions of the form
7095 //
7096 // LR operator%(L, R);
7097 // LR operator&(L, R);
7098 // LR operator^(L, R);
7099 // LR operator|(L, R);
7100 // L operator<<(L, R);
7101 // L operator>>(L, R);
7102 //
7103 // where LR is the result of the usual arithmetic conversions
7104 // between types L and R.
7105 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007106 if (!HasArithmeticOrEnumeralCandidateType)
7107 return;
7108
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007109 for (unsigned Left = FirstPromotedIntegralType;
7110 Left < LastPromotedIntegralType; ++Left) {
7111 for (unsigned Right = FirstPromotedIntegralType;
7112 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007113 QualType LandR[2] = { getArithmeticType(Left),
7114 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007115 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7116 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007117 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007118 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7119 }
7120 }
7121 }
7122
7123 // C++ [over.built]p20:
7124 //
7125 // For every pair (T, VQ), where T is an enumeration or
7126 // pointer to member type and VQ is either volatile or
7127 // empty, there exist candidate operator functions of the form
7128 //
7129 // VQ T& operator=(VQ T&, T);
7130 void addAssignmentMemberPointerOrEnumeralOverloads() {
7131 /// Set of (canonical) types that we've already handled.
7132 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7133
7134 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7135 for (BuiltinCandidateTypeSet::iterator
7136 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7137 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7138 Enum != EnumEnd; ++Enum) {
7139 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7140 continue;
7141
7142 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7143 CandidateSet);
7144 }
7145
7146 for (BuiltinCandidateTypeSet::iterator
7147 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7148 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7149 MemPtr != MemPtrEnd; ++MemPtr) {
7150 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7151 continue;
7152
7153 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7154 CandidateSet);
7155 }
7156 }
7157 }
7158
7159 // C++ [over.built]p19:
7160 //
7161 // For every pair (T, VQ), where T is any type and VQ is either
7162 // volatile or empty, there exist candidate operator functions
7163 // of the form
7164 //
7165 // T*VQ& operator=(T*VQ&, T*);
7166 //
7167 // C++ [over.built]p21:
7168 //
7169 // For every pair (T, VQ), where T is a cv-qualified or
7170 // cv-unqualified object type and VQ is either volatile or
7171 // empty, there exist candidate operator functions of the form
7172 //
7173 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7174 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7175 void addAssignmentPointerOverloads(bool isEqualOp) {
7176 /// Set of (canonical) types that we've already handled.
7177 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7178
7179 for (BuiltinCandidateTypeSet::iterator
7180 Ptr = CandidateTypes[0].pointer_begin(),
7181 PtrEnd = CandidateTypes[0].pointer_end();
7182 Ptr != PtrEnd; ++Ptr) {
7183 // If this is operator=, keep track of the builtin candidates we added.
7184 if (isEqualOp)
7185 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007186 else if (!(*Ptr)->getPointeeType()->isObjectType())
7187 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007188
7189 // non-volatile version
7190 QualType ParamTypes[2] = {
7191 S.Context.getLValueReferenceType(*Ptr),
7192 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7193 };
7194 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7195 /*IsAssigmentOperator=*/ isEqualOp);
7196
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007197 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7198 VisibleTypeConversionsQuals.hasVolatile();
7199 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007200 // volatile version
7201 ParamTypes[0] =
7202 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7203 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7204 /*IsAssigmentOperator=*/isEqualOp);
7205 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007206
7207 if (!(*Ptr).isRestrictQualified() &&
7208 VisibleTypeConversionsQuals.hasRestrict()) {
7209 // restrict version
7210 ParamTypes[0]
7211 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7212 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7213 /*IsAssigmentOperator=*/isEqualOp);
7214
7215 if (NeedVolatile) {
7216 // volatile restrict version
7217 ParamTypes[0]
7218 = S.Context.getLValueReferenceType(
7219 S.Context.getCVRQualifiedType(*Ptr,
7220 (Qualifiers::Volatile |
7221 Qualifiers::Restrict)));
7222 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7223 CandidateSet,
7224 /*IsAssigmentOperator=*/isEqualOp);
7225 }
7226 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007227 }
7228
7229 if (isEqualOp) {
7230 for (BuiltinCandidateTypeSet::iterator
7231 Ptr = CandidateTypes[1].pointer_begin(),
7232 PtrEnd = CandidateTypes[1].pointer_end();
7233 Ptr != PtrEnd; ++Ptr) {
7234 // Make sure we don't add the same candidate twice.
7235 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7236 continue;
7237
Chandler Carruth6df868e2010-12-12 08:17:55 +00007238 QualType ParamTypes[2] = {
7239 S.Context.getLValueReferenceType(*Ptr),
7240 *Ptr,
7241 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007242
7243 // non-volatile version
7244 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7245 /*IsAssigmentOperator=*/true);
7246
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007247 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7248 VisibleTypeConversionsQuals.hasVolatile();
7249 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007250 // volatile version
7251 ParamTypes[0] =
7252 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7254 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007255 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007256
7257 if (!(*Ptr).isRestrictQualified() &&
7258 VisibleTypeConversionsQuals.hasRestrict()) {
7259 // restrict version
7260 ParamTypes[0]
7261 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7262 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7263 CandidateSet, /*IsAssigmentOperator=*/true);
7264
7265 if (NeedVolatile) {
7266 // volatile restrict version
7267 ParamTypes[0]
7268 = S.Context.getLValueReferenceType(
7269 S.Context.getCVRQualifiedType(*Ptr,
7270 (Qualifiers::Volatile |
7271 Qualifiers::Restrict)));
7272 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7273 CandidateSet, /*IsAssigmentOperator=*/true);
7274
7275 }
7276 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007277 }
7278 }
7279 }
7280
7281 // C++ [over.built]p18:
7282 //
7283 // For every triple (L, VQ, R), where L is an arithmetic type,
7284 // VQ is either volatile or empty, and R is a promoted
7285 // arithmetic type, there exist candidate operator functions of
7286 // the form
7287 //
7288 // VQ L& operator=(VQ L&, R);
7289 // VQ L& operator*=(VQ L&, R);
7290 // VQ L& operator/=(VQ L&, R);
7291 // VQ L& operator+=(VQ L&, R);
7292 // VQ L& operator-=(VQ L&, R);
7293 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007294 if (!HasArithmeticOrEnumeralCandidateType)
7295 return;
7296
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007297 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7298 for (unsigned Right = FirstPromotedArithmeticType;
7299 Right < LastPromotedArithmeticType; ++Right) {
7300 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007301 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007302
7303 // Add this built-in operator as a candidate (VQ is empty).
7304 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007305 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007306 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7307 /*IsAssigmentOperator=*/isEqualOp);
7308
7309 // Add this built-in operator as a candidate (VQ is 'volatile').
7310 if (VisibleTypeConversionsQuals.hasVolatile()) {
7311 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007312 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007313 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007314 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7315 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007316 /*IsAssigmentOperator=*/isEqualOp);
7317 }
7318 }
7319 }
7320
7321 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7322 for (BuiltinCandidateTypeSet::iterator
7323 Vec1 = CandidateTypes[0].vector_begin(),
7324 Vec1End = CandidateTypes[0].vector_end();
7325 Vec1 != Vec1End; ++Vec1) {
7326 for (BuiltinCandidateTypeSet::iterator
7327 Vec2 = CandidateTypes[1].vector_begin(),
7328 Vec2End = CandidateTypes[1].vector_end();
7329 Vec2 != Vec2End; ++Vec2) {
7330 QualType ParamTypes[2];
7331 ParamTypes[1] = *Vec2;
7332 // Add this built-in operator as a candidate (VQ is empty).
7333 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7334 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7335 /*IsAssigmentOperator=*/isEqualOp);
7336
7337 // Add this built-in operator as a candidate (VQ is 'volatile').
7338 if (VisibleTypeConversionsQuals.hasVolatile()) {
7339 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7340 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7342 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007343 /*IsAssigmentOperator=*/isEqualOp);
7344 }
7345 }
7346 }
7347 }
7348
7349 // C++ [over.built]p22:
7350 //
7351 // For every triple (L, VQ, R), where L is an integral type, VQ
7352 // is either volatile or empty, and R is a promoted integral
7353 // type, there exist candidate operator functions of the form
7354 //
7355 // VQ L& operator%=(VQ L&, R);
7356 // VQ L& operator<<=(VQ L&, R);
7357 // VQ L& operator>>=(VQ L&, R);
7358 // VQ L& operator&=(VQ L&, R);
7359 // VQ L& operator^=(VQ L&, R);
7360 // VQ L& operator|=(VQ L&, R);
7361 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007362 if (!HasArithmeticOrEnumeralCandidateType)
7363 return;
7364
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007365 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7366 for (unsigned Right = FirstPromotedIntegralType;
7367 Right < LastPromotedIntegralType; ++Right) {
7368 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007369 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007370
7371 // Add this built-in operator as a candidate (VQ is empty).
7372 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007373 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7375 if (VisibleTypeConversionsQuals.hasVolatile()) {
7376 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007377 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007378 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7379 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7380 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7381 CandidateSet);
7382 }
7383 }
7384 }
7385 }
7386
7387 // C++ [over.operator]p23:
7388 //
7389 // There also exist candidate operator functions of the form
7390 //
7391 // bool operator!(bool);
7392 // bool operator&&(bool, bool);
7393 // bool operator||(bool, bool);
7394 void addExclaimOverload() {
7395 QualType ParamTy = S.Context.BoolTy;
7396 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7397 /*IsAssignmentOperator=*/false,
7398 /*NumContextualBoolArguments=*/1);
7399 }
7400 void addAmpAmpOrPipePipeOverload() {
7401 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7402 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7403 /*IsAssignmentOperator=*/false,
7404 /*NumContextualBoolArguments=*/2);
7405 }
7406
7407 // C++ [over.built]p13:
7408 //
7409 // For every cv-qualified or cv-unqualified object type T there
7410 // exist candidate operator functions of the form
7411 //
7412 // T* operator+(T*, ptrdiff_t); [ABOVE]
7413 // T& operator[](T*, ptrdiff_t);
7414 // T* operator-(T*, ptrdiff_t); [ABOVE]
7415 // T* operator+(ptrdiff_t, T*); [ABOVE]
7416 // T& operator[](ptrdiff_t, T*);
7417 void addSubscriptOverloads() {
7418 for (BuiltinCandidateTypeSet::iterator
7419 Ptr = CandidateTypes[0].pointer_begin(),
7420 PtrEnd = CandidateTypes[0].pointer_end();
7421 Ptr != PtrEnd; ++Ptr) {
7422 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7423 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007424 if (!PointeeType->isObjectType())
7425 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007426
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007427 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7428
7429 // T& operator[](T*, ptrdiff_t)
7430 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7431 }
7432
7433 for (BuiltinCandidateTypeSet::iterator
7434 Ptr = CandidateTypes[1].pointer_begin(),
7435 PtrEnd = CandidateTypes[1].pointer_end();
7436 Ptr != PtrEnd; ++Ptr) {
7437 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7438 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007439 if (!PointeeType->isObjectType())
7440 continue;
7441
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007442 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7443
7444 // T& operator[](ptrdiff_t, T*)
7445 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7446 }
7447 }
7448
7449 // C++ [over.built]p11:
7450 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7451 // C1 is the same type as C2 or is a derived class of C2, T is an object
7452 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7453 // there exist candidate operator functions of the form
7454 //
7455 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7456 //
7457 // where CV12 is the union of CV1 and CV2.
7458 void addArrowStarOverloads() {
7459 for (BuiltinCandidateTypeSet::iterator
7460 Ptr = CandidateTypes[0].pointer_begin(),
7461 PtrEnd = CandidateTypes[0].pointer_end();
7462 Ptr != PtrEnd; ++Ptr) {
7463 QualType C1Ty = (*Ptr);
7464 QualType C1;
7465 QualifierCollector Q1;
7466 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7467 if (!isa<RecordType>(C1))
7468 continue;
7469 // heuristic to reduce number of builtin candidates in the set.
7470 // Add volatile/restrict version only if there are conversions to a
7471 // volatile/restrict type.
7472 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7473 continue;
7474 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7475 continue;
7476 for (BuiltinCandidateTypeSet::iterator
7477 MemPtr = CandidateTypes[1].member_pointer_begin(),
7478 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7479 MemPtr != MemPtrEnd; ++MemPtr) {
7480 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7481 QualType C2 = QualType(mptr->getClass(), 0);
7482 C2 = C2.getUnqualifiedType();
7483 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7484 break;
7485 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7486 // build CV12 T&
7487 QualType T = mptr->getPointeeType();
7488 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7489 T.isVolatileQualified())
7490 continue;
7491 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7492 T.isRestrictQualified())
7493 continue;
7494 T = Q1.apply(S.Context, T);
7495 QualType ResultTy = S.Context.getLValueReferenceType(T);
7496 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7497 }
7498 }
7499 }
7500
7501 // Note that we don't consider the first argument, since it has been
7502 // contextually converted to bool long ago. The candidates below are
7503 // therefore added as binary.
7504 //
7505 // C++ [over.built]p25:
7506 // For every type T, where T is a pointer, pointer-to-member, or scoped
7507 // enumeration type, there exist candidate operator functions of the form
7508 //
7509 // T operator?(bool, T, T);
7510 //
7511 void addConditionalOperatorOverloads() {
7512 /// Set of (canonical) types that we've already handled.
7513 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7514
7515 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7516 for (BuiltinCandidateTypeSet::iterator
7517 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7518 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7519 Ptr != PtrEnd; ++Ptr) {
7520 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7521 continue;
7522
7523 QualType ParamTypes[2] = { *Ptr, *Ptr };
7524 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7525 }
7526
7527 for (BuiltinCandidateTypeSet::iterator
7528 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7529 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7530 MemPtr != MemPtrEnd; ++MemPtr) {
7531 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7532 continue;
7533
7534 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7535 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7536 }
7537
Richard Smith80ad52f2013-01-02 11:42:31 +00007538 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007539 for (BuiltinCandidateTypeSet::iterator
7540 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7541 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7542 Enum != EnumEnd; ++Enum) {
7543 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7544 continue;
7545
7546 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7547 continue;
7548
7549 QualType ParamTypes[2] = { *Enum, *Enum };
7550 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7551 }
7552 }
7553 }
7554 }
7555};
7556
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007557} // end anonymous namespace
7558
7559/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7560/// operator overloads to the candidate set (C++ [over.built]), based
7561/// on the operator @p Op and the arguments given. For example, if the
7562/// operator is a binary '+', this routine might add "int
7563/// operator+(int, int)" to cover integer addition.
7564void
7565Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7566 SourceLocation OpLoc,
7567 Expr **Args, unsigned NumArgs,
7568 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007569 // Find all of the types that the arguments can convert to, but only
7570 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007571 // that make use of these types. Also record whether we encounter non-record
7572 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007573 Qualifiers VisibleTypeConversionsQuals;
7574 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007575 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7576 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007577
7578 bool HasNonRecordCandidateType = false;
7579 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007580 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007581 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7582 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7583 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7584 OpLoc,
7585 true,
7586 (Op == OO_Exclaim ||
7587 Op == OO_AmpAmp ||
7588 Op == OO_PipePipe),
7589 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007590 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7591 CandidateTypes[ArgIdx].hasNonRecordTypes();
7592 HasArithmeticOrEnumeralCandidateType =
7593 HasArithmeticOrEnumeralCandidateType ||
7594 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007595 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007596
Chandler Carruth6a577462010-12-13 01:44:01 +00007597 // Exit early when no non-record types have been added to the candidate set
7598 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007599 //
7600 // We can't exit early for !, ||, or &&, since there we have always have
7601 // 'bool' overloads.
7602 if (!HasNonRecordCandidateType &&
7603 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007604 return;
7605
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007606 // Setup an object to manage the common state for building overloads.
7607 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7608 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007609 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007610 CandidateTypes, CandidateSet);
7611
7612 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007613 switch (Op) {
7614 case OO_None:
7615 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007616 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007617
Chandler Carruthabb71842010-12-12 08:51:33 +00007618 case OO_New:
7619 case OO_Delete:
7620 case OO_Array_New:
7621 case OO_Array_Delete:
7622 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007623 llvm_unreachable(
7624 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007625
7626 case OO_Comma:
7627 case OO_Arrow:
7628 // C++ [over.match.oper]p3:
7629 // -- For the operator ',', the unary operator '&', or the
7630 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007631 break;
7632
7633 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007634 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007635 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007636 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007637
7638 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007639 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007640 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007641 } else {
7642 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7643 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7644 }
Douglas Gregor74253732008-11-19 15:42:04 +00007645 break;
7646
Chandler Carruthabb71842010-12-12 08:51:33 +00007647 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007648 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007649 OpBuilder.addUnaryStarPointerOverloads();
7650 else
7651 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7652 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007653
Chandler Carruthabb71842010-12-12 08:51:33 +00007654 case OO_Slash:
7655 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007656 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007657
7658 case OO_PlusPlus:
7659 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007660 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7661 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007662 break;
7663
Douglas Gregor19b7b152009-08-24 13:43:27 +00007664 case OO_EqualEqual:
7665 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007666 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007667 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007668
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007669 case OO_Less:
7670 case OO_Greater:
7671 case OO_LessEqual:
7672 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007673 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007674 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7675 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007676
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007677 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007678 case OO_Caret:
7679 case OO_Pipe:
7680 case OO_LessLess:
7681 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007682 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007683 break;
7684
Chandler Carruthabb71842010-12-12 08:51:33 +00007685 case OO_Amp: // '&' is either unary or binary
7686 if (NumArgs == 1)
7687 // C++ [over.match.oper]p3:
7688 // -- For the operator ',', the unary operator '&', or the
7689 // operator '->', the built-in candidates set is empty.
7690 break;
7691
7692 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7693 break;
7694
7695 case OO_Tilde:
7696 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7697 break;
7698
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007699 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007700 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007701 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007702
7703 case OO_PlusEqual:
7704 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007705 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007706 // Fall through.
7707
7708 case OO_StarEqual:
7709 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007710 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007711 break;
7712
7713 case OO_PercentEqual:
7714 case OO_LessLessEqual:
7715 case OO_GreaterGreaterEqual:
7716 case OO_AmpEqual:
7717 case OO_CaretEqual:
7718 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007719 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007720 break;
7721
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007722 case OO_Exclaim:
7723 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007724 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007725
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007726 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007727 case OO_PipePipe:
7728 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007729 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007730
7731 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007732 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007733 break;
7734
7735 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007736 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007737 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007738
7739 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007740 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007741 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7742 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007743 }
7744}
7745
Douglas Gregorfa047642009-02-04 00:32:51 +00007746/// \brief Add function candidates found via argument-dependent lookup
7747/// to the set of overloading candidates.
7748///
7749/// This routine performs argument-dependent name lookup based on the
7750/// given function name (which may also be an operator name) and adds
7751/// all of the overload candidates found by ADL to the overload
7752/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007753void
Douglas Gregorfa047642009-02-04 00:32:51 +00007754Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007755 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007756 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007757 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007758 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007759 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007760 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007761
John McCalla113e722010-01-26 06:04:06 +00007762 // FIXME: This approach for uniquing ADL results (and removing
7763 // redundant candidates from the set) relies on pointer-equality,
7764 // which means we need to key off the canonical decl. However,
7765 // always going back to the canonical decl might not get us the
7766 // right set of default arguments. What default arguments are
7767 // we supposed to consider on ADL candidates, anyway?
7768
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007769 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007770 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007771
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007772 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007773 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7774 CandEnd = CandidateSet.end();
7775 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007776 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007777 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007778 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007779 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007780 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007781
7782 // For each of the ADL candidates we found, add it to the overload
7783 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007784 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007785 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007786 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007787 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007788 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007789
Ahmed Charles13a140c2012-02-25 11:00:22 +00007790 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7791 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007792 } else
John McCall6e266892010-01-26 03:27:55 +00007793 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007794 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007795 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007796 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007797}
7798
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007799/// isBetterOverloadCandidate - Determines whether the first overload
7800/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007801bool
John McCall120d63c2010-08-24 20:38:10 +00007802isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007803 const OverloadCandidate &Cand1,
7804 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007805 SourceLocation Loc,
7806 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007807 // Define viable functions to be better candidates than non-viable
7808 // functions.
7809 if (!Cand2.Viable)
7810 return Cand1.Viable;
7811 else if (!Cand1.Viable)
7812 return false;
7813
Douglas Gregor88a35142008-12-22 05:46:06 +00007814 // C++ [over.match.best]p1:
7815 //
7816 // -- if F is a static member function, ICS1(F) is defined such
7817 // that ICS1(F) is neither better nor worse than ICS1(G) for
7818 // any function G, and, symmetrically, ICS1(G) is neither
7819 // better nor worse than ICS1(F).
7820 unsigned StartArg = 0;
7821 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7822 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007823
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007824 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007825 // A viable function F1 is defined to be a better function than another
7826 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007827 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007828 unsigned NumArgs = Cand1.NumConversions;
7829 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007830 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007831 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007832 switch (CompareImplicitConversionSequences(S,
7833 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007834 Cand2.Conversions[ArgIdx])) {
7835 case ImplicitConversionSequence::Better:
7836 // Cand1 has a better conversion sequence.
7837 HasBetterConversion = true;
7838 break;
7839
7840 case ImplicitConversionSequence::Worse:
7841 // Cand1 can't be better than Cand2.
7842 return false;
7843
7844 case ImplicitConversionSequence::Indistinguishable:
7845 // Do nothing.
7846 break;
7847 }
7848 }
7849
Mike Stump1eb44332009-09-09 15:08:12 +00007850 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007851 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007852 if (HasBetterConversion)
7853 return true;
7854
Mike Stump1eb44332009-09-09 15:08:12 +00007855 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007856 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007857 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007858 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7859 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007860
7861 // -- F1 and F2 are function template specializations, and the function
7862 // template for F1 is more specialized than the template for F2
7863 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007864 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007865 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007866 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007867 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007868 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7869 Cand2.Function->getPrimaryTemplate(),
7870 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007871 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007872 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007873 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007874 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007875 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007876
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007877 // -- the context is an initialization by user-defined conversion
7878 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7879 // from the return type of F1 to the destination type (i.e.,
7880 // the type of the entity being initialized) is a better
7881 // conversion sequence than the standard conversion sequence
7882 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007883 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007884 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007885 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007886 // First check whether we prefer one of the conversion functions over the
7887 // other. This only distinguishes the results in non-standard, extension
7888 // cases such as the conversion from a lambda closure type to a function
7889 // pointer or block.
7890 ImplicitConversionSequence::CompareKind FuncResult
7891 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7892 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7893 return FuncResult;
7894
John McCall120d63c2010-08-24 20:38:10 +00007895 switch (CompareStandardConversionSequences(S,
7896 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007897 Cand2.FinalConversion)) {
7898 case ImplicitConversionSequence::Better:
7899 // Cand1 has a better conversion sequence.
7900 return true;
7901
7902 case ImplicitConversionSequence::Worse:
7903 // Cand1 can't be better than Cand2.
7904 return false;
7905
7906 case ImplicitConversionSequence::Indistinguishable:
7907 // Do nothing
7908 break;
7909 }
7910 }
7911
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007912 return false;
7913}
7914
Mike Stump1eb44332009-09-09 15:08:12 +00007915/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007916/// within an overload candidate set.
7917///
James Dennettefce31f2012-06-22 08:10:18 +00007918/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007919/// which overload resolution occurs.
7920///
James Dennettefce31f2012-06-22 08:10:18 +00007921/// \param Best If overload resolution was successful or found a deleted
7922/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007923///
7924/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007925OverloadingResult
7926OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007927 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007928 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007929 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007930 Best = end();
7931 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7932 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007933 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007934 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007935 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007936 }
7937
7938 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007939 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007940 return OR_No_Viable_Function;
7941
7942 // Make sure that this function is better than every other viable
7943 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007944 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007945 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007946 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007947 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007948 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007949 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007950 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007951 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007952 }
Mike Stump1eb44332009-09-09 15:08:12 +00007953
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007954 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007955 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007956 (Best->Function->isDeleted() ||
7957 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007958 return OR_Deleted;
7959
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007960 return OR_Success;
7961}
7962
John McCall3c80f572010-01-12 02:15:36 +00007963namespace {
7964
7965enum OverloadCandidateKind {
7966 oc_function,
7967 oc_method,
7968 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007969 oc_function_template,
7970 oc_method_template,
7971 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007972 oc_implicit_default_constructor,
7973 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007974 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007975 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007976 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007977 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007978};
7979
John McCall220ccbf2010-01-13 00:25:19 +00007980OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7981 FunctionDecl *Fn,
7982 std::string &Description) {
7983 bool isTemplate = false;
7984
7985 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7986 isTemplate = true;
7987 Description = S.getTemplateArgumentBindingsText(
7988 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7989 }
John McCallb1622a12010-01-06 09:43:14 +00007990
7991 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007992 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007993 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007994
Sebastian Redlf677ea32011-02-05 19:23:19 +00007995 if (Ctor->getInheritedConstructor())
7996 return oc_implicit_inherited_constructor;
7997
Sean Hunt82713172011-05-25 23:16:36 +00007998 if (Ctor->isDefaultConstructor())
7999 return oc_implicit_default_constructor;
8000
8001 if (Ctor->isMoveConstructor())
8002 return oc_implicit_move_constructor;
8003
8004 assert(Ctor->isCopyConstructor() &&
8005 "unexpected sort of implicit constructor");
8006 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008007 }
8008
8009 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8010 // This actually gets spelled 'candidate function' for now, but
8011 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008012 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008013 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008014
Sean Hunt82713172011-05-25 23:16:36 +00008015 if (Meth->isMoveAssignmentOperator())
8016 return oc_implicit_move_assignment;
8017
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008018 if (Meth->isCopyAssignmentOperator())
8019 return oc_implicit_copy_assignment;
8020
8021 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8022 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008023 }
8024
John McCall220ccbf2010-01-13 00:25:19 +00008025 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008026}
8027
Sebastian Redlf677ea32011-02-05 19:23:19 +00008028void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8029 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8030 if (!Ctor) return;
8031
8032 Ctor = Ctor->getInheritedConstructor();
8033 if (!Ctor) return;
8034
8035 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8036}
8037
John McCall3c80f572010-01-12 02:15:36 +00008038} // end anonymous namespace
8039
8040// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008041void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008042 std::string FnDesc;
8043 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008044 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8045 << (unsigned) K << FnDesc;
8046 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8047 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008048 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008049}
8050
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008051//Notes the location of all overload candidates designated through
8052// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008053void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008054 assert(OverloadedExpr->getType() == Context.OverloadTy);
8055
8056 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8057 OverloadExpr *OvlExpr = Ovl.Expression;
8058
8059 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8060 IEnd = OvlExpr->decls_end();
8061 I != IEnd; ++I) {
8062 if (FunctionTemplateDecl *FunTmpl =
8063 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008064 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008065 } else if (FunctionDecl *Fun
8066 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008067 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008068 }
8069 }
8070}
8071
John McCall1d318332010-01-12 00:44:57 +00008072/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8073/// "lead" diagnostic; it will be given two arguments, the source and
8074/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008075void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8076 Sema &S,
8077 SourceLocation CaretLoc,
8078 const PartialDiagnostic &PDiag) const {
8079 S.Diag(CaretLoc, PDiag)
8080 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008081 // FIXME: The note limiting machinery is borrowed from
8082 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8083 // refactoring here.
8084 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8085 unsigned CandsShown = 0;
8086 AmbiguousConversionSequence::const_iterator I, E;
8087 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8088 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8089 break;
8090 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008091 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008092 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008093 if (I != E)
8094 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008095}
8096
John McCall1d318332010-01-12 00:44:57 +00008097namespace {
8098
John McCalladbb8f82010-01-13 09:16:55 +00008099void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8100 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8101 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008102 assert(Cand->Function && "for now, candidate must be a function");
8103 FunctionDecl *Fn = Cand->Function;
8104
8105 // There's a conversion slot for the object argument if this is a
8106 // non-constructor method. Note that 'I' corresponds the
8107 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008108 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008109 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008110 if (I == 0)
8111 isObjectArgument = true;
8112 else
8113 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008114 }
8115
John McCall220ccbf2010-01-13 00:25:19 +00008116 std::string FnDesc;
8117 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8118
John McCalladbb8f82010-01-13 09:16:55 +00008119 Expr *FromExpr = Conv.Bad.FromExpr;
8120 QualType FromTy = Conv.Bad.getFromType();
8121 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008122
John McCall5920dbb2010-02-02 02:42:52 +00008123 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008124 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008125 Expr *E = FromExpr->IgnoreParens();
8126 if (isa<UnaryOperator>(E))
8127 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008128 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008129
8130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8131 << (unsigned) FnKind << FnDesc
8132 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8133 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008134 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008135 return;
8136 }
8137
John McCall258b2032010-01-23 08:10:49 +00008138 // Do some hand-waving analysis to see if the non-viability is due
8139 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008140 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8141 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8142 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8143 CToTy = RT->getPointeeType();
8144 else {
8145 // TODO: detect and diagnose the full richness of const mismatches.
8146 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8147 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8148 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8149 }
8150
8151 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8152 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008153 Qualifiers FromQs = CFromTy.getQualifiers();
8154 Qualifiers ToQs = CToTy.getQualifiers();
8155
8156 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8157 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8158 << (unsigned) FnKind << FnDesc
8159 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8160 << FromTy
8161 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8162 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008163 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008164 return;
8165 }
8166
John McCallf85e1932011-06-15 23:02:42 +00008167 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008169 << (unsigned) FnKind << FnDesc
8170 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8171 << FromTy
8172 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8173 << (unsigned) isObjectArgument << I+1;
8174 MaybeEmitInheritedConstructorNote(S, Fn);
8175 return;
8176 }
8177
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008178 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8180 << (unsigned) FnKind << FnDesc
8181 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8182 << FromTy
8183 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8184 << (unsigned) isObjectArgument << I+1;
8185 MaybeEmitInheritedConstructorNote(S, Fn);
8186 return;
8187 }
8188
John McCall651f3ee2010-01-14 03:28:57 +00008189 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8190 assert(CVR && "unexpected qualifiers mismatch");
8191
8192 if (isObjectArgument) {
8193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8194 << (unsigned) FnKind << FnDesc
8195 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8196 << FromTy << (CVR - 1);
8197 } else {
8198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8199 << (unsigned) FnKind << FnDesc
8200 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8201 << FromTy << (CVR - 1) << I+1;
8202 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008203 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008204 return;
8205 }
8206
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008207 // Special diagnostic for failure to convert an initializer list, since
8208 // telling the user that it has type void is not useful.
8209 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8210 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8211 << (unsigned) FnKind << FnDesc
8212 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8213 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8214 MaybeEmitInheritedConstructorNote(S, Fn);
8215 return;
8216 }
8217
John McCall258b2032010-01-23 08:10:49 +00008218 // Diagnose references or pointers to incomplete types differently,
8219 // since it's far from impossible that the incompleteness triggered
8220 // the failure.
8221 QualType TempFromTy = FromTy.getNonReferenceType();
8222 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8223 TempFromTy = PTy->getPointeeType();
8224 if (TempFromTy->isIncompleteType()) {
8225 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8226 << (unsigned) FnKind << FnDesc
8227 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8228 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008229 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008230 return;
8231 }
8232
Douglas Gregor85789812010-06-30 23:01:39 +00008233 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008234 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008235 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8236 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8237 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8238 FromPtrTy->getPointeeType()) &&
8239 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8240 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008241 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008242 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008243 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008244 }
8245 } else if (const ObjCObjectPointerType *FromPtrTy
8246 = FromTy->getAs<ObjCObjectPointerType>()) {
8247 if (const ObjCObjectPointerType *ToPtrTy
8248 = ToTy->getAs<ObjCObjectPointerType>())
8249 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8250 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8251 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8252 FromPtrTy->getPointeeType()) &&
8253 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008254 BaseToDerivedConversion = 2;
8255 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008256 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8257 !FromTy->isIncompleteType() &&
8258 !ToRefTy->getPointeeType()->isIncompleteType() &&
8259 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8260 BaseToDerivedConversion = 3;
8261 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8262 ToTy.getNonReferenceType().getCanonicalType() ==
8263 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8265 << (unsigned) FnKind << FnDesc
8266 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8267 << (unsigned) isObjectArgument << I + 1;
8268 MaybeEmitInheritedConstructorNote(S, Fn);
8269 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008270 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008271 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008272
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008273 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008274 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008275 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008276 << (unsigned) FnKind << FnDesc
8277 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008278 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008279 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008280 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008281 return;
8282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008283
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008284 if (isa<ObjCObjectPointerType>(CFromTy) &&
8285 isa<PointerType>(CToTy)) {
8286 Qualifiers FromQs = CFromTy.getQualifiers();
8287 Qualifiers ToQs = CToTy.getQualifiers();
8288 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8289 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8290 << (unsigned) FnKind << FnDesc
8291 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8292 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8293 MaybeEmitInheritedConstructorNote(S, Fn);
8294 return;
8295 }
8296 }
8297
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008298 // Emit the generic diagnostic and, optionally, add the hints to it.
8299 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8300 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008301 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008302 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8303 << (unsigned) (Cand->Fix.Kind);
8304
8305 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008306 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8307 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008308 FDiag << *HI;
8309 S.Diag(Fn->getLocation(), FDiag);
8310
Sebastian Redlf677ea32011-02-05 19:23:19 +00008311 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008312}
8313
8314void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8315 unsigned NumFormalArgs) {
8316 // TODO: treat calls to a missing default constructor as a special case
8317
8318 FunctionDecl *Fn = Cand->Function;
8319 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8320
8321 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008322
Douglas Gregor439d3c32011-05-05 00:13:13 +00008323 // With invalid overloaded operators, it's possible that we think we
8324 // have an arity mismatch when it fact it looks like we have the
8325 // right number of arguments, because only overloaded operators have
8326 // the weird behavior of overloading member and non-member functions.
8327 // Just don't report anything.
8328 if (Fn->isInvalidDecl() &&
8329 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8330 return;
8331
John McCalladbb8f82010-01-13 09:16:55 +00008332 // at least / at most / exactly
8333 unsigned mode, modeCount;
8334 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008335 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8336 (Cand->FailureKind == ovl_fail_bad_deduction &&
8337 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008338 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008339 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008340 mode = 0; // "at least"
8341 else
8342 mode = 2; // "exactly"
8343 modeCount = MinParams;
8344 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008345 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8346 (Cand->FailureKind == ovl_fail_bad_deduction &&
8347 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008348 if (MinParams != FnTy->getNumArgs())
8349 mode = 1; // "at most"
8350 else
8351 mode = 2; // "exactly"
8352 modeCount = FnTy->getNumArgs();
8353 }
8354
8355 std::string Description;
8356 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8357
Richard Smithf7b80562012-05-11 05:16:41 +00008358 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8360 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8361 << Fn->getParamDecl(0) << NumFormalArgs;
8362 else
8363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8364 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8365 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008366 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008367}
8368
John McCall342fec42010-02-01 18:53:26 +00008369/// Diagnose a failed template-argument deduction.
8370void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008371 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008372 FunctionDecl *Fn = Cand->Function; // pattern
8373
Douglas Gregora9333192010-05-08 17:41:32 +00008374 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008375 NamedDecl *ParamD;
8376 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8377 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8378 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008379 switch (Cand->DeductionFailure.Result) {
8380 case Sema::TDK_Success:
8381 llvm_unreachable("TDK_success while diagnosing bad deduction");
8382
8383 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008384 assert(ParamD && "no parameter found for incomplete deduction result");
8385 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8386 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008387 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008388 return;
8389 }
8390
John McCall57e97782010-08-05 09:05:08 +00008391 case Sema::TDK_Underqualified: {
8392 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8393 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8394
8395 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8396
8397 // Param will have been canonicalized, but it should just be a
8398 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008399 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008400 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008401 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008402 assert(S.Context.hasSameType(Param, NonCanonParam));
8403
8404 // Arg has also been canonicalized, but there's nothing we can do
8405 // about that. It also doesn't matter as much, because it won't
8406 // have any template parameters in it (because deduction isn't
8407 // done on dependent types).
8408 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8409
8410 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8411 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008412 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008413 return;
8414 }
8415
8416 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008417 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008418 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008419 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008420 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008421 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008422 which = 1;
8423 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008424 which = 2;
8425 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008426
Douglas Gregora9333192010-05-08 17:41:32 +00008427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008428 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008429 << *Cand->DeductionFailure.getFirstArg()
8430 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008431 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008432 return;
8433 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008434
Douglas Gregorf1a84452010-05-08 19:15:54 +00008435 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008436 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008437 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008438 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008439 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8440 << ParamD->getDeclName();
8441 else {
8442 int index = 0;
8443 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8444 index = TTP->getIndex();
8445 else if (NonTypeTemplateParmDecl *NTTP
8446 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8447 index = NTTP->getIndex();
8448 else
8449 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008450 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008451 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8452 << (index + 1);
8453 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008454 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008455 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008456
Douglas Gregora18592e2010-05-08 18:13:28 +00008457 case Sema::TDK_TooManyArguments:
8458 case Sema::TDK_TooFewArguments:
8459 DiagnoseArityMismatch(S, Cand, NumArgs);
8460 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008461
8462 case Sema::TDK_InstantiationDepth:
8463 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008464 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008465 return;
8466
8467 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008468 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008469 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008470 if (TemplateArgumentList *Args =
8471 Cand->DeductionFailure.getTemplateArgumentList()) {
8472 TemplateArgString = " ";
8473 TemplateArgString += S.getTemplateArgumentBindingsText(
8474 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8475 }
8476
Richard Smith4493c0a2012-05-09 05:17:00 +00008477 // If this candidate was disabled by enable_if, say so.
8478 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8479 if (PDiag && PDiag->second.getDiagID() ==
8480 diag::err_typename_nested_not_found_enable_if) {
8481 // FIXME: Use the source range of the condition, and the fully-qualified
8482 // name of the enable_if template. These are both present in PDiag.
8483 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8484 << "'enable_if'" << TemplateArgString;
8485 return;
8486 }
8487
Richard Smithb8590f32012-05-07 09:03:25 +00008488 // Format the SFINAE diagnostic into the argument string.
8489 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8490 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008491 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008492 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008493 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008494 SFINAEArgString = ": ";
8495 R = SourceRange(PDiag->first, PDiag->first);
8496 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8497 }
8498
Douglas Gregorec20f462010-05-08 20:07:26 +00008499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008500 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008501 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008502 return;
8503 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008504
Richard Smith0efa62f2013-01-31 04:03:12 +00008505 case Sema::TDK_FailedOverloadResolution: {
8506 OverloadExpr::FindResult R =
8507 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8508 S.Diag(Fn->getLocation(),
8509 diag::note_ovl_candidate_failed_overload_resolution)
8510 << R.Expression->getName();
8511 return;
8512 }
8513
Richard Trieueef35f82013-04-08 21:11:40 +00008514 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008515 // FIXME: Provide a source location to indicate what we couldn't match.
Richard Trieueef35f82013-04-08 21:11:40 +00008516 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8517 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
8518 if (FirstTA.getKind() == TemplateArgument::Template &&
8519 SecondTA.getKind() == TemplateArgument::Template) {
8520 TemplateName FirstTN = FirstTA.getAsTemplate();
8521 TemplateName SecondTN = SecondTA.getAsTemplate();
8522 if (FirstTN.getKind() == TemplateName::Template &&
8523 SecondTN.getKind() == TemplateName::Template) {
8524 if (FirstTN.getAsTemplateDecl()->getName() ==
8525 SecondTN.getAsTemplateDecl()->getName()) {
8526 // FIXME: This fixes a bad diagnostic where both templates are named
8527 // the same. This particular case is a bit difficult since:
8528 // 1) It is passed as a string to the diagnostic printer.
8529 // 2) The diagnostic printer only attempts to find a better
8530 // name for types, not decls.
8531 // Ideally, this should folded into the diagnostic printer.
8532 S.Diag(Fn->getLocation(),
8533 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8534 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8535 return;
8536 }
8537 }
8538 }
Richard Smith29805ca2013-01-31 05:19:49 +00008539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
Richard Trieueef35f82013-04-08 21:11:40 +00008540 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008541 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008542 }
John McCall342fec42010-02-01 18:53:26 +00008543 // TODO: diagnose these individually, then kill off
8544 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008545 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008546 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008547 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008548 return;
8549 }
8550}
8551
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008552/// CUDA: diagnose an invalid call across targets.
8553void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8554 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8555 FunctionDecl *Callee = Cand->Function;
8556
8557 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8558 CalleeTarget = S.IdentifyCUDATarget(Callee);
8559
8560 std::string FnDesc;
8561 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8562
8563 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8564 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8565}
8566
John McCall342fec42010-02-01 18:53:26 +00008567/// Generates a 'note' diagnostic for an overload candidate. We've
8568/// already generated a primary error at the call site.
8569///
8570/// It really does need to be a single diagnostic with its caret
8571/// pointed at the candidate declaration. Yes, this creates some
8572/// major challenges of technical writing. Yes, this makes pointing
8573/// out problems with specific arguments quite awkward. It's still
8574/// better than generating twenty screens of text for every failed
8575/// overload.
8576///
8577/// It would be great to be able to express per-candidate problems
8578/// more richly for those diagnostic clients that cared, but we'd
8579/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008580void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008581 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008582 FunctionDecl *Fn = Cand->Function;
8583
John McCall81201622010-01-08 04:41:39 +00008584 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008585 if (Cand->Viable && (Fn->isDeleted() ||
8586 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008587 std::string FnDesc;
8588 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008589
8590 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008591 << FnKind << FnDesc
8592 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008593 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008594 return;
John McCall81201622010-01-08 04:41:39 +00008595 }
8596
John McCall220ccbf2010-01-13 00:25:19 +00008597 // We don't really have anything else to say about viable candidates.
8598 if (Cand->Viable) {
8599 S.NoteOverloadCandidate(Fn);
8600 return;
8601 }
John McCall1d318332010-01-12 00:44:57 +00008602
John McCalladbb8f82010-01-13 09:16:55 +00008603 switch (Cand->FailureKind) {
8604 case ovl_fail_too_many_arguments:
8605 case ovl_fail_too_few_arguments:
8606 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008607
John McCalladbb8f82010-01-13 09:16:55 +00008608 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008609 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008610
John McCall717e8912010-01-23 05:17:32 +00008611 case ovl_fail_trivial_conversion:
8612 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008613 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008614 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008615
John McCallb1bdc622010-02-25 01:37:24 +00008616 case ovl_fail_bad_conversion: {
8617 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008618 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008619 if (Cand->Conversions[I].isBad())
8620 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008621
John McCalladbb8f82010-01-13 09:16:55 +00008622 // FIXME: this currently happens when we're called from SemaInit
8623 // when user-conversion overload fails. Figure out how to handle
8624 // those conditions and diagnose them well.
8625 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008626 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008627
8628 case ovl_fail_bad_target:
8629 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008630 }
John McCalla1d7d622010-01-08 00:58:21 +00008631}
8632
8633void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8634 // Desugar the type of the surrogate down to a function type,
8635 // retaining as many typedefs as possible while still showing
8636 // the function type (and, therefore, its parameter types).
8637 QualType FnType = Cand->Surrogate->getConversionType();
8638 bool isLValueReference = false;
8639 bool isRValueReference = false;
8640 bool isPointer = false;
8641 if (const LValueReferenceType *FnTypeRef =
8642 FnType->getAs<LValueReferenceType>()) {
8643 FnType = FnTypeRef->getPointeeType();
8644 isLValueReference = true;
8645 } else if (const RValueReferenceType *FnTypeRef =
8646 FnType->getAs<RValueReferenceType>()) {
8647 FnType = FnTypeRef->getPointeeType();
8648 isRValueReference = true;
8649 }
8650 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8651 FnType = FnTypePtr->getPointeeType();
8652 isPointer = true;
8653 }
8654 // Desugar down to a function type.
8655 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8656 // Reconstruct the pointer/reference as appropriate.
8657 if (isPointer) FnType = S.Context.getPointerType(FnType);
8658 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8659 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8660
8661 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8662 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008663 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008664}
8665
8666void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008667 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008668 SourceLocation OpLoc,
8669 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008670 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008671 std::string TypeStr("operator");
8672 TypeStr += Opc;
8673 TypeStr += "(";
8674 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008675 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008676 TypeStr += ")";
8677 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8678 } else {
8679 TypeStr += ", ";
8680 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8681 TypeStr += ")";
8682 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8683 }
8684}
8685
8686void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8687 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008688 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008689 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8690 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008691 if (ICS.isBad()) break; // all meaningless after first invalid
8692 if (!ICS.isAmbiguous()) continue;
8693
John McCall120d63c2010-08-24 20:38:10 +00008694 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008695 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008696 }
8697}
8698
John McCall1b77e732010-01-15 23:32:50 +00008699SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8700 if (Cand->Function)
8701 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008702 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008703 return Cand->Surrogate->getLocation();
8704 return SourceLocation();
8705}
8706
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008707static unsigned
8708RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008709 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008710 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008711 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008712
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008713 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008714 case Sema::TDK_Incomplete:
8715 return 1;
8716
8717 case Sema::TDK_Underqualified:
8718 case Sema::TDK_Inconsistent:
8719 return 2;
8720
8721 case Sema::TDK_SubstitutionFailure:
8722 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008723 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008724 return 3;
8725
8726 case Sema::TDK_InstantiationDepth:
8727 case Sema::TDK_FailedOverloadResolution:
8728 return 4;
8729
8730 case Sema::TDK_InvalidExplicitArguments:
8731 return 5;
8732
8733 case Sema::TDK_TooManyArguments:
8734 case Sema::TDK_TooFewArguments:
8735 return 6;
8736 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008737 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008738}
8739
John McCallbf65c0b2010-01-12 00:48:53 +00008740struct CompareOverloadCandidatesForDisplay {
8741 Sema &S;
8742 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008743
8744 bool operator()(const OverloadCandidate *L,
8745 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008746 // Fast-path this check.
8747 if (L == R) return false;
8748
John McCall81201622010-01-08 04:41:39 +00008749 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008750 if (L->Viable) {
8751 if (!R->Viable) return true;
8752
8753 // TODO: introduce a tri-valued comparison for overload
8754 // candidates. Would be more worthwhile if we had a sort
8755 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008756 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8757 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008758 } else if (R->Viable)
8759 return false;
John McCall81201622010-01-08 04:41:39 +00008760
John McCall1b77e732010-01-15 23:32:50 +00008761 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008762
John McCall1b77e732010-01-15 23:32:50 +00008763 // Criteria by which we can sort non-viable candidates:
8764 if (!L->Viable) {
8765 // 1. Arity mismatches come after other candidates.
8766 if (L->FailureKind == ovl_fail_too_many_arguments ||
8767 L->FailureKind == ovl_fail_too_few_arguments)
8768 return false;
8769 if (R->FailureKind == ovl_fail_too_many_arguments ||
8770 R->FailureKind == ovl_fail_too_few_arguments)
8771 return true;
John McCall81201622010-01-08 04:41:39 +00008772
John McCall717e8912010-01-23 05:17:32 +00008773 // 2. Bad conversions come first and are ordered by the number
8774 // of bad conversions and quality of good conversions.
8775 if (L->FailureKind == ovl_fail_bad_conversion) {
8776 if (R->FailureKind != ovl_fail_bad_conversion)
8777 return true;
8778
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008779 // The conversion that can be fixed with a smaller number of changes,
8780 // comes first.
8781 unsigned numLFixes = L->Fix.NumConversionsFixed;
8782 unsigned numRFixes = R->Fix.NumConversionsFixed;
8783 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8784 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008785 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008786 if (numLFixes < numRFixes)
8787 return true;
8788 else
8789 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008790 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008791
John McCall717e8912010-01-23 05:17:32 +00008792 // If there's any ordering between the defined conversions...
8793 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008794 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008795
8796 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008797 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008798 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008799 switch (CompareImplicitConversionSequences(S,
8800 L->Conversions[I],
8801 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008802 case ImplicitConversionSequence::Better:
8803 leftBetter++;
8804 break;
8805
8806 case ImplicitConversionSequence::Worse:
8807 leftBetter--;
8808 break;
8809
8810 case ImplicitConversionSequence::Indistinguishable:
8811 break;
8812 }
8813 }
8814 if (leftBetter > 0) return true;
8815 if (leftBetter < 0) return false;
8816
8817 } else if (R->FailureKind == ovl_fail_bad_conversion)
8818 return false;
8819
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008820 if (L->FailureKind == ovl_fail_bad_deduction) {
8821 if (R->FailureKind != ovl_fail_bad_deduction)
8822 return true;
8823
8824 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8825 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008826 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008827 } else if (R->FailureKind == ovl_fail_bad_deduction)
8828 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008829
John McCall1b77e732010-01-15 23:32:50 +00008830 // TODO: others?
8831 }
8832
8833 // Sort everything else by location.
8834 SourceLocation LLoc = GetLocationForCandidate(L);
8835 SourceLocation RLoc = GetLocationForCandidate(R);
8836
8837 // Put candidates without locations (e.g. builtins) at the end.
8838 if (LLoc.isInvalid()) return false;
8839 if (RLoc.isInvalid()) return true;
8840
8841 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008842 }
8843};
8844
John McCall717e8912010-01-23 05:17:32 +00008845/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008846/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008847void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008848 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008849 assert(!Cand->Viable);
8850
8851 // Don't do anything on failures other than bad conversion.
8852 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8853
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008854 // We only want the FixIts if all the arguments can be corrected.
8855 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008856 // Use a implicit copy initialization to check conversion fixes.
8857 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008858
John McCall717e8912010-01-23 05:17:32 +00008859 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008860 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008861 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008862 while (true) {
8863 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8864 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008865 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008866 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008867 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008868 }
John McCall717e8912010-01-23 05:17:32 +00008869 }
8870
8871 if (ConvIdx == ConvCount)
8872 return;
8873
John McCallb1bdc622010-02-25 01:37:24 +00008874 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8875 "remaining conversion is initialized?");
8876
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008877 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008878 // operation somehow.
8879 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008880
8881 const FunctionProtoType* Proto;
8882 unsigned ArgIdx = ConvIdx;
8883
8884 if (Cand->IsSurrogate) {
8885 QualType ConvType
8886 = Cand->Surrogate->getConversionType().getNonReferenceType();
8887 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8888 ConvType = ConvPtrType->getPointeeType();
8889 Proto = ConvType->getAs<FunctionProtoType>();
8890 ArgIdx--;
8891 } else if (Cand->Function) {
8892 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8893 if (isa<CXXMethodDecl>(Cand->Function) &&
8894 !isa<CXXConstructorDecl>(Cand->Function))
8895 ArgIdx--;
8896 } else {
8897 // Builtin binary operator with a bad first conversion.
8898 assert(ConvCount <= 3);
8899 for (; ConvIdx != ConvCount; ++ConvIdx)
8900 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008901 = TryCopyInitialization(S, Args[ConvIdx],
8902 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008903 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008904 /*InOverloadResolution*/ true,
8905 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008906 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008907 return;
8908 }
8909
8910 // Fill in the rest of the conversions.
8911 unsigned NumArgsInProto = Proto->getNumArgs();
8912 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008913 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008914 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008915 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008916 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008917 /*InOverloadResolution=*/true,
8918 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008919 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008920 // Store the FixIt in the candidate if it exists.
8921 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008922 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008923 }
John McCall717e8912010-01-23 05:17:32 +00008924 else
8925 Cand->Conversions[ConvIdx].setEllipsis();
8926 }
8927}
8928
John McCalla1d7d622010-01-08 00:58:21 +00008929} // end anonymous namespace
8930
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008931/// PrintOverloadCandidates - When overload resolution fails, prints
8932/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008933/// set.
John McCall120d63c2010-08-24 20:38:10 +00008934void OverloadCandidateSet::NoteCandidates(Sema &S,
8935 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008936 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008937 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008938 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008939 // Sort the candidates by viability and position. Sorting directly would
8940 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008941 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008942 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8943 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008944 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008945 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008946 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008947 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008948 if (Cand->Function || Cand->IsSurrogate)
8949 Cands.push_back(Cand);
8950 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8951 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008952 }
8953 }
8954
John McCallbf65c0b2010-01-12 00:48:53 +00008955 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008956 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008957
John McCall1d318332010-01-12 00:44:57 +00008958 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008959
Chris Lattner5f9e2722011-07-23 10:55:15 +00008960 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008961 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008962 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008963 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8964 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008965
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008966 // Set an arbitrary limit on the number of candidate functions we'll spam
8967 // the user with. FIXME: This limit should depend on details of the
8968 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008969 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008970 break;
8971 }
8972 ++CandsShown;
8973
John McCalla1d7d622010-01-08 00:58:21 +00008974 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008975 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008976 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008977 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008978 else {
8979 assert(Cand->Viable &&
8980 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008981 // Generally we only see ambiguities including viable builtin
8982 // operators if overload resolution got screwed up by an
8983 // ambiguous user-defined conversion.
8984 //
8985 // FIXME: It's quite possible for different conversions to see
8986 // different ambiguities, though.
8987 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008988 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008989 ReportedAmbiguousConversions = true;
8990 }
John McCalla1d7d622010-01-08 00:58:21 +00008991
John McCall1d318332010-01-12 00:44:57 +00008992 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008993 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008994 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008995 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008996
8997 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008998 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008999}
9000
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009001// [PossiblyAFunctionType] --> [Return]
9002// NonFunctionType --> NonFunctionType
9003// R (A) --> R(A)
9004// R (*)(A) --> R (A)
9005// R (&)(A) --> R (A)
9006// R (S::*)(A) --> R (A)
9007QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9008 QualType Ret = PossiblyAFunctionType;
9009 if (const PointerType *ToTypePtr =
9010 PossiblyAFunctionType->getAs<PointerType>())
9011 Ret = ToTypePtr->getPointeeType();
9012 else if (const ReferenceType *ToTypeRef =
9013 PossiblyAFunctionType->getAs<ReferenceType>())
9014 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009015 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009016 PossiblyAFunctionType->getAs<MemberPointerType>())
9017 Ret = MemTypePtr->getPointeeType();
9018 Ret =
9019 Context.getCanonicalType(Ret).getUnqualifiedType();
9020 return Ret;
9021}
Douglas Gregor904eed32008-11-10 20:40:00 +00009022
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009023// A helper class to help with address of function resolution
9024// - allows us to avoid passing around all those ugly parameters
9025class AddressOfFunctionResolver
9026{
9027 Sema& S;
9028 Expr* SourceExpr;
9029 const QualType& TargetType;
9030 QualType TargetFunctionType; // Extracted function type from target type
9031
9032 bool Complain;
9033 //DeclAccessPair& ResultFunctionAccessPair;
9034 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009035
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009036 bool TargetTypeIsNonStaticMemberFunction;
9037 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009038
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009039 OverloadExpr::FindResult OvlExprInfo;
9040 OverloadExpr *OvlExpr;
9041 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009042 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009043
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009044public:
9045 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9046 const QualType& TargetType, bool Complain)
9047 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9048 Complain(Complain), Context(S.getASTContext()),
9049 TargetTypeIsNonStaticMemberFunction(
9050 !!TargetType->getAs<MemberPointerType>()),
9051 FoundNonTemplateFunction(false),
9052 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9053 OvlExpr(OvlExprInfo.Expression)
9054 {
9055 ExtractUnqualifiedFunctionTypeFromTargetType();
9056
9057 if (!TargetFunctionType->isFunctionType()) {
9058 if (OvlExpr->hasExplicitTemplateArgs()) {
9059 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009060 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009061 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009062
9063 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9064 if (!Method->isStatic()) {
9065 // If the target type is a non-function type and the function
9066 // found is a non-static member function, pretend as if that was
9067 // the target, it's the only possible type to end up with.
9068 TargetTypeIsNonStaticMemberFunction = true;
9069
9070 // And skip adding the function if its not in the proper form.
9071 // We'll diagnose this due to an empty set of functions.
9072 if (!OvlExprInfo.HasFormOfMemberPointer)
9073 return;
9074 }
9075 }
9076
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009077 Matches.push_back(std::make_pair(dap,Fn));
9078 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009079 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009080 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009081 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009082
9083 if (OvlExpr->hasExplicitTemplateArgs())
9084 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009085
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009086 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9087 // C++ [over.over]p4:
9088 // If more than one function is selected, [...]
9089 if (Matches.size() > 1) {
9090 if (FoundNonTemplateFunction)
9091 EliminateAllTemplateMatches();
9092 else
9093 EliminateAllExceptMostSpecializedTemplate();
9094 }
9095 }
9096 }
9097
9098private:
9099 bool isTargetTypeAFunction() const {
9100 return TargetFunctionType->isFunctionType();
9101 }
9102
9103 // [ToType] [Return]
9104
9105 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9106 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9107 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9108 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9109 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9110 }
9111
9112 // return true if any matching specializations were found
9113 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9114 const DeclAccessPair& CurAccessFunPair) {
9115 if (CXXMethodDecl *Method
9116 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9117 // Skip non-static function templates when converting to pointer, and
9118 // static when converting to member pointer.
9119 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9120 return false;
9121 }
9122 else if (TargetTypeIsNonStaticMemberFunction)
9123 return false;
9124
9125 // C++ [over.over]p2:
9126 // If the name is a function template, template argument deduction is
9127 // done (14.8.2.2), and if the argument deduction succeeds, the
9128 // resulting template argument list is used to generate a single
9129 // function template specialization, which is added to the set of
9130 // overloaded functions considered.
9131 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009132 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009133 if (Sema::TemplateDeductionResult Result
9134 = S.DeduceTemplateArguments(FunctionTemplate,
9135 &OvlExplicitTemplateArgs,
9136 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009137 Info, /*InOverloadResolution=*/true)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009138 // FIXME: make a note of the failed deduction for diagnostics.
9139 (void)Result;
9140 return false;
9141 }
9142
Douglas Gregor092140a2013-04-17 08:45:07 +00009143 // Template argument deduction ensures that we have an exact match or
9144 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009145 // This function template specicalization works.
9146 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009147 assert(S.isSameOrCompatibleFunctionType(
9148 Context.getCanonicalType(Specialization->getType()),
9149 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009150 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9151 return true;
9152 }
9153
9154 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9155 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009156 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009157 // Skip non-static functions when converting to pointer, and static
9158 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009159 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9160 return false;
9161 }
9162 else if (TargetTypeIsNonStaticMemberFunction)
9163 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009164
Chandler Carruthbd647292009-12-29 06:17:27 +00009165 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009166 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009167 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9168 if (S.CheckCUDATarget(Caller, FunDecl))
9169 return false;
9170
Douglas Gregor43c79c22009-12-09 00:47:37 +00009171 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009172 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9173 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009174 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9175 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009176 Matches.push_back(std::make_pair(CurAccessFunPair,
9177 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009178 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009179 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009180 }
Mike Stump1eb44332009-09-09 15:08:12 +00009181 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009182
9183 return false;
9184 }
9185
9186 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9187 bool Ret = false;
9188
9189 // If the overload expression doesn't have the form of a pointer to
9190 // member, don't try to convert it to a pointer-to-member type.
9191 if (IsInvalidFormOfPointerToMemberFunction())
9192 return false;
9193
9194 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9195 E = OvlExpr->decls_end();
9196 I != E; ++I) {
9197 // Look through any using declarations to find the underlying function.
9198 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9199
9200 // C++ [over.over]p3:
9201 // Non-member functions and static member functions match
9202 // targets of type "pointer-to-function" or "reference-to-function."
9203 // Nonstatic member functions match targets of
9204 // type "pointer-to-member-function."
9205 // Note that according to DR 247, the containing class does not matter.
9206 if (FunctionTemplateDecl *FunctionTemplate
9207 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9208 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9209 Ret = true;
9210 }
9211 // If we have explicit template arguments supplied, skip non-templates.
9212 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9213 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9214 Ret = true;
9215 }
9216 assert(Ret || Matches.empty());
9217 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009218 }
9219
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009220 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009221 // [...] and any given function template specialization F1 is
9222 // eliminated if the set contains a second function template
9223 // specialization whose function template is more specialized
9224 // than the function template of F1 according to the partial
9225 // ordering rules of 14.5.5.2.
9226
9227 // The algorithm specified above is quadratic. We instead use a
9228 // two-pass algorithm (similar to the one used to identify the
9229 // best viable function in an overload set) that identifies the
9230 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009231
9232 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9233 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9234 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009235
John McCallc373d482010-01-27 01:50:18 +00009236 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009237 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9238 TPOC_Other, 0, SourceExpr->getLocStart(),
9239 S.PDiag(),
9240 S.PDiag(diag::err_addr_ovl_ambiguous)
9241 << Matches[0].second->getDeclName(),
9242 S.PDiag(diag::note_ovl_candidate)
9243 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009244 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009245
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009246 if (Result != MatchesCopy.end()) {
9247 // Make it the first and only element
9248 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9249 Matches[0].second = cast<FunctionDecl>(*Result);
9250 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009251 }
9252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009253
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009254 void EliminateAllTemplateMatches() {
9255 // [...] any function template specializations in the set are
9256 // eliminated if the set also contains a non-template function, [...]
9257 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9258 if (Matches[I].second->getPrimaryTemplate() == 0)
9259 ++I;
9260 else {
9261 Matches[I] = Matches[--N];
9262 Matches.set_size(N);
9263 }
9264 }
9265 }
9266
9267public:
9268 void ComplainNoMatchesFound() const {
9269 assert(Matches.empty());
9270 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9271 << OvlExpr->getName() << TargetFunctionType
9272 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009273 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009274 }
9275
9276 bool IsInvalidFormOfPointerToMemberFunction() const {
9277 return TargetTypeIsNonStaticMemberFunction &&
9278 !OvlExprInfo.HasFormOfMemberPointer;
9279 }
9280
9281 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9282 // TODO: Should we condition this on whether any functions might
9283 // have matched, or is it more appropriate to do that in callers?
9284 // TODO: a fixit wouldn't hurt.
9285 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9286 << TargetType << OvlExpr->getSourceRange();
9287 }
9288
9289 void ComplainOfInvalidConversion() const {
9290 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9291 << OvlExpr->getName() << TargetType;
9292 }
9293
9294 void ComplainMultipleMatchesFound() const {
9295 assert(Matches.size() > 1);
9296 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9297 << OvlExpr->getName()
9298 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009299 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009300 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009301
9302 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9303
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009304 int getNumMatches() const { return Matches.size(); }
9305
9306 FunctionDecl* getMatchingFunctionDecl() const {
9307 if (Matches.size() != 1) return 0;
9308 return Matches[0].second;
9309 }
9310
9311 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9312 if (Matches.size() != 1) return 0;
9313 return &Matches[0].first;
9314 }
9315};
9316
9317/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9318/// an overloaded function (C++ [over.over]), where @p From is an
9319/// expression with overloaded function type and @p ToType is the type
9320/// we're trying to resolve to. For example:
9321///
9322/// @code
9323/// int f(double);
9324/// int f(int);
9325///
9326/// int (*pfd)(double) = f; // selects f(double)
9327/// @endcode
9328///
9329/// This routine returns the resulting FunctionDecl if it could be
9330/// resolved, and NULL otherwise. When @p Complain is true, this
9331/// routine will emit diagnostics if there is an error.
9332FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009333Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9334 QualType TargetType,
9335 bool Complain,
9336 DeclAccessPair &FoundResult,
9337 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009338 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009339
9340 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9341 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009342 int NumMatches = Resolver.getNumMatches();
9343 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009344 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009345 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9346 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9347 else
9348 Resolver.ComplainNoMatchesFound();
9349 }
9350 else if (NumMatches > 1 && Complain)
9351 Resolver.ComplainMultipleMatchesFound();
9352 else if (NumMatches == 1) {
9353 Fn = Resolver.getMatchingFunctionDecl();
9354 assert(Fn);
9355 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009356 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009357 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009358 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009359
9360 if (pHadMultipleCandidates)
9361 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009362 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009363}
9364
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009365/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009366/// resolve that overloaded function expression down to a single function.
9367///
9368/// This routine can only resolve template-ids that refer to a single function
9369/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009370/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009371/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009372FunctionDecl *
9373Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9374 bool Complain,
9375 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009376 // C++ [over.over]p1:
9377 // [...] [Note: any redundant set of parentheses surrounding the
9378 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009379 // C++ [over.over]p1:
9380 // [...] The overloaded function name can be preceded by the &
9381 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009382
Douglas Gregor4b52e252009-12-21 23:17:24 +00009383 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009384 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009385 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009386
9387 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009388 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009389
Douglas Gregor4b52e252009-12-21 23:17:24 +00009390 // Look through all of the overloaded functions, searching for one
9391 // whose type matches exactly.
9392 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009393 for (UnresolvedSetIterator I = ovl->decls_begin(),
9394 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009395 // C++0x [temp.arg.explicit]p3:
9396 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009397 // where deduction is not done, if a template argument list is
9398 // specified and it, along with any default template arguments,
9399 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009400 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009401 FunctionTemplateDecl *FunctionTemplate
9402 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009403
Douglas Gregor4b52e252009-12-21 23:17:24 +00009404 // C++ [over.over]p2:
9405 // If the name is a function template, template argument deduction is
9406 // done (14.8.2.2), and if the argument deduction succeeds, the
9407 // resulting template argument list is used to generate a single
9408 // function template specialization, which is added to the set of
9409 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009410 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009411 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009412 if (TemplateDeductionResult Result
9413 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009414 Specialization, Info,
9415 /*InOverloadResolution=*/true)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009416 // FIXME: make a note of the failed deduction for diagnostics.
9417 (void)Result;
9418 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009419 }
9420
John McCall864c0412011-04-26 20:42:42 +00009421 assert(Specialization && "no specialization and no error?");
9422
Douglas Gregor4b52e252009-12-21 23:17:24 +00009423 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009424 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009425 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009426 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9427 << ovl->getName();
9428 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009429 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009430 return 0;
John McCall864c0412011-04-26 20:42:42 +00009431 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009432
John McCall864c0412011-04-26 20:42:42 +00009433 Matched = Specialization;
9434 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009435 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009436
Douglas Gregor4b52e252009-12-21 23:17:24 +00009437 return Matched;
9438}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009439
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009440
9441
9442
John McCall6dbba4f2011-10-11 23:14:30 +00009443// Resolve and fix an overloaded expression that can be resolved
9444// because it identifies a single function template specialization.
9445//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009446// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009447//
9448// Return true if it was logically possible to so resolve the
9449// expression, regardless of whether or not it succeeded. Always
9450// returns true if 'complain' is set.
9451bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9452 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9453 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009454 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009455 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009456 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009457
John McCall6dbba4f2011-10-11 23:14:30 +00009458 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009459
John McCall864c0412011-04-26 20:42:42 +00009460 DeclAccessPair found;
9461 ExprResult SingleFunctionExpression;
9462 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9463 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009464 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009465 SrcExpr = ExprError();
9466 return true;
9467 }
John McCall864c0412011-04-26 20:42:42 +00009468
9469 // It is only correct to resolve to an instance method if we're
9470 // resolving a form that's permitted to be a pointer to member.
9471 // Otherwise we'll end up making a bound member expression, which
9472 // is illegal in all the contexts we resolve like this.
9473 if (!ovl.HasFormOfMemberPointer &&
9474 isa<CXXMethodDecl>(fn) &&
9475 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009476 if (!complain) return false;
9477
9478 Diag(ovl.Expression->getExprLoc(),
9479 diag::err_bound_member_function)
9480 << 0 << ovl.Expression->getSourceRange();
9481
9482 // TODO: I believe we only end up here if there's a mix of
9483 // static and non-static candidates (otherwise the expression
9484 // would have 'bound member' type, not 'overload' type).
9485 // Ideally we would note which candidate was chosen and why
9486 // the static candidates were rejected.
9487 SrcExpr = ExprError();
9488 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009489 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009490
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009491 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009492 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009493 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009494
9495 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009496 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009497 SingleFunctionExpression =
9498 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009499 if (SingleFunctionExpression.isInvalid()) {
9500 SrcExpr = ExprError();
9501 return true;
9502 }
9503 }
John McCall864c0412011-04-26 20:42:42 +00009504 }
9505
9506 if (!SingleFunctionExpression.isUsable()) {
9507 if (complain) {
9508 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9509 << ovl.Expression->getName()
9510 << DestTypeForComplaining
9511 << OpRangeForComplaining
9512 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009513 NoteAllOverloadCandidates(SrcExpr.get());
9514
9515 SrcExpr = ExprError();
9516 return true;
9517 }
9518
9519 return false;
John McCall864c0412011-04-26 20:42:42 +00009520 }
9521
John McCall6dbba4f2011-10-11 23:14:30 +00009522 SrcExpr = SingleFunctionExpression;
9523 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009524}
9525
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009526/// \brief Add a single candidate to the overload set.
9527static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009528 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009529 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009530 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009531 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009532 bool PartialOverloading,
9533 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009534 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009535 if (isa<UsingShadowDecl>(Callee))
9536 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9537
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009538 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009539 if (ExplicitTemplateArgs) {
9540 assert(!KnownValid && "Explicit template arguments?");
9541 return;
9542 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009543 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9544 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009545 return;
John McCallba135432009-11-21 08:51:07 +00009546 }
9547
9548 if (FunctionTemplateDecl *FuncTemplate
9549 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009550 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009551 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009552 return;
9553 }
9554
Richard Smith2ced0442011-06-26 22:19:54 +00009555 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009556}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009557
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009558/// \brief Add the overload candidates named by callee and/or found by argument
9559/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009560void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009561 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009562 OverloadCandidateSet &CandidateSet,
9563 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009564
9565#ifndef NDEBUG
9566 // Verify that ArgumentDependentLookup is consistent with the rules
9567 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009568 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009569 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9570 // and let Y be the lookup set produced by argument dependent
9571 // lookup (defined as follows). If X contains
9572 //
9573 // -- a declaration of a class member, or
9574 //
9575 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009576 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009577 //
9578 // -- a declaration that is neither a function or a function
9579 // template
9580 //
9581 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009582
John McCall3b4294e2009-12-16 12:17:52 +00009583 if (ULE->requiresADL()) {
9584 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9585 E = ULE->decls_end(); I != E; ++I) {
9586 assert(!(*I)->getDeclContext()->isRecord());
9587 assert(isa<UsingShadowDecl>(*I) ||
9588 !(*I)->getDeclContext()->isFunctionOrMethod());
9589 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009590 }
9591 }
9592#endif
9593
John McCall3b4294e2009-12-16 12:17:52 +00009594 // It would be nice to avoid this copy.
9595 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009596 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009597 if (ULE->hasExplicitTemplateArgs()) {
9598 ULE->copyTemplateArgumentsInto(TABuffer);
9599 ExplicitTemplateArgs = &TABuffer;
9600 }
9601
9602 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9603 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009604 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9605 CandidateSet, PartialOverloading,
9606 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009607
John McCall3b4294e2009-12-16 12:17:52 +00009608 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009609 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009610 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009611 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009612 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009613}
John McCall578b69b2009-12-16 08:11:27 +00009614
Richard Smithf50e88a2011-06-05 22:42:48 +00009615/// Attempt to recover from an ill-formed use of a non-dependent name in a
9616/// template, where the non-dependent name was declared after the template
9617/// was defined. This is common in code written for a compilers which do not
9618/// correctly implement two-stage name lookup.
9619///
9620/// Returns true if a viable candidate was found and a diagnostic was issued.
9621static bool
9622DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9623 const CXXScopeSpec &SS, LookupResult &R,
9624 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009625 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009626 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9627 return false;
9628
9629 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009630 if (DC->isTransparentContext())
9631 continue;
9632
Richard Smithf50e88a2011-06-05 22:42:48 +00009633 SemaRef.LookupQualifiedName(R, DC);
9634
9635 if (!R.empty()) {
9636 R.suppressDiagnostics();
9637
9638 if (isa<CXXRecordDecl>(DC)) {
9639 // Don't diagnose names we find in classes; we get much better
9640 // diagnostics for these from DiagnoseEmptyLookup.
9641 R.clear();
9642 return false;
9643 }
9644
9645 OverloadCandidateSet Candidates(FnLoc);
9646 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9647 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009648 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009649 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009650
9651 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009652 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009653 // No viable functions. Don't bother the user with notes for functions
9654 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009655 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009656 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009657 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009658
9659 // Find the namespaces where ADL would have looked, and suggest
9660 // declaring the function there instead.
9661 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9662 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009663 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009664 AssociatedNamespaces,
9665 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009666 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009667 DeclContext *Std = SemaRef.getStdNamespace();
9668 for (Sema::AssociatedNamespaceSet::iterator
9669 it = AssociatedNamespaces.begin(),
9670 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009671 // Never suggest declaring a function within namespace 'std'.
9672 if (Std && Std->Encloses(*it))
9673 continue;
9674
9675 // Never suggest declaring a function within a namespace with a reserved
9676 // name, like __gnu_cxx.
9677 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9678 if (NS &&
9679 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9680 continue;
9681
9682 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009683 }
9684
9685 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9686 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009687 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009688 SemaRef.Diag(Best->Function->getLocation(),
9689 diag::note_not_found_by_two_phase_lookup)
9690 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009691 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009692 SemaRef.Diag(Best->Function->getLocation(),
9693 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009694 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009695 } else {
9696 // FIXME: It would be useful to list the associated namespaces here,
9697 // but the diagnostics infrastructure doesn't provide a way to produce
9698 // a localized representation of a list of items.
9699 SemaRef.Diag(Best->Function->getLocation(),
9700 diag::note_not_found_by_two_phase_lookup)
9701 << R.getLookupName() << 2;
9702 }
9703
9704 // Try to recover by calling this function.
9705 return true;
9706 }
9707
9708 R.clear();
9709 }
9710
9711 return false;
9712}
9713
9714/// Attempt to recover from ill-formed use of a non-dependent operator in a
9715/// template, where the non-dependent operator was declared after the template
9716/// was defined.
9717///
9718/// Returns true if a viable candidate was found and a diagnostic was issued.
9719static bool
9720DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9721 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009722 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009723 DeclarationName OpName =
9724 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9725 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9726 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009727 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009728}
9729
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009730namespace {
9731// Callback to limit the allowed keywords and to only accept typo corrections
9732// that are keywords or whose decls refer to functions (or template functions)
9733// that accept the given number of arguments.
9734class RecoveryCallCCC : public CorrectionCandidateCallback {
9735 public:
9736 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9737 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009738 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009739 WantRemainingKeywords = false;
9740 }
9741
9742 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9743 if (!candidate.getCorrectionDecl())
9744 return candidate.isKeyword();
9745
9746 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9747 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9748 FunctionDecl *FD = 0;
9749 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9750 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9751 FD = FTD->getTemplatedDecl();
9752 if (!HasExplicitTemplateArgs && !FD) {
9753 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9754 // If the Decl is neither a function nor a template function,
9755 // determine if it is a pointer or reference to a function. If so,
9756 // check against the number of arguments expected for the pointee.
9757 QualType ValType = cast<ValueDecl>(ND)->getType();
9758 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9759 ValType = ValType->getPointeeType();
9760 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9761 if (FPT->getNumArgs() == NumArgs)
9762 return true;
9763 }
9764 }
9765 if (FD && FD->getNumParams() >= NumArgs &&
9766 FD->getMinRequiredArguments() <= NumArgs)
9767 return true;
9768 }
9769 return false;
9770 }
9771
9772 private:
9773 unsigned NumArgs;
9774 bool HasExplicitTemplateArgs;
9775};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009776
9777// Callback that effectively disabled typo correction
9778class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9779 public:
9780 NoTypoCorrectionCCC() {
9781 WantTypeSpecifiers = false;
9782 WantExpressionKeywords = false;
9783 WantCXXNamedCasts = false;
9784 WantRemainingKeywords = false;
9785 }
9786
9787 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9788 return false;
9789 }
9790};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009791
9792class BuildRecoveryCallExprRAII {
9793 Sema &SemaRef;
9794public:
9795 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9796 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9797 SemaRef.IsBuildingRecoveryCallExpr = true;
9798 }
9799
9800 ~BuildRecoveryCallExprRAII() {
9801 SemaRef.IsBuildingRecoveryCallExpr = false;
9802 }
9803};
9804
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009805}
9806
John McCall578b69b2009-12-16 08:11:27 +00009807/// Attempts to recover from a call where no functions were found.
9808///
9809/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009810static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009811BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009812 UnresolvedLookupExpr *ULE,
9813 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009814 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009815 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009816 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009817 // Do not try to recover if it is already building a recovery call.
9818 // This stops infinite loops for template instantiations like
9819 //
9820 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9821 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9822 //
9823 if (SemaRef.IsBuildingRecoveryCallExpr)
9824 return ExprError();
9825 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009826
9827 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009828 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009829 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009830
John McCall3b4294e2009-12-16 12:17:52 +00009831 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009832 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009833 if (ULE->hasExplicitTemplateArgs()) {
9834 ULE->copyTemplateArgumentsInto(TABuffer);
9835 ExplicitTemplateArgs = &TABuffer;
9836 }
9837
John McCall578b69b2009-12-16 08:11:27 +00009838 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9839 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009840 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009841 NoTypoCorrectionCCC RejectAll;
9842 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9843 (CorrectionCandidateCallback*)&Validator :
9844 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009845 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009846 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009847 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009848 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009849 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009850 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009851
John McCall3b4294e2009-12-16 12:17:52 +00009852 assert(!R.empty() && "lookup results empty despite recovery");
9853
9854 // Build an implicit member call if appropriate. Just drop the
9855 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009856 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009857 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009858 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9859 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009860 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009861 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009862 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009863 else
9864 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9865
9866 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009867 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009868
9869 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009870 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009871 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009872 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009873 MultiExprArg(Args.data(), Args.size()),
9874 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009875}
Douglas Gregord7a95972010-06-08 17:35:15 +00009876
Sam Panzere1715b62012-08-21 00:52:01 +00009877/// \brief Constructs and populates an OverloadedCandidateSet from
9878/// the given function.
9879/// \returns true when an the ExprResult output parameter has been set.
9880bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9881 UnresolvedLookupExpr *ULE,
9882 Expr **Args, unsigned NumArgs,
9883 SourceLocation RParenLoc,
9884 OverloadCandidateSet *CandidateSet,
9885 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009886#ifndef NDEBUG
9887 if (ULE->requiresADL()) {
9888 // To do ADL, we must have found an unqualified name.
9889 assert(!ULE->getQualifier() && "qualified name with ADL");
9890
9891 // We don't perform ADL for implicit declarations of builtins.
9892 // Verify that this was correctly set up.
9893 FunctionDecl *F;
9894 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9895 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9896 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009897 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009898
John McCall3b4294e2009-12-16 12:17:52 +00009899 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009900 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009901 }
John McCall3b4294e2009-12-16 12:17:52 +00009902#endif
9903
John McCall5acb0c92011-10-17 18:40:02 +00009904 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009905 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9906 *Result = ExprError();
9907 return true;
9908 }
Douglas Gregor17330012009-02-04 15:01:18 +00009909
John McCall3b4294e2009-12-16 12:17:52 +00009910 // Add the functions denoted by the callee to the set of candidate
9911 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009912 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009913 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009914
9915 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009916 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9917 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009918 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009919 // In Microsoft mode, if we are inside a template class member function then
9920 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009921 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009922 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009923 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009924 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009925 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9926 llvm::makeArrayRef(Args, NumArgs),
9927 Context.DependentTy, VK_RValue,
9928 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009929 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009930 *Result = Owned(CE);
9931 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009932 }
Sam Panzere1715b62012-08-21 00:52:01 +00009933 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009934 }
John McCall578b69b2009-12-16 08:11:27 +00009935
John McCall5acb0c92011-10-17 18:40:02 +00009936 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009937 return false;
9938}
John McCall5acb0c92011-10-17 18:40:02 +00009939
Sam Panzere1715b62012-08-21 00:52:01 +00009940/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9941/// the completed call expression. If overload resolution fails, emits
9942/// diagnostics and returns ExprError()
9943static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9944 UnresolvedLookupExpr *ULE,
9945 SourceLocation LParenLoc,
9946 Expr **Args, unsigned NumArgs,
9947 SourceLocation RParenLoc,
9948 Expr *ExecConfig,
9949 OverloadCandidateSet *CandidateSet,
9950 OverloadCandidateSet::iterator *Best,
9951 OverloadingResult OverloadResult,
9952 bool AllowTypoCorrection) {
9953 if (CandidateSet->empty())
9954 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9955 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9956 RParenLoc, /*EmptyLookup=*/true,
9957 AllowTypoCorrection);
9958
9959 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009960 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009961 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +00009962 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9963 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9964 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9965 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9966 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009967 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009968
Richard Smithf50e88a2011-06-05 22:42:48 +00009969 case OR_No_Viable_Function: {
9970 // Try to recover by looking for viable functions which the user might
9971 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009972 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009973 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9974 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009975 /*EmptyLookup=*/false,
9976 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009977 if (!Recovery.isInvalid())
9978 return Recovery;
9979
Sam Panzere1715b62012-08-21 00:52:01 +00009980 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009981 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009982 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009983 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9984 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009985 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009986 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009987
9988 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009989 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009990 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009991 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9992 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009993 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009994
Sam Panzere1715b62012-08-21 00:52:01 +00009995 case OR_Deleted: {
9996 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9997 << (*Best)->Function->isDeleted()
9998 << ULE->getName()
9999 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10000 << Fn->getSourceRange();
10001 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
10002 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010003
Sam Panzere1715b62012-08-21 00:52:01 +000010004 // We emitted an error for the unvailable/deleted function call but keep
10005 // the call in the AST.
10006 FunctionDecl *FDecl = (*Best)->Function;
10007 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10008 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
10009 RParenLoc, ExecConfig);
10010 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010011 }
10012
Douglas Gregorff331c12010-07-25 18:17:45 +000010013 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010014 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010015}
10016
Sam Panzere1715b62012-08-21 00:52:01 +000010017/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10018/// (which eventually refers to the declaration Func) and the call
10019/// arguments Args/NumArgs, attempt to resolve the function call down
10020/// to a specific function. If overload resolution succeeds, returns
10021/// the call expression produced by overload resolution.
10022/// Otherwise, emits diagnostics and returns ExprError.
10023ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10024 UnresolvedLookupExpr *ULE,
10025 SourceLocation LParenLoc,
10026 Expr **Args, unsigned NumArgs,
10027 SourceLocation RParenLoc,
10028 Expr *ExecConfig,
10029 bool AllowTypoCorrection) {
10030 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10031 ExprResult result;
10032
10033 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
10034 &CandidateSet, &result))
10035 return result;
10036
10037 OverloadCandidateSet::iterator Best;
10038 OverloadingResult OverloadResult =
10039 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10040
10041 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
10042 RParenLoc, ExecConfig, &CandidateSet,
10043 &Best, OverloadResult,
10044 AllowTypoCorrection);
10045}
10046
John McCall6e266892010-01-26 03:27:55 +000010047static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010048 return Functions.size() > 1 ||
10049 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10050}
10051
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010052/// \brief Create a unary operation that may resolve to an overloaded
10053/// operator.
10054///
10055/// \param OpLoc The location of the operator itself (e.g., '*').
10056///
10057/// \param OpcIn The UnaryOperator::Opcode that describes this
10058/// operator.
10059///
James Dennett40ae6662012-06-22 08:52:37 +000010060/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010061/// considered by overload resolution. The caller needs to build this
10062/// set based on the context using, e.g.,
10063/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10064/// set should not contain any member functions; those will be added
10065/// by CreateOverloadedUnaryOp().
10066///
James Dennett8da16872012-06-22 10:32:46 +000010067/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010068ExprResult
John McCall6e266892010-01-26 03:27:55 +000010069Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10070 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010071 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010072 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010073
10074 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10075 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10076 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010077 // TODO: provide better source location info.
10078 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010079
John McCall5acb0c92011-10-17 18:40:02 +000010080 if (checkPlaceholderForOverload(*this, Input))
10081 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010082
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010083 Expr *Args[2] = { Input, 0 };
10084 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010085
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010086 // For post-increment and post-decrement, add the implicit '0' as
10087 // the second argument, so that we know this is a post-increment or
10088 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010089 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010090 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010091 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10092 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010093 NumArgs = 2;
10094 }
10095
10096 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010097 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010098 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010099 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010100 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010101 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010102 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010103
John McCallc373d482010-01-27 01:50:18 +000010104 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010105 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010106 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010107 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010108 /*ADL*/ true, IsOverloaded(Fns),
10109 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010110 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010111 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010112 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010113 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010114 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010115 }
10116
10117 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010118 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010119
10120 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010121 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10122 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010123
10124 // Add operator candidates that are member functions.
10125 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10126
John McCall6e266892010-01-26 03:27:55 +000010127 // Add candidates from ADL.
10128 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010129 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010130 /*ExplicitTemplateArgs*/ 0,
10131 CandidateSet);
10132
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010133 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010134 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010135
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010136 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10137
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010138 // Perform overload resolution.
10139 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010140 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010141 case OR_Success: {
10142 // We found a built-in operator or an overloaded operator.
10143 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010144
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010145 if (FnDecl) {
10146 // We matched an overloaded operator. Build a call to that
10147 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010148
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010149 // Convert the arguments.
10150 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010151 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010152
John Wiegley429bb272011-04-08 18:41:53 +000010153 ExprResult InputRes =
10154 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10155 Best->FoundDecl, Method);
10156 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010157 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010158 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010159 } else {
10160 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010161 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010162 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010163 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010164 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010165 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010166 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010167 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010168 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010169 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010170 }
10171
John McCallf89e55a2010-11-18 06:31:45 +000010172 // Determine the result type.
10173 QualType ResultTy = FnDecl->getResultType();
10174 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10175 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010176
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010177 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010178 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010179 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010180 if (FnExpr.isInvalid())
10181 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010182
Eli Friedman4c3b8962009-11-18 03:58:17 +000010183 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010184 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010185 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010186 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010187 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010188
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010189 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010190 FnDecl))
10191 return ExprError();
10192
John McCall9ae2f072010-08-23 23:25:46 +000010193 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010194 } else {
10195 // We matched a built-in operator. Convert the arguments, then
10196 // break out so that we will build the appropriate built-in
10197 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010198 ExprResult InputRes =
10199 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10200 Best->Conversions[0], AA_Passing);
10201 if (InputRes.isInvalid())
10202 return ExprError();
10203 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010204 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010205 }
John Wiegley429bb272011-04-08 18:41:53 +000010206 }
10207
10208 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010209 // This is an erroneous use of an operator which can be overloaded by
10210 // a non-member function. Check for non-member operators which were
10211 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010212 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10213 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010214 // FIXME: Recover by calling the found function.
10215 return ExprError();
10216
John Wiegley429bb272011-04-08 18:41:53 +000010217 // No viable function; fall through to handling this as a
10218 // built-in operator, which will produce an error message for us.
10219 break;
10220
10221 case OR_Ambiguous:
10222 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10223 << UnaryOperator::getOpcodeStr(Opc)
10224 << Input->getType()
10225 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010226 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10227 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010228 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10229 return ExprError();
10230
10231 case OR_Deleted:
10232 Diag(OpLoc, diag::err_ovl_deleted_oper)
10233 << Best->Function->isDeleted()
10234 << UnaryOperator::getOpcodeStr(Opc)
10235 << getDeletedOrUnavailableSuffix(Best->Function)
10236 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010237 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10238 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010239 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010240 return ExprError();
10241 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010242
10243 // Either we found no viable overloaded operator or we matched a
10244 // built-in operator. In either case, fall through to trying to
10245 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010246 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010247}
10248
Douglas Gregor063daf62009-03-13 18:40:31 +000010249/// \brief Create a binary operation that may resolve to an overloaded
10250/// operator.
10251///
10252/// \param OpLoc The location of the operator itself (e.g., '+').
10253///
10254/// \param OpcIn The BinaryOperator::Opcode that describes this
10255/// operator.
10256///
James Dennett40ae6662012-06-22 08:52:37 +000010257/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010258/// considered by overload resolution. The caller needs to build this
10259/// set based on the context using, e.g.,
10260/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10261/// set should not contain any member functions; those will be added
10262/// by CreateOverloadedBinOp().
10263///
10264/// \param LHS Left-hand argument.
10265/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010266ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010267Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010268 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010269 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010270 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010271 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010272 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010273
10274 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10275 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10276 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10277
10278 // If either side is type-dependent, create an appropriate dependent
10279 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010280 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010281 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010282 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010283 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010284 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010285 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010286 Context.DependentTy,
10287 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010288 OpLoc,
10289 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010290
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010291 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10292 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010293 VK_LValue,
10294 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010295 Context.DependentTy,
10296 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010297 OpLoc,
10298 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010299 }
John McCall6e266892010-01-26 03:27:55 +000010300
10301 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010302 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010303 // TODO: provide better source location info in DNLoc component.
10304 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010305 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010306 = UnresolvedLookupExpr::Create(Context, NamingClass,
10307 NestedNameSpecifierLoc(), OpNameInfo,
10308 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010309 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010310 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10311 Context.DependentTy, VK_RValue,
10312 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010313 }
10314
John McCall5acb0c92011-10-17 18:40:02 +000010315 // Always do placeholder-like conversions on the RHS.
10316 if (checkPlaceholderForOverload(*this, Args[1]))
10317 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010318
John McCall3c3b7f92011-10-25 17:37:35 +000010319 // Do placeholder-like conversion on the LHS; note that we should
10320 // not get here with a PseudoObject LHS.
10321 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010322 if (checkPlaceholderForOverload(*this, Args[0]))
10323 return ExprError();
10324
Sebastian Redl275c2b42009-11-18 23:10:33 +000010325 // If this is the assignment operator, we only perform overload resolution
10326 // if the left-hand side is a class or enumeration type. This is actually
10327 // a hack. The standard requires that we do overload resolution between the
10328 // various built-in candidates, but as DR507 points out, this can lead to
10329 // problems. So we do it this way, which pretty much follows what GCC does.
10330 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010331 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010332 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010333
John McCall0e800c92010-12-04 08:14:53 +000010334 // If this is the .* operator, which is not overloadable, just
10335 // create a built-in binary operator.
10336 if (Opc == BO_PtrMemD)
10337 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10338
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010339 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010340 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010341
10342 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010343 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010344
10345 // Add operator candidates that are member functions.
10346 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10347
John McCall6e266892010-01-26 03:27:55 +000010348 // Add candidates from ADL.
10349 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010350 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010351 /*ExplicitTemplateArgs*/ 0,
10352 CandidateSet);
10353
Douglas Gregor063daf62009-03-13 18:40:31 +000010354 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010355 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010356
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010357 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10358
Douglas Gregor063daf62009-03-13 18:40:31 +000010359 // Perform overload resolution.
10360 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010361 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010362 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010363 // We found a built-in operator or an overloaded operator.
10364 FunctionDecl *FnDecl = Best->Function;
10365
10366 if (FnDecl) {
10367 // We matched an overloaded operator. Build a call to that
10368 // operator.
10369
10370 // Convert the arguments.
10371 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010372 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010373 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010374
Chandler Carruth6df868e2010-12-12 08:17:55 +000010375 ExprResult Arg1 =
10376 PerformCopyInitialization(
10377 InitializedEntity::InitializeParameter(Context,
10378 FnDecl->getParamDecl(0)),
10379 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010380 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010381 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010382
John Wiegley429bb272011-04-08 18:41:53 +000010383 ExprResult Arg0 =
10384 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10385 Best->FoundDecl, Method);
10386 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010387 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010388 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010389 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010390 } else {
10391 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010392 ExprResult Arg0 = PerformCopyInitialization(
10393 InitializedEntity::InitializeParameter(Context,
10394 FnDecl->getParamDecl(0)),
10395 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010396 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010397 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010398
Chandler Carruth6df868e2010-12-12 08:17:55 +000010399 ExprResult Arg1 =
10400 PerformCopyInitialization(
10401 InitializedEntity::InitializeParameter(Context,
10402 FnDecl->getParamDecl(1)),
10403 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010404 if (Arg1.isInvalid())
10405 return ExprError();
10406 Args[0] = LHS = Arg0.takeAs<Expr>();
10407 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010408 }
10409
John McCallf89e55a2010-11-18 06:31:45 +000010410 // Determine the result type.
10411 QualType ResultTy = FnDecl->getResultType();
10412 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10413 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010414
10415 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010416 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010417 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010418 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010419 if (FnExpr.isInvalid())
10420 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010421
John McCall9ae2f072010-08-23 23:25:46 +000010422 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010423 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010424 Args, ResultTy, VK, OpLoc,
10425 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010426
10427 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010428 FnDecl))
10429 return ExprError();
10430
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010431 ArrayRef<const Expr *> ArgsArray(Args, 2);
10432 // Cut off the implicit 'this'.
10433 if (isa<CXXMethodDecl>(FnDecl))
10434 ArgsArray = ArgsArray.slice(1);
10435 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10436 TheCall->getSourceRange(), VariadicDoesNotApply);
10437
John McCall9ae2f072010-08-23 23:25:46 +000010438 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010439 } else {
10440 // We matched a built-in operator. Convert the arguments, then
10441 // break out so that we will build the appropriate built-in
10442 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010443 ExprResult ArgsRes0 =
10444 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10445 Best->Conversions[0], AA_Passing);
10446 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010447 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010448 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010449
John Wiegley429bb272011-04-08 18:41:53 +000010450 ExprResult ArgsRes1 =
10451 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10452 Best->Conversions[1], AA_Passing);
10453 if (ArgsRes1.isInvalid())
10454 return ExprError();
10455 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010456 break;
10457 }
10458 }
10459
Douglas Gregor33074752009-09-30 21:46:01 +000010460 case OR_No_Viable_Function: {
10461 // C++ [over.match.oper]p9:
10462 // If the operator is the operator , [...] and there are no
10463 // viable functions, then the operator is assumed to be the
10464 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010465 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010466 break;
10467
Chandler Carruth6df868e2010-12-12 08:17:55 +000010468 // For class as left operand for assignment or compound assigment
10469 // operator do not fall through to handling in built-in, but report that
10470 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010471 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010472 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010473 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010474 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10475 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010476 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010477 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010478 // This is an erroneous use of an operator which can be overloaded by
10479 // a non-member function. Check for non-member operators which were
10480 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010481 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010482 // FIXME: Recover by calling the found function.
10483 return ExprError();
10484
Douglas Gregor33074752009-09-30 21:46:01 +000010485 // No viable function; try to create a built-in operation, which will
10486 // produce an error. Then, show the non-viable candidates.
10487 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010488 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010489 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010490 "C++ binary operator overloading is missing candidates!");
10491 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010492 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010493 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010494 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010495 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010496
10497 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010498 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010499 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010500 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010501 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010502 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010503 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010504 return ExprError();
10505
10506 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010507 if (isImplicitlyDeleted(Best->Function)) {
10508 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10509 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010510 << Context.getRecordType(Method->getParent())
10511 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010512
Richard Smith0f46e642012-12-28 12:23:24 +000010513 // The user probably meant to call this special member. Just
10514 // explain why it's deleted.
10515 NoteDeletedFunction(Method);
10516 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010517 } else {
10518 Diag(OpLoc, diag::err_ovl_deleted_oper)
10519 << Best->Function->isDeleted()
10520 << BinaryOperator::getOpcodeStr(Opc)
10521 << getDeletedOrUnavailableSuffix(Best->Function)
10522 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10523 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010524 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010525 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010526 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010527 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010528
Douglas Gregor33074752009-09-30 21:46:01 +000010529 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010530 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010531}
10532
John McCall60d7b3a2010-08-24 06:29:42 +000010533ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010534Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10535 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010536 Expr *Base, Expr *Idx) {
10537 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010538 DeclarationName OpName =
10539 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10540
10541 // If either side is type-dependent, create an appropriate dependent
10542 // expression.
10543 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10544
John McCallc373d482010-01-27 01:50:18 +000010545 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010546 // CHECKME: no 'operator' keyword?
10547 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10548 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010549 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010550 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010551 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010552 /*ADL*/ true, /*Overloaded*/ false,
10553 UnresolvedSetIterator(),
10554 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010555 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010556
Sebastian Redlf322ed62009-10-29 20:17:01 +000010557 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010558 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010559 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010560 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010561 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010562 }
10563
John McCall5acb0c92011-10-17 18:40:02 +000010564 // Handle placeholders on both operands.
10565 if (checkPlaceholderForOverload(*this, Args[0]))
10566 return ExprError();
10567 if (checkPlaceholderForOverload(*this, Args[1]))
10568 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010569
Sebastian Redlf322ed62009-10-29 20:17:01 +000010570 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010571 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010572
10573 // Subscript can only be overloaded as a member function.
10574
10575 // Add operator candidates that are member functions.
10576 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10577
10578 // Add builtin operator candidates.
10579 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10580
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010581 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10582
Sebastian Redlf322ed62009-10-29 20:17:01 +000010583 // Perform overload resolution.
10584 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010585 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010586 case OR_Success: {
10587 // We found a built-in operator or an overloaded operator.
10588 FunctionDecl *FnDecl = Best->Function;
10589
10590 if (FnDecl) {
10591 // We matched an overloaded operator. Build a call to that
10592 // operator.
10593
John McCall9aa472c2010-03-19 07:35:19 +000010594 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010595
Sebastian Redlf322ed62009-10-29 20:17:01 +000010596 // Convert the arguments.
10597 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010598 ExprResult Arg0 =
10599 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10600 Best->FoundDecl, Method);
10601 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010602 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010603 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010604
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010605 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010606 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010607 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010608 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010609 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010610 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010611 Owned(Args[1]));
10612 if (InputInit.isInvalid())
10613 return ExprError();
10614
10615 Args[1] = InputInit.takeAs<Expr>();
10616
Sebastian Redlf322ed62009-10-29 20:17:01 +000010617 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010618 QualType ResultTy = FnDecl->getResultType();
10619 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10620 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010621
10622 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010623 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10624 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010625 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010626 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010627 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010628 OpLocInfo.getLoc(),
10629 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010630 if (FnExpr.isInvalid())
10631 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010632
John McCall9ae2f072010-08-23 23:25:46 +000010633 CXXOperatorCallExpr *TheCall =
10634 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010635 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010636 ResultTy, VK, RLoc,
10637 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010638
John McCall9ae2f072010-08-23 23:25:46 +000010639 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010640 FnDecl))
10641 return ExprError();
10642
John McCall9ae2f072010-08-23 23:25:46 +000010643 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010644 } else {
10645 // We matched a built-in operator. Convert the arguments, then
10646 // break out so that we will build the appropriate built-in
10647 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010648 ExprResult ArgsRes0 =
10649 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10650 Best->Conversions[0], AA_Passing);
10651 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010652 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010653 Args[0] = ArgsRes0.take();
10654
10655 ExprResult ArgsRes1 =
10656 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10657 Best->Conversions[1], AA_Passing);
10658 if (ArgsRes1.isInvalid())
10659 return ExprError();
10660 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010661
10662 break;
10663 }
10664 }
10665
10666 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010667 if (CandidateSet.empty())
10668 Diag(LLoc, diag::err_ovl_no_oper)
10669 << Args[0]->getType() << /*subscript*/ 0
10670 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10671 else
10672 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10673 << Args[0]->getType()
10674 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010675 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010676 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010677 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010678 }
10679
10680 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010681 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010682 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010683 << Args[0]->getType() << Args[1]->getType()
10684 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010685 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010686 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010687 return ExprError();
10688
10689 case OR_Deleted:
10690 Diag(LLoc, diag::err_ovl_deleted_oper)
10691 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010692 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010693 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010694 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010695 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010696 return ExprError();
10697 }
10698
10699 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010700 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010701}
10702
Douglas Gregor88a35142008-12-22 05:46:06 +000010703/// BuildCallToMemberFunction - Build a call to a member
10704/// function. MemExpr is the expression that refers to the member
10705/// function (and includes the object parameter), Args/NumArgs are the
10706/// arguments to the function call (not including the object
10707/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010708/// expression refers to a non-static member function or an overloaded
10709/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010710ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010711Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10712 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010713 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010714 assert(MemExprE->getType() == Context.BoundMemberTy ||
10715 MemExprE->getType() == Context.OverloadTy);
10716
Douglas Gregor88a35142008-12-22 05:46:06 +000010717 // Dig out the member expression. This holds both the object
10718 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010719 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010720
John McCall864c0412011-04-26 20:42:42 +000010721 // Determine whether this is a call to a pointer-to-member function.
10722 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10723 assert(op->getType() == Context.BoundMemberTy);
10724 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10725
10726 QualType fnType =
10727 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10728
10729 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10730 QualType resultType = proto->getCallResultType(Context);
10731 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10732
10733 // Check that the object type isn't more qualified than the
10734 // member function we're calling.
10735 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10736
10737 QualType objectType = op->getLHS()->getType();
10738 if (op->getOpcode() == BO_PtrMemI)
10739 objectType = objectType->castAs<PointerType>()->getPointeeType();
10740 Qualifiers objectQuals = objectType.getQualifiers();
10741
10742 Qualifiers difference = objectQuals - funcQuals;
10743 difference.removeObjCGCAttr();
10744 difference.removeAddressSpace();
10745 if (difference) {
10746 std::string qualsString = difference.getAsString();
10747 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10748 << fnType.getUnqualifiedType()
10749 << qualsString
10750 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10751 }
10752
10753 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010754 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10755 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010756 resultType, valueKind, RParenLoc);
10757
10758 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010759 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010760 call, 0))
10761 return ExprError();
10762
10763 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10764 return ExprError();
10765
10766 return MaybeBindToTemporary(call);
10767 }
10768
John McCall5acb0c92011-10-17 18:40:02 +000010769 UnbridgedCastsSet UnbridgedCasts;
10770 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10771 return ExprError();
10772
John McCall129e2df2009-11-30 22:42:35 +000010773 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010774 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010775 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010776 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010777 if (isa<MemberExpr>(NakedMemExpr)) {
10778 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010779 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010780 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010781 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010782 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010783 } else {
10784 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010785 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010786
John McCall701c89e2009-12-03 04:06:58 +000010787 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010788 Expr::Classification ObjectClassification
10789 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10790 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010791
Douglas Gregor88a35142008-12-22 05:46:06 +000010792 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010793 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010794
John McCallaa81e162009-12-01 22:10:20 +000010795 // FIXME: avoid copy.
10796 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10797 if (UnresExpr->hasExplicitTemplateArgs()) {
10798 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10799 TemplateArgs = &TemplateArgsBuffer;
10800 }
10801
John McCall129e2df2009-11-30 22:42:35 +000010802 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10803 E = UnresExpr->decls_end(); I != E; ++I) {
10804
John McCall701c89e2009-12-03 04:06:58 +000010805 NamedDecl *Func = *I;
10806 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10807 if (isa<UsingShadowDecl>(Func))
10808 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10809
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010810
Francois Pichetdbee3412011-01-18 05:04:39 +000010811 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010812 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010813 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10814 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010815 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010816 // If explicit template arguments were provided, we can't call a
10817 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010818 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010819 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010820
John McCall9aa472c2010-03-19 07:35:19 +000010821 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010822 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010823 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010824 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010825 } else {
John McCall129e2df2009-11-30 22:42:35 +000010826 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010827 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010828 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010829 llvm::makeArrayRef(Args, NumArgs),
10830 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010831 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010832 }
Douglas Gregordec06662009-08-21 18:42:58 +000010833 }
Mike Stump1eb44332009-09-09 15:08:12 +000010834
John McCall129e2df2009-11-30 22:42:35 +000010835 DeclarationName DeclName = UnresExpr->getMemberName();
10836
John McCall5acb0c92011-10-17 18:40:02 +000010837 UnbridgedCasts.restore();
10838
Douglas Gregor88a35142008-12-22 05:46:06 +000010839 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010840 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010841 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010842 case OR_Success:
10843 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010844 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010845 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010846 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010847 break;
10848
10849 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010850 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010851 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010852 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010853 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10854 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010855 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010856 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010857
10858 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010859 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010860 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010861 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10862 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010863 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010864 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010865
10866 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010867 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010868 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010869 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010870 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010871 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010872 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10873 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010874 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010875 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010876 }
10877
John McCall6bb80172010-03-30 21:47:33 +000010878 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010879
John McCallaa81e162009-12-01 22:10:20 +000010880 // If overload resolution picked a static member, build a
10881 // non-member call based on that function.
10882 if (Method->isStatic()) {
10883 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10884 Args, NumArgs, RParenLoc);
10885 }
10886
John McCall129e2df2009-11-30 22:42:35 +000010887 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010888 }
10889
John McCallf89e55a2010-11-18 06:31:45 +000010890 QualType ResultType = Method->getResultType();
10891 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10892 ResultType = ResultType.getNonLValueExprType(Context);
10893
Douglas Gregor88a35142008-12-22 05:46:06 +000010894 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010895 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010896 new (Context) CXXMemberCallExpr(Context, MemExprE,
10897 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010898 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010899
Anders Carlssoneed3e692009-10-10 00:06:20 +000010900 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010901 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010902 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010903 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010904
Douglas Gregor88a35142008-12-22 05:46:06 +000010905 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010906 // We only need to do this if there was actually an overload; otherwise
10907 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010908 if (!Method->isStatic()) {
10909 ExprResult ObjectArg =
10910 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10911 FoundDecl, Method);
10912 if (ObjectArg.isInvalid())
10913 return ExprError();
10914 MemExpr->setBase(ObjectArg.take());
10915 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010916
10917 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010918 const FunctionProtoType *Proto =
10919 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010920 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010921 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010922 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010923
Eli Friedmane61eb042012-02-18 04:48:30 +000010924 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10925
Richard Smith831421f2012-06-25 20:30:08 +000010926 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010927 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010928
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010929 if ((isa<CXXConstructorDecl>(CurContext) ||
10930 isa<CXXDestructorDecl>(CurContext)) &&
10931 TheCall->getMethodDecl()->isPure()) {
10932 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10933
Chandler Carruthae198062011-06-27 08:31:58 +000010934 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010935 Diag(MemExpr->getLocStart(),
10936 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10937 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10938 << MD->getParent()->getDeclName();
10939
10940 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010941 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010942 }
John McCall9ae2f072010-08-23 23:25:46 +000010943 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010944}
10945
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010946/// BuildCallToObjectOfClassType - Build a call to an object of class
10947/// type (C++ [over.call.object]), which can end up invoking an
10948/// overloaded function call operator (@c operator()) or performing a
10949/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010950ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010951Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010952 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010953 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010954 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010955 if (checkPlaceholderForOverload(*this, Obj))
10956 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010957 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010958
10959 UnbridgedCastsSet UnbridgedCasts;
10960 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10961 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010962
John Wiegley429bb272011-04-08 18:41:53 +000010963 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10964 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010965
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010966 // C++ [over.call.object]p1:
10967 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010968 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010969 // candidate functions includes at least the function call
10970 // operators of T. The function call operators of T are obtained by
10971 // ordinary lookup of the name operator() in the context of
10972 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010973 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010974 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010975
John Wiegley429bb272011-04-08 18:41:53 +000010976 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010977 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010978 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010979
John McCalla24dc2e2009-11-17 02:14:36 +000010980 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10981 LookupQualifiedName(R, Record->getDecl());
10982 R.suppressDiagnostics();
10983
Douglas Gregor593564b2009-11-15 07:48:03 +000010984 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010985 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010986 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10987 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010988 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010989 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010990
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010991 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010992 // In addition, for each (non-explicit in C++0x) conversion function
10993 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010994 //
10995 // operator conversion-type-id () cv-qualifier;
10996 //
10997 // where cv-qualifier is the same cv-qualification as, or a
10998 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010999 // denotes the type "pointer to function of (P1,...,Pn) returning
11000 // R", or the type "reference to pointer to function of
11001 // (P1,...,Pn) returning R", or the type "reference to function
11002 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011003 // is also considered as a candidate function. Similarly,
11004 // surrogate call functions are added to the set of candidate
11005 // functions for each conversion function declared in an
11006 // accessible base class provided the function is not hidden
11007 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011008 std::pair<CXXRecordDecl::conversion_iterator,
11009 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011010 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011011 for (CXXRecordDecl::conversion_iterator
11012 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011013 NamedDecl *D = *I;
11014 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11015 if (isa<UsingShadowDecl>(D))
11016 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011017
Douglas Gregor4a27d702009-10-21 06:18:39 +000011018 // Skip over templated conversion functions; they aren't
11019 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011020 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011021 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011022
John McCall701c89e2009-12-03 04:06:58 +000011023 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011024 if (!Conv->isExplicit()) {
11025 // Strip the reference type (if any) and then the pointer type (if
11026 // any) to get down to what might be a function type.
11027 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11028 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11029 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011030
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011031 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11032 {
11033 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000011034 Object.get(), llvm::makeArrayRef(Args, NumArgs),
11035 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011036 }
11037 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011038 }
Mike Stump1eb44332009-09-09 15:08:12 +000011039
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011040 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11041
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011042 // Perform overload resolution.
11043 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011044 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011045 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011046 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011047 // Overload resolution succeeded; we'll build the appropriate call
11048 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011049 break;
11050
11051 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011052 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011053 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011054 << Object.get()->getType() << /*call*/ 1
11055 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011056 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011057 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011058 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011059 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011060 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11061 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011062 break;
11063
11064 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011065 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011066 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011067 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011068 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11069 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011070 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011071
11072 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011073 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011074 diag::err_ovl_deleted_object_call)
11075 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011076 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011077 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011078 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011079 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11080 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011081 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011082 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011083
Douglas Gregorff331c12010-07-25 18:17:45 +000011084 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011085 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011086
John McCall5acb0c92011-10-17 18:40:02 +000011087 UnbridgedCasts.restore();
11088
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011089 if (Best->Function == 0) {
11090 // Since there is no function declaration, this is one of the
11091 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011092 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011093 = cast<CXXConversionDecl>(
11094 Best->Conversions[0].UserDefined.ConversionFunction);
11095
John Wiegley429bb272011-04-08 18:41:53 +000011096 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011097 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011098
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011099 // We selected one of the surrogate functions that converts the
11100 // object parameter to a function pointer. Perform the conversion
11101 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011102
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011103 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011104 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011105 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11106 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011107 if (Call.isInvalid())
11108 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011109 // Record usage of conversion in an implicit cast.
11110 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11111 CK_UserDefinedConversion,
11112 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011113
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011114 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011115 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011116 }
11117
John Wiegley429bb272011-04-08 18:41:53 +000011118 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011119
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011120 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11121 // that calls this method, using Object for the implicit object
11122 // parameter and passing along the remaining arguments.
11123 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011124
11125 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011126 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011127 return ExprError();
11128
Chandler Carruth6df868e2010-12-12 08:17:55 +000011129 const FunctionProtoType *Proto =
11130 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011131
11132 unsigned NumArgsInProto = Proto->getNumArgs();
11133 unsigned NumArgsToCheck = NumArgs;
11134
11135 // Build the full argument list for the method call (the
11136 // implicit object parameter is placed at the beginning of the
11137 // list).
11138 Expr **MethodArgs;
11139 if (NumArgs < NumArgsInProto) {
11140 NumArgsToCheck = NumArgsInProto;
11141 MethodArgs = new Expr*[NumArgsInProto + 1];
11142 } else {
11143 MethodArgs = new Expr*[NumArgs + 1];
11144 }
John Wiegley429bb272011-04-08 18:41:53 +000011145 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011146 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11147 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011148
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011149 DeclarationNameInfo OpLocInfo(
11150 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11151 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011152 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011153 HadMultipleCandidates,
11154 OpLocInfo.getLoc(),
11155 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011156 if (NewFn.isInvalid())
11157 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011158
11159 // Once we've built TheCall, all of the expressions are properly
11160 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011161 QualType ResultTy = Method->getResultType();
11162 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11163 ResultTy = ResultTy.getNonLValueExprType(Context);
11164
John McCall9ae2f072010-08-23 23:25:46 +000011165 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011166 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011167 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011168 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011169 delete [] MethodArgs;
11170
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011171 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011172 Method))
11173 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011174
Douglas Gregor518fda12009-01-13 05:10:00 +000011175 // We may have default arguments. If so, we need to allocate more
11176 // slots in the call for them.
11177 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011178 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011179 else if (NumArgs > NumArgsInProto)
11180 NumArgsToCheck = NumArgsInProto;
11181
Chris Lattner312531a2009-04-12 08:11:20 +000011182 bool IsError = false;
11183
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011184 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011185 ExprResult ObjRes =
11186 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11187 Best->FoundDecl, Method);
11188 if (ObjRes.isInvalid())
11189 IsError = true;
11190 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011191 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011192 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011193
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011194 // Check the argument types.
11195 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011196 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011197 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011198 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011199
Douglas Gregor518fda12009-01-13 05:10:00 +000011200 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011201
John McCall60d7b3a2010-08-24 06:29:42 +000011202 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011203 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011204 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011205 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011206 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011207
Anders Carlsson3faa4862010-01-29 18:43:53 +000011208 IsError |= InputInit.isInvalid();
11209 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011210 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011211 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011212 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11213 if (DefArg.isInvalid()) {
11214 IsError = true;
11215 break;
11216 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011217
Douglas Gregord47c47d2009-11-09 19:27:57 +000011218 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011219 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011220
11221 TheCall->setArg(i + 1, Arg);
11222 }
11223
11224 // If this is a variadic call, handle args passed through "...".
11225 if (Proto->isVariadic()) {
11226 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011227 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011228 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11229 IsError |= Arg.isInvalid();
11230 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011231 }
11232 }
11233
Chris Lattner312531a2009-04-12 08:11:20 +000011234 if (IsError) return true;
11235
Eli Friedmane61eb042012-02-18 04:48:30 +000011236 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11237
Richard Smith831421f2012-06-25 20:30:08 +000011238 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011239 return true;
11240
John McCall182f7092010-08-24 06:09:16 +000011241 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011242}
11243
Douglas Gregor8ba10742008-11-20 16:27:02 +000011244/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011245/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011246/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011247ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011248Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011249 assert(Base->getType()->isRecordType() &&
11250 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011251
John McCall5acb0c92011-10-17 18:40:02 +000011252 if (checkPlaceholderForOverload(*this, Base))
11253 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011254
John McCall5769d612010-02-08 23:07:23 +000011255 SourceLocation Loc = Base->getExprLoc();
11256
Douglas Gregor8ba10742008-11-20 16:27:02 +000011257 // C++ [over.ref]p1:
11258 //
11259 // [...] An expression x->m is interpreted as (x.operator->())->m
11260 // for a class object x of type T if T::operator->() exists and if
11261 // the operator is selected as the best match function by the
11262 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011263 DeclarationName OpName =
11264 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011265 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011266 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011267
John McCall5769d612010-02-08 23:07:23 +000011268 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011269 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011270 return ExprError();
11271
John McCalla24dc2e2009-11-17 02:14:36 +000011272 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11273 LookupQualifiedName(R, BaseRecord->getDecl());
11274 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011275
11276 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011277 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011278 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11279 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011280 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011281
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011282 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11283
Douglas Gregor8ba10742008-11-20 16:27:02 +000011284 // Perform overload resolution.
11285 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011286 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011287 case OR_Success:
11288 // Overload resolution succeeded; we'll build the call below.
11289 break;
11290
11291 case OR_No_Viable_Function:
11292 if (CandidateSet.empty())
11293 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011294 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011295 else
11296 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011297 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011298 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011299 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011300
11301 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011302 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11303 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011304 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011305 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011306
11307 case OR_Deleted:
11308 Diag(OpLoc, diag::err_ovl_deleted_oper)
11309 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011310 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011311 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011312 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011313 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011314 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011315 }
11316
John McCall9aa472c2010-03-19 07:35:19 +000011317 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11318
Douglas Gregor8ba10742008-11-20 16:27:02 +000011319 // Convert the object parameter.
11320 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011321 ExprResult BaseResult =
11322 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11323 Best->FoundDecl, Method);
11324 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011325 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011326 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011327
Douglas Gregor8ba10742008-11-20 16:27:02 +000011328 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011329 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011330 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011331 if (FnExpr.isInvalid())
11332 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011333
John McCallf89e55a2010-11-18 06:31:45 +000011334 QualType ResultTy = Method->getResultType();
11335 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11336 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011337 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011338 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011339 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011340
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011341 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011342 Method))
11343 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011344
11345 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011346}
11347
Richard Smith36f5cfe2012-03-09 08:00:36 +000011348/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11349/// a literal operator described by the provided lookup results.
11350ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11351 DeclarationNameInfo &SuffixInfo,
11352 ArrayRef<Expr*> Args,
11353 SourceLocation LitEndLoc,
11354 TemplateArgumentListInfo *TemplateArgs) {
11355 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011356
Richard Smith36f5cfe2012-03-09 08:00:36 +000011357 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11358 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11359 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011360
Richard Smith36f5cfe2012-03-09 08:00:36 +000011361 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11362
Richard Smith36f5cfe2012-03-09 08:00:36 +000011363 // Perform overload resolution. This will usually be trivial, but might need
11364 // to perform substitutions for a literal operator template.
11365 OverloadCandidateSet::iterator Best;
11366 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11367 case OR_Success:
11368 case OR_Deleted:
11369 break;
11370
11371 case OR_No_Viable_Function:
11372 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11373 << R.getLookupName();
11374 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11375 return ExprError();
11376
11377 case OR_Ambiguous:
11378 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11379 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11380 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011381 }
11382
Richard Smith36f5cfe2012-03-09 08:00:36 +000011383 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011384 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11385 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011386 SuffixInfo.getLoc(),
11387 SuffixInfo.getInfo());
11388 if (Fn.isInvalid())
11389 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011390
11391 // Check the argument types. This should almost always be a no-op, except
11392 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011393 Expr *ConvArgs[2];
11394 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11395 ExprResult InputInit = PerformCopyInitialization(
11396 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11397 SourceLocation(), Args[ArgIdx]);
11398 if (InputInit.isInvalid())
11399 return true;
11400 ConvArgs[ArgIdx] = InputInit.take();
11401 }
11402
Richard Smith9fcce652012-03-07 08:35:16 +000011403 QualType ResultTy = FD->getResultType();
11404 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11405 ResultTy = ResultTy.getNonLValueExprType(Context);
11406
Richard Smith9fcce652012-03-07 08:35:16 +000011407 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011408 new (Context) UserDefinedLiteral(Context, Fn.take(),
11409 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011410 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11411
11412 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11413 return ExprError();
11414
Richard Smith831421f2012-06-25 20:30:08 +000011415 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011416 return ExprError();
11417
11418 return MaybeBindToTemporary(UDL);
11419}
11420
Sam Panzere1715b62012-08-21 00:52:01 +000011421/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11422/// given LookupResult is non-empty, it is assumed to describe a member which
11423/// will be invoked. Otherwise, the function will be found via argument
11424/// dependent lookup.
11425/// CallExpr is set to a valid expression and FRS_Success returned on success,
11426/// otherwise CallExpr is set to ExprError() and some non-success value
11427/// is returned.
11428Sema::ForRangeStatus
11429Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11430 SourceLocation RangeLoc, VarDecl *Decl,
11431 BeginEndFunction BEF,
11432 const DeclarationNameInfo &NameInfo,
11433 LookupResult &MemberLookup,
11434 OverloadCandidateSet *CandidateSet,
11435 Expr *Range, ExprResult *CallExpr) {
11436 CandidateSet->clear();
11437 if (!MemberLookup.empty()) {
11438 ExprResult MemberRef =
11439 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11440 /*IsPtr=*/false, CXXScopeSpec(),
11441 /*TemplateKWLoc=*/SourceLocation(),
11442 /*FirstQualifierInScope=*/0,
11443 MemberLookup,
11444 /*TemplateArgs=*/0);
11445 if (MemberRef.isInvalid()) {
11446 *CallExpr = ExprError();
11447 Diag(Range->getLocStart(), diag::note_in_for_range)
11448 << RangeLoc << BEF << Range->getType();
11449 return FRS_DiagnosticIssued;
11450 }
11451 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11452 if (CallExpr->isInvalid()) {
11453 *CallExpr = ExprError();
11454 Diag(Range->getLocStart(), diag::note_in_for_range)
11455 << RangeLoc << BEF << Range->getType();
11456 return FRS_DiagnosticIssued;
11457 }
11458 } else {
11459 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011460 UnresolvedLookupExpr *Fn =
11461 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11462 NestedNameSpecifierLoc(), NameInfo,
11463 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011464 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011465
11466 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11467 CandidateSet, CallExpr);
11468 if (CandidateSet->empty() || CandidateSetError) {
11469 *CallExpr = ExprError();
11470 return FRS_NoViableFunction;
11471 }
11472 OverloadCandidateSet::iterator Best;
11473 OverloadingResult OverloadResult =
11474 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11475
11476 if (OverloadResult == OR_No_Viable_Function) {
11477 *CallExpr = ExprError();
11478 return FRS_NoViableFunction;
11479 }
11480 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11481 Loc, 0, CandidateSet, &Best,
11482 OverloadResult,
11483 /*AllowTypoCorrection=*/false);
11484 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11485 *CallExpr = ExprError();
11486 Diag(Range->getLocStart(), diag::note_in_for_range)
11487 << RangeLoc << BEF << Range->getType();
11488 return FRS_DiagnosticIssued;
11489 }
11490 }
11491 return FRS_Success;
11492}
11493
11494
Douglas Gregor904eed32008-11-10 20:40:00 +000011495/// FixOverloadedFunctionReference - E is an expression that refers to
11496/// a C++ overloaded function (possibly with some parentheses and
11497/// perhaps a '&' around it). We have resolved the overloaded function
11498/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011499/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011500Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011501 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011502 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011503 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11504 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011505 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011506 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011507
Douglas Gregor699ee522009-11-20 19:42:02 +000011508 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011509 }
11510
Douglas Gregor699ee522009-11-20 19:42:02 +000011511 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011512 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11513 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011514 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011515 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011516 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011517 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011518 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011519 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011520
11521 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011522 ICE->getCastKind(),
11523 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011524 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011525 }
11526
Douglas Gregor699ee522009-11-20 19:42:02 +000011527 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011528 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011529 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011530 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11531 if (Method->isStatic()) {
11532 // Do nothing: static member functions aren't any different
11533 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011534 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011535 // Fix the sub expression, which really has to be an
11536 // UnresolvedLookupExpr holding an overloaded member function
11537 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011538 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11539 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011540 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011541 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011542
John McCallba135432009-11-21 08:51:07 +000011543 assert(isa<DeclRefExpr>(SubExpr)
11544 && "fixed to something other than a decl ref");
11545 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11546 && "fixed to a member ref with no nested name qualifier");
11547
11548 // We have taken the address of a pointer to member
11549 // function. Perform the computation here so that we get the
11550 // appropriate pointer to member type.
11551 QualType ClassType
11552 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11553 QualType MemPtrType
11554 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11555
John McCallf89e55a2010-11-18 06:31:45 +000011556 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11557 VK_RValue, OK_Ordinary,
11558 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011559 }
11560 }
John McCall6bb80172010-03-30 21:47:33 +000011561 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11562 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011563 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011564 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011565
John McCall2de56d12010-08-25 11:45:40 +000011566 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011567 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011568 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011569 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011570 }
John McCallba135432009-11-21 08:51:07 +000011571
11572 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011573 // FIXME: avoid copy.
11574 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011575 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011576 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11577 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011578 }
11579
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011580 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11581 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011582 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011583 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011584 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011585 ULE->getNameLoc(),
11586 Fn->getType(),
11587 VK_LValue,
11588 Found.getDecl(),
11589 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011590 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011591 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11592 return DRE;
John McCallba135432009-11-21 08:51:07 +000011593 }
11594
John McCall129e2df2009-11-30 22:42:35 +000011595 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011596 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011597 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11598 if (MemExpr->hasExplicitTemplateArgs()) {
11599 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11600 TemplateArgs = &TemplateArgsBuffer;
11601 }
John McCalld5532b62009-11-23 01:53:49 +000011602
John McCallaa81e162009-12-01 22:10:20 +000011603 Expr *Base;
11604
John McCallf89e55a2010-11-18 06:31:45 +000011605 // If we're filling in a static method where we used to have an
11606 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011607 if (MemExpr->isImplicitAccess()) {
11608 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011609 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11610 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011611 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011612 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011613 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011614 MemExpr->getMemberLoc(),
11615 Fn->getType(),
11616 VK_LValue,
11617 Found.getDecl(),
11618 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011619 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011620 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11621 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011622 } else {
11623 SourceLocation Loc = MemExpr->getMemberLoc();
11624 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011625 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011626 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011627 Base = new (Context) CXXThisExpr(Loc,
11628 MemExpr->getBaseType(),
11629 /*isImplicit=*/true);
11630 }
John McCallaa81e162009-12-01 22:10:20 +000011631 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011632 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011633
John McCallf5307512011-04-27 00:36:17 +000011634 ExprValueKind valueKind;
11635 QualType type;
11636 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11637 valueKind = VK_LValue;
11638 type = Fn->getType();
11639 } else {
11640 valueKind = VK_RValue;
11641 type = Context.BoundMemberTy;
11642 }
11643
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011644 MemberExpr *ME = MemberExpr::Create(Context, Base,
11645 MemExpr->isArrow(),
11646 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011647 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011648 Fn,
11649 Found,
11650 MemExpr->getMemberNameInfo(),
11651 TemplateArgs,
11652 type, valueKind, OK_Ordinary);
11653 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011654 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011655 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011656 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011657
John McCall3fa5cae2010-10-26 07:05:15 +000011658 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011659}
11660
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011661ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011662 DeclAccessPair Found,
11663 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011664 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011665}
11666
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011667} // end namespace clang