blob: fe4cac863049cd2cb1c64a2907288e76bcf38489 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000031#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000033#include <algorithm>
34
35namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000036using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000037
John McCallf89e55a2010-11-18 06:31:45 +000038/// A convenience routine for creating a decayed reference to a
39/// function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000042 SourceLocation Loc = SourceLocation(),
43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000044 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000045 VK_LValue, Loc, LocInfo);
46 if (HadMultipleCandidates)
47 DRE->setHadMultipleCandidates(true);
48 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000049 E = S.DefaultFunctionArrayConversion(E.take());
50 if (E.isInvalid())
51 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000052 return E;
John McCallf89e55a2010-11-18 06:31:45 +000053}
54
John McCall120d63c2010-08-24 20:38:10 +000055static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000057 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000058 bool CStyle,
59 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000060
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000061static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
62 QualType &ToType,
63 bool InOverloadResolution,
64 StandardConversionSequence &SCS,
65 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000066static OverloadingResult
67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
68 UserDefinedConversionSequence& User,
69 OverloadCandidateSet& Conversions,
70 bool AllowExplicit);
71
72
73static ImplicitConversionSequence::CompareKind
74CompareStandardConversionSequences(Sema &S,
75 const StandardConversionSequence& SCS1,
76 const StandardConversionSequence& SCS2);
77
78static ImplicitConversionSequence::CompareKind
79CompareQualificationConversions(Sema &S,
80 const StandardConversionSequence& SCS1,
81 const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareDerivedToBaseConversions(Sema &S,
85 const StandardConversionSequence& SCS1,
86 const StandardConversionSequence& SCS2);
87
88
89
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000090/// GetConversionCategory - Retrieve the implicit conversion
91/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000092ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000093GetConversionCategory(ImplicitConversionKind Kind) {
94 static const ImplicitConversionCategory
95 Category[(int)ICK_Num_Conversion_Kinds] = {
96 ICC_Identity,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000100 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 ICC_Qualification_Adjustment,
102 ICC_Promotion,
103 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 ICC_Promotion,
105 ICC_Conversion,
106 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000112 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000113 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000114 ICC_Conversion,
115 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000116 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 ICC_Conversion
118 };
119 return Category[(int)Kind];
120}
121
122/// GetConversionRank - Retrieve the implicit conversion rank
123/// corresponding to the given implicit conversion kind.
124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
125 static const ImplicitConversionRank
126 Rank[(int)ICK_Num_Conversion_Kinds] = {
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000132 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 ICR_Promotion,
134 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000135 ICR_Promotion,
136 ICR_Conversion,
137 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 ICR_Conversion,
146 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000147 ICR_Complex_Real_Conversion,
148 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000149 ICR_Conversion,
150 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000163 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000167 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000168 "Integral conversion",
169 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000170 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000174 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000175 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000176 "Derived-to-base conversion",
177 "Vector conversion",
178 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000182 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183 };
184 return Name[Kind];
185}
186
Douglas Gregor60d62c22008-10-31 16:23:19 +0000187/// StandardConversionSequence - Set the standard conversion
188/// sequence to the identity conversion.
189void StandardConversionSequence::setAsIdentityConversion() {
190 First = ICK_Identity;
191 Second = ICK_Identity;
192 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000193 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000194 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000195 ReferenceBinding = false;
196 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000197 IsLvalueReference = true;
198 BindsToFunctionLvalue = false;
199 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000200 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000201 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000203}
204
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205/// getRank - Retrieve the rank of this standard conversion sequence
206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207/// implicit conversions.
208ImplicitConversionRank StandardConversionSequence::getRank() const {
209 ImplicitConversionRank Rank = ICR_Exact_Match;
210 if (GetConversionRank(First) > Rank)
211 Rank = GetConversionRank(First);
212 if (GetConversionRank(Second) > Rank)
213 Rank = GetConversionRank(Second);
214 if (GetConversionRank(Third) > Rank)
215 Rank = GetConversionRank(Third);
216 return Rank;
217}
218
219/// isPointerConversionToBool - Determines whether this conversion is
220/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000221/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000222/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000223bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000224 // Note that FromType has not necessarily been transformed by the
225 // array-to-pointer or function-to-pointer implicit conversions, so
226 // check for their presence as well as checking whether FromType is
227 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000228 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000229 (getFromType()->isPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000232 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000243bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000244StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000245isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000246 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000247 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
Douglas Gregorf9af5242011-04-15 20:45:44 +0000255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
266 switch (ICE->getCastKind()) {
267 case CK_NoOp:
268 case CK_IntegralCast:
269 case CK_IntegralToBoolean:
270 case CK_IntegralToFloating:
271 case CK_FloatingToIntegral:
272 case CK_FloatingToBoolean:
273 case CK_FloatingCast:
274 Converted = ICE->getSubExpr();
275 continue;
276
277 default:
278 return Converted;
279 }
280 }
281
282 return Converted;
283}
284
285/// Check if this standard conversion sequence represents a narrowing
286/// conversion, according to C++11 [dcl.init.list]p7.
287///
288/// \param Ctx The AST context.
289/// \param Converted The result of applying this standard conversion sequence.
290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
291/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
293/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000294NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000297 APValue &ConstantValue,
298 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000300
301 // C++11 [dcl.init.list]p7:
302 // A narrowing conversion is an implicit conversion ...
303 QualType FromType = getToType(0);
304 QualType ToType = getToType(1);
305 switch (Second) {
306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314 return NK_Type_Narrowing;
315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316 llvm::APSInt IntConstantValue;
317 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318 if (Initializer &&
319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320 // Convert the integer to the floating type.
321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323 llvm::APFloat::rmNearestTiesToEven);
324 // And back.
325 llvm::APSInt ConvertedValue = IntConstantValue;
326 bool ignored;
327 Result.convertToInteger(ConvertedValue,
328 llvm::APFloat::rmTowardZero, &ignored);
329 // If the resulting value is different, this was a narrowing conversion.
330 if (IntConstantValue != ConvertedValue) {
331 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000332 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000333 return NK_Constant_Narrowing;
334 }
335 } else {
336 // Variables are always narrowings.
337 return NK_Variable_Narrowing;
338 }
339 }
340 return NK_Not_Narrowing;
341
342 // -- from long double to double or float, or from double to float, except
343 // where the source is a constant expression and the actual value after
344 // conversion is within the range of values that can be represented (even
345 // if it cannot be represented exactly), or
346 case ICK_Floating_Conversion:
347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349 // FromType is larger than ToType.
350 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352 // Constant!
353 assert(ConstantValue.isFloat());
354 llvm::APFloat FloatVal = ConstantValue.getFloat();
355 // Convert the source value into the target type.
356 bool ignored;
357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358 Ctx.getFloatTypeSemantics(ToType),
359 llvm::APFloat::rmNearestTiesToEven, &ignored);
360 // If there was no overflow, the source value is within the range of
361 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000362 if (ConvertStatus & llvm::APFloat::opOverflow) {
363 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000364 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000365 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000366 } else {
367 return NK_Variable_Narrowing;
368 }
369 }
370 return NK_Not_Narrowing;
371
372 // -- from an integer type or unscoped enumeration type to an integer type
373 // that cannot represent all the values of the original type, except where
374 // the source is a constant expression and the actual value after
375 // conversion will fit into the target type and will produce the original
376 // value when converted back to the original type.
377 case ICK_Boolean_Conversion: // Bools are integers too.
378 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379 // Boolean conversions can be from pointers and pointers to members
380 // [conv.bool], and those aren't considered narrowing conversions.
381 return NK_Not_Narrowing;
382 } // Otherwise, fall through to the integral case.
383 case ICK_Integral_Conversion: {
384 assert(FromType->isIntegralOrUnscopedEnumerationType());
385 assert(ToType->isIntegralOrUnscopedEnumerationType());
386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387 const unsigned FromWidth = Ctx.getIntWidth(FromType);
388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389 const unsigned ToWidth = Ctx.getIntWidth(ToType);
390
391 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000392 (FromWidth == ToWidth && FromSigned != ToSigned) ||
393 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000394 // Not all values of FromType can be represented in ToType.
395 llvm::APSInt InitializerValue;
396 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
398 // Such conversions on variables are always narrowing.
399 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000400 }
401 bool Narrowing = false;
402 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000403 // Negative -> unsigned is narrowing. Otherwise, more bits is never
404 // narrowing.
405 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000406 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000407 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000408 // Add a bit to the InitializerValue so we don't have to worry about
409 // signed vs. unsigned comparisons.
410 InitializerValue = InitializerValue.extend(
411 InitializerValue.getBitWidth() + 1);
412 // Convert the initializer to and from the target width and signed-ness.
413 llvm::APSInt ConvertedValue = InitializerValue;
414 ConvertedValue = ConvertedValue.trunc(ToWidth);
415 ConvertedValue.setIsSigned(ToSigned);
416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
417 ConvertedValue.setIsSigned(InitializerValue.isSigned());
418 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000419 if (ConvertedValue != InitializerValue)
420 Narrowing = true;
421 }
422 if (Narrowing) {
423 ConstantType = Initializer->getType();
424 ConstantValue = APValue(InitializerValue);
425 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000426 }
427 }
428 return NK_Not_Narrowing;
429 }
430
431 default:
432 // Other kinds of conversions are not narrowings.
433 return NK_Not_Narrowing;
434 }
435}
436
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000437/// DebugPrint - Print this standard conversion sequence to standard
438/// error. Useful for debugging overloading issues.
439void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000440 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000441 bool PrintedSomething = false;
442 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000443 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000444 PrintedSomething = true;
445 }
446
447 if (Second != ICK_Identity) {
448 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000449 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000451 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000452
453 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000455 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000457 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000458 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000459 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Third != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
474}
475
476/// DebugPrint - Print this user-defined conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 if (Before.First || Before.Second || Before.Third) {
481 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000482 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000484 if (ConversionFunction)
485 OS << '\'' << *ConversionFunction << '\'';
486 else
487 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 After.DebugPrint();
491 }
492}
493
494/// DebugPrint - Print this implicit conversion sequence to standard
495/// error. Useful for debugging overloading issues.
496void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000497 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498 switch (ConversionKind) {
499 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000500 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501 Standard.DebugPrint();
502 break;
503 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000504 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 UserDefined.DebugPrint();
506 break;
507 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000508 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509 break;
John McCall1d318332010-01-12 00:44:57 +0000510 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000511 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000512 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000514 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 break;
516 }
517
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519}
520
John McCall1d318332010-01-12 00:44:57 +0000521void AmbiguousConversionSequence::construct() {
522 new (&conversions()) ConversionSet();
523}
524
525void AmbiguousConversionSequence::destruct() {
526 conversions().~ConversionSet();
527}
528
529void
530AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
531 FromTypePtr = O.FromTypePtr;
532 ToTypePtr = O.ToTypePtr;
533 new (&conversions()) ConversionSet(O.conversions());
534}
535
Douglas Gregora9333192010-05-08 17:41:32 +0000536namespace {
537 // Structure used by OverloadCandidate::DeductionFailureInfo to store
538 // template parameter and template argument information.
539 struct DFIParamWithArguments {
540 TemplateParameter Param;
541 TemplateArgument FirstArg;
542 TemplateArgument SecondArg;
543 };
544}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000545
Douglas Gregora9333192010-05-08 17:41:32 +0000546/// \brief Convert from Sema's representation of template deduction information
547/// to the form used in overload-candidate information.
548OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000549static MakeDeductionFailureInfo(ASTContext &Context,
550 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000551 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000552 OverloadCandidate::DeductionFailureInfo Result;
553 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000554 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000555 Result.Data = 0;
556 switch (TDK) {
557 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000558 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000559 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000560 case Sema::TDK_TooManyArguments:
561 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000562 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000565 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000566 Result.Data = Info.Param.getOpaqueValue();
567 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora9333192010-05-08 17:41:32 +0000569 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000570 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000571 // FIXME: Should allocate from normal heap so that we can free this later.
572 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000573 Saved->Param = Info.Param;
574 Saved->FirstArg = Info.FirstArg;
575 Saved->SecondArg = Info.SecondArg;
576 Result.Data = Saved;
577 break;
578 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579
Douglas Gregora9333192010-05-08 17:41:32 +0000580 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000581 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000582 if (Info.hasSFINAEDiagnostic()) {
583 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
584 SourceLocation(), PartialDiagnostic::NullDiagnostic());
585 Info.takeSFINAEDiagnostic(*Diag);
586 Result.HasDiagnostic = true;
587 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589
Douglas Gregora9333192010-05-08 17:41:32 +0000590 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000591 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000592 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000593 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594
Douglas Gregora9333192010-05-08 17:41:32 +0000595 return Result;
596}
John McCall1d318332010-01-12 00:44:57 +0000597
Douglas Gregora9333192010-05-08 17:41:32 +0000598void OverloadCandidate::DeductionFailureInfo::Destroy() {
599 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
600 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000601 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000602 case Sema::TDK_InstantiationDepth:
603 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000604 case Sema::TDK_TooManyArguments:
605 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000606 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000607 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000608
Douglas Gregora9333192010-05-08 17:41:32 +0000609 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000610 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000611 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000612 Data = 0;
613 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000614
615 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000616 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000617 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000618 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
619 Diag->~PartialDiagnosticAt();
620 HasDiagnostic = false;
621 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000622 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000624 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000625 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000626 case Sema::TDK_FailedOverloadResolution:
627 break;
628 }
629}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000630
Richard Smithb8590f32012-05-07 09:03:25 +0000631PartialDiagnosticAt *
632OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
633 if (HasDiagnostic)
634 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
635 return 0;
636}
637
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000638TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000639OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000642 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000643 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000646 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000647 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648
Douglas Gregora9333192010-05-08 17:41:32 +0000649 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000650 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000651 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000652
653 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000654 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000655 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000656
Douglas Gregora9333192010-05-08 17:41:32 +0000657 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000658 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000659 case Sema::TDK_FailedOverloadResolution:
660 break;
661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000662
Douglas Gregora9333192010-05-08 17:41:32 +0000663 return TemplateParameter();
664}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665
Douglas Gregorec20f462010-05-08 20:07:26 +0000666TemplateArgumentList *
667OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000670 case Sema::TDK_Invalid:
Douglas Gregorec20f462010-05-08 20:07:26 +0000671 case Sema::TDK_InstantiationDepth:
672 case Sema::TDK_TooManyArguments:
673 case Sema::TDK_TooFewArguments:
674 case Sema::TDK_Incomplete:
675 case Sema::TDK_InvalidExplicitArguments:
676 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000677 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000678 return 0;
679
680 case Sema::TDK_SubstitutionFailure:
681 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682
Douglas Gregorec20f462010-05-08 20:07:26 +0000683 // Unhandled
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
686 break;
687 }
688
689 return 0;
690}
691
Douglas Gregora9333192010-05-08 17:41:32 +0000692const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
694 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000695 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000696 case Sema::TDK_InstantiationDepth:
697 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000698 case Sema::TDK_TooManyArguments:
699 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000700 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000701 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000702 return 0;
703
Douglas Gregora9333192010-05-08 17:41:32 +0000704 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000705 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000706 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000707
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000708 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000709 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000710 case Sema::TDK_FailedOverloadResolution:
711 break;
712 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713
Douglas Gregora9333192010-05-08 17:41:32 +0000714 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715}
Douglas Gregora9333192010-05-08 17:41:32 +0000716
717const TemplateArgument *
718OverloadCandidate::DeductionFailureInfo::getSecondArg() {
719 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
720 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000721 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000722 case Sema::TDK_InstantiationDepth:
723 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000724 case Sema::TDK_TooManyArguments:
725 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000726 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000727 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000728 return 0;
729
Douglas Gregora9333192010-05-08 17:41:32 +0000730 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000731 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000732 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
733
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000734 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000735 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 case Sema::TDK_FailedOverloadResolution:
737 break;
738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000739
Douglas Gregora9333192010-05-08 17:41:32 +0000740 return 0;
741}
742
743void OverloadCandidateSet::clear() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000744 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000745 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
746 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000747 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
748 i->DeductionFailure.Destroy();
749 }
Benjamin Kramer314f5542012-01-14 19:31:39 +0000750 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000751 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000752 Functions.clear();
753}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000754
John McCall5acb0c92011-10-17 18:40:02 +0000755namespace {
756 class UnbridgedCastsSet {
757 struct Entry {
758 Expr **Addr;
759 Expr *Saved;
760 };
761 SmallVector<Entry, 2> Entries;
762
763 public:
764 void save(Sema &S, Expr *&E) {
765 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
766 Entry entry = { &E, E };
767 Entries.push_back(entry);
768 E = S.stripARCUnbridgedCast(E);
769 }
770
771 void restore() {
772 for (SmallVectorImpl<Entry>::iterator
773 i = Entries.begin(), e = Entries.end(); i != e; ++i)
774 *i->Addr = i->Saved;
775 }
776 };
777}
778
779/// checkPlaceholderForOverload - Do any interesting placeholder-like
780/// preprocessing on the given expression.
781///
782/// \param unbridgedCasts a collection to which to add unbridged casts;
783/// without this, they will be immediately diagnosed as errors
784///
785/// Return true on unrecoverable error.
786static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
787 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000788 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
789 // We can't handle overloaded expressions here because overload
790 // resolution might reasonably tweak them.
791 if (placeholder->getKind() == BuiltinType::Overload) return false;
792
793 // If the context potentially accepts unbridged ARC casts, strip
794 // the unbridged cast and add it to the collection for later restoration.
795 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
796 unbridgedCasts) {
797 unbridgedCasts->save(S, E);
798 return false;
799 }
800
801 // Go ahead and check everything else.
802 ExprResult result = S.CheckPlaceholderExpr(E);
803 if (result.isInvalid())
804 return true;
805
806 E = result.take();
807 return false;
808 }
809
810 // Nothing to do.
811 return false;
812}
813
814/// checkArgPlaceholdersForOverload - Check a set of call operands for
815/// placeholders.
816static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
817 unsigned numArgs,
818 UnbridgedCastsSet &unbridged) {
819 for (unsigned i = 0; i != numArgs; ++i)
820 if (checkPlaceholderForOverload(S, args[i], &unbridged))
821 return true;
822
823 return false;
824}
825
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000826// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000827// overload of the declarations in Old. This routine returns false if
828// New and Old cannot be overloaded, e.g., if New has the same
829// signature as some function in Old (C++ 1.3.10) or if the Old
830// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000831// it does return false, MatchedDecl will point to the decl that New
832// cannot be overloaded with. This decl may be a UsingShadowDecl on
833// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000834//
835// Example: Given the following input:
836//
837// void f(int, float); // #1
838// void f(int, int); // #2
839// int f(int, int); // #3
840//
841// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000842// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000843//
John McCall51fa86f2009-12-02 08:47:38 +0000844// When we process #2, Old contains only the FunctionDecl for #1. By
845// comparing the parameter types, we see that #1 and #2 are overloaded
846// (since they have different signatures), so this routine returns
847// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000848//
John McCall51fa86f2009-12-02 08:47:38 +0000849// When we process #3, Old is an overload set containing #1 and #2. We
850// compare the signatures of #3 to #1 (they're overloaded, so we do
851// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
852// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000853// signature), IsOverload returns false and MatchedDecl will be set to
854// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000855//
856// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
857// into a class by a using declaration. The rules for whether to hide
858// shadow declarations ignore some properties which otherwise figure
859// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000860Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000861Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
862 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000863 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000864 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000865 NamedDecl *OldD = *I;
866
867 bool OldIsUsingDecl = false;
868 if (isa<UsingShadowDecl>(OldD)) {
869 OldIsUsingDecl = true;
870
871 // We can always introduce two using declarations into the same
872 // context, even if they have identical signatures.
873 if (NewIsUsingDecl) continue;
874
875 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
876 }
877
878 // If either declaration was introduced by a using declaration,
879 // we'll need to use slightly different rules for matching.
880 // Essentially, these rules are the normal rules, except that
881 // function templates hide function templates with different
882 // return types or template parameter lists.
883 bool UseMemberUsingDeclRules =
884 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
885
John McCall51fa86f2009-12-02 08:47:38 +0000886 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000887 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
888 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
889 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
890 continue;
891 }
892
John McCall871b2e72009-12-09 03:35:25 +0000893 Match = *I;
894 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895 }
John McCall51fa86f2009-12-02 08:47:38 +0000896 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000897 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
898 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
899 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
900 continue;
901 }
902
John McCall871b2e72009-12-09 03:35:25 +0000903 Match = *I;
904 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000905 }
John McCalld7945c62010-11-10 03:01:53 +0000906 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000907 // We can overload with these, which can show up when doing
908 // redeclaration checks for UsingDecls.
909 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000910 } else if (isa<TagDecl>(OldD)) {
911 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000912 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
913 // Optimistically assume that an unresolved using decl will
914 // overload; if it doesn't, we'll have to diagnose during
915 // template instantiation.
916 } else {
John McCall68263142009-11-18 22:49:29 +0000917 // (C++ 13p1):
918 // Only function declarations can be overloaded; object and type
919 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000920 Match = *I;
921 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000922 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000923 }
John McCall68263142009-11-18 22:49:29 +0000924
John McCall871b2e72009-12-09 03:35:25 +0000925 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000926}
927
John McCallad00b772010-06-16 08:42:20 +0000928bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
929 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000930 // If both of the functions are extern "C", then they are not
931 // overloads.
932 if (Old->isExternC() && New->isExternC())
933 return false;
934
John McCall68263142009-11-18 22:49:29 +0000935 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
936 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
937
938 // C++ [temp.fct]p2:
939 // A function template can be overloaded with other function templates
940 // and with normal (non-template) functions.
941 if ((OldTemplate == 0) != (NewTemplate == 0))
942 return true;
943
944 // Is the function New an overload of the function Old?
945 QualType OldQType = Context.getCanonicalType(Old->getType());
946 QualType NewQType = Context.getCanonicalType(New->getType());
947
948 // Compare the signatures (C++ 1.3.10) of the two functions to
949 // determine whether they are overloads. If we find any mismatch
950 // in the signature, they are overloads.
951
952 // If either of these functions is a K&R-style function (no
953 // prototype), then we consider them to have matching signatures.
954 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
955 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
956 return false;
957
John McCallf4c73712011-01-19 06:33:43 +0000958 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
959 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000960
961 // The signature of a function includes the types of its
962 // parameters (C++ 1.3.10), which includes the presence or absence
963 // of the ellipsis; see C++ DR 357).
964 if (OldQType != NewQType &&
965 (OldType->getNumArgs() != NewType->getNumArgs() ||
966 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000967 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000968 return true;
969
970 // C++ [temp.over.link]p4:
971 // The signature of a function template consists of its function
972 // signature, its return type and its template parameter list. The names
973 // of the template parameters are significant only for establishing the
974 // relationship between the template parameters and the rest of the
975 // signature.
976 //
977 // We check the return type and template parameter lists for function
978 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000979 //
980 // However, we don't consider either of these when deciding whether
981 // a member introduced by a shadow declaration is hidden.
982 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000983 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
984 OldTemplate->getTemplateParameters(),
985 false, TPL_TemplateMatch) ||
986 OldType->getResultType() != NewType->getResultType()))
987 return true;
988
989 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000990 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000991 //
992 // As part of this, also check whether one of the member functions
993 // is static, in which case they are not overloads (C++
994 // 13.1p2). While not part of the definition of the signature,
995 // this check is important to determine whether these functions
996 // can be overloaded.
997 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
998 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
999 if (OldMethod && NewMethod &&
1000 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001001 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +00001002 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1003 if (!UseUsingDeclRules &&
1004 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1005 (OldMethod->getRefQualifier() == RQ_None ||
1006 NewMethod->getRefQualifier() == RQ_None)) {
1007 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001008 // - Member function declarations with the same name and the same
1009 // parameter-type-list as well as member function template
1010 // declarations with the same name, the same parameter-type-list, and
1011 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +00001012 // them, but not all, have a ref-qualifier (8.3.5).
1013 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1014 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1015 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
John McCall68263142009-11-18 22:49:29 +00001018 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001019 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001020
John McCall68263142009-11-18 22:49:29 +00001021 // The signatures match; this is not an overload.
1022 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001023}
1024
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001025/// \brief Checks availability of the function depending on the current
1026/// function context. Inside an unavailable function, unavailability is ignored.
1027///
1028/// \returns true if \arg FD is unavailable and current context is inside
1029/// an available function, false otherwise.
1030bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1031 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1032}
1033
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001034/// \brief Tries a user-defined conversion from From to ToType.
1035///
1036/// Produces an implicit conversion sequence for when a standard conversion
1037/// is not an option. See TryImplicitConversion for more information.
1038static ImplicitConversionSequence
1039TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1040 bool SuppressUserConversions,
1041 bool AllowExplicit,
1042 bool InOverloadResolution,
1043 bool CStyle,
1044 bool AllowObjCWritebackConversion) {
1045 ImplicitConversionSequence ICS;
1046
1047 if (SuppressUserConversions) {
1048 // We're not in the case above, so there is no conversion that
1049 // we can perform.
1050 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1051 return ICS;
1052 }
1053
1054 // Attempt user-defined conversion.
1055 OverloadCandidateSet Conversions(From->getExprLoc());
1056 OverloadingResult UserDefResult
1057 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1058 AllowExplicit);
1059
1060 if (UserDefResult == OR_Success) {
1061 ICS.setUserDefined();
1062 // C++ [over.ics.user]p4:
1063 // A conversion of an expression of class type to the same class
1064 // type is given Exact Match rank, and a conversion of an
1065 // expression of class type to a base class of that type is
1066 // given Conversion rank, in spite of the fact that a copy
1067 // constructor (i.e., a user-defined conversion function) is
1068 // called for those cases.
1069 if (CXXConstructorDecl *Constructor
1070 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1071 QualType FromCanon
1072 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1073 QualType ToCanon
1074 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1075 if (Constructor->isCopyConstructor() &&
1076 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1077 // Turn this into a "standard" conversion sequence, so that it
1078 // gets ranked with standard conversion sequences.
1079 ICS.setStandard();
1080 ICS.Standard.setAsIdentityConversion();
1081 ICS.Standard.setFromType(From->getType());
1082 ICS.Standard.setAllToTypes(ToType);
1083 ICS.Standard.CopyConstructor = Constructor;
1084 if (ToCanon != FromCanon)
1085 ICS.Standard.Second = ICK_Derived_To_Base;
1086 }
1087 }
1088
1089 // C++ [over.best.ics]p4:
1090 // However, when considering the argument of a user-defined
1091 // conversion function that is a candidate by 13.3.1.3 when
1092 // invoked for the copying of the temporary in the second step
1093 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1094 // 13.3.1.6 in all cases, only standard conversion sequences and
1095 // ellipsis conversion sequences are allowed.
1096 if (SuppressUserConversions && ICS.isUserDefined()) {
1097 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1098 }
1099 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1100 ICS.setAmbiguous();
1101 ICS.Ambiguous.setFromType(From->getType());
1102 ICS.Ambiguous.setToType(ToType);
1103 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1104 Cand != Conversions.end(); ++Cand)
1105 if (Cand->Viable)
1106 ICS.Ambiguous.addConversion(Cand->Function);
1107 } else {
1108 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1109 }
1110
1111 return ICS;
1112}
1113
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001114/// TryImplicitConversion - Attempt to perform an implicit conversion
1115/// from the given expression (Expr) to the given type (ToType). This
1116/// function returns an implicit conversion sequence that can be used
1117/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001118///
1119/// void f(float f);
1120/// void g(int i) { f(i); }
1121///
1122/// this routine would produce an implicit conversion sequence to
1123/// describe the initialization of f from i, which will be a standard
1124/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1125/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1126//
1127/// Note that this routine only determines how the conversion can be
1128/// performed; it does not actually perform the conversion. As such,
1129/// it will not produce any diagnostics if no conversion is available,
1130/// but will instead return an implicit conversion sequence of kind
1131/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001132///
1133/// If @p SuppressUserConversions, then user-defined conversions are
1134/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001135/// If @p AllowExplicit, then explicit user-defined conversions are
1136/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001137///
1138/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1139/// writeback conversion, which allows __autoreleasing id* parameters to
1140/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001141static ImplicitConversionSequence
1142TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1143 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001144 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001145 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001146 bool CStyle,
1147 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001148 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001149 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001150 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001151 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001152 return ICS;
1153 }
1154
David Blaikie4e4d0842012-03-11 07:00:24 +00001155 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001156 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001157 return ICS;
1158 }
1159
Douglas Gregor604eb652010-08-11 02:15:33 +00001160 // C++ [over.ics.user]p4:
1161 // A conversion of an expression of class type to the same class
1162 // type is given Exact Match rank, and a conversion of an
1163 // expression of class type to a base class of that type is
1164 // given Conversion rank, in spite of the fact that a copy/move
1165 // constructor (i.e., a user-defined conversion function) is
1166 // called for those cases.
1167 QualType FromType = From->getType();
1168 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001169 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1170 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001171 ICS.setStandard();
1172 ICS.Standard.setAsIdentityConversion();
1173 ICS.Standard.setFromType(FromType);
1174 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001175
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001176 // We don't actually check at this point whether there is a valid
1177 // copy/move constructor, since overloading just assumes that it
1178 // exists. When we actually perform initialization, we'll find the
1179 // appropriate constructor to copy the returned object, if needed.
1180 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001181
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001182 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001183 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001184 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001185
Douglas Gregor604eb652010-08-11 02:15:33 +00001186 return ICS;
1187 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001188
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001189 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1190 AllowExplicit, InOverloadResolution, CStyle,
1191 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001192}
1193
John McCallf85e1932011-06-15 23:02:42 +00001194ImplicitConversionSequence
1195Sema::TryImplicitConversion(Expr *From, QualType ToType,
1196 bool SuppressUserConversions,
1197 bool AllowExplicit,
1198 bool InOverloadResolution,
1199 bool CStyle,
1200 bool AllowObjCWritebackConversion) {
1201 return clang::TryImplicitConversion(*this, From, ToType,
1202 SuppressUserConversions, AllowExplicit,
1203 InOverloadResolution, CStyle,
1204 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001205}
1206
Douglas Gregor575c63a2010-04-16 22:27:05 +00001207/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001208/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001209/// converted expression. Flavor is the kind of conversion we're
1210/// performing, used in the error message. If @p AllowExplicit,
1211/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001212ExprResult
1213Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001214 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001215 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001216 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001217}
1218
John Wiegley429bb272011-04-08 18:41:53 +00001219ExprResult
1220Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001221 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001222 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001223 if (checkPlaceholderForOverload(*this, From))
1224 return ExprError();
1225
John McCallf85e1932011-06-15 23:02:42 +00001226 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1227 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001228 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001229 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001230
John McCall120d63c2010-08-24 20:38:10 +00001231 ICS = clang::TryImplicitConversion(*this, From, ToType,
1232 /*SuppressUserConversions=*/false,
1233 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001234 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001235 /*CStyle=*/false,
1236 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001237 return PerformImplicitConversion(From, ToType, ICS, Action);
1238}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001239
1240/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001241/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001242bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1243 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001244 if (Context.hasSameUnqualifiedType(FromType, ToType))
1245 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001246
John McCall00ccbef2010-12-21 00:44:39 +00001247 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1248 // where F adds one of the following at most once:
1249 // - a pointer
1250 // - a member pointer
1251 // - a block pointer
1252 CanQualType CanTo = Context.getCanonicalType(ToType);
1253 CanQualType CanFrom = Context.getCanonicalType(FromType);
1254 Type::TypeClass TyClass = CanTo->getTypeClass();
1255 if (TyClass != CanFrom->getTypeClass()) return false;
1256 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1257 if (TyClass == Type::Pointer) {
1258 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1259 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1260 } else if (TyClass == Type::BlockPointer) {
1261 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1262 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1263 } else if (TyClass == Type::MemberPointer) {
1264 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1265 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1266 } else {
1267 return false;
1268 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001269
John McCall00ccbef2010-12-21 00:44:39 +00001270 TyClass = CanTo->getTypeClass();
1271 if (TyClass != CanFrom->getTypeClass()) return false;
1272 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1273 return false;
1274 }
1275
1276 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1277 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1278 if (!EInfo.getNoReturn()) return false;
1279
1280 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1281 assert(QualType(FromFn, 0).isCanonical());
1282 if (QualType(FromFn, 0) != CanTo) return false;
1283
1284 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001285 return true;
1286}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001287
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001288/// \brief Determine whether the conversion from FromType to ToType is a valid
1289/// vector conversion.
1290///
1291/// \param ICK Will be set to the vector conversion kind, if this is a vector
1292/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001293static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1294 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001295 // We need at least one of these types to be a vector type to have a vector
1296 // conversion.
1297 if (!ToType->isVectorType() && !FromType->isVectorType())
1298 return false;
1299
1300 // Identical types require no conversions.
1301 if (Context.hasSameUnqualifiedType(FromType, ToType))
1302 return false;
1303
1304 // There are no conversions between extended vector types, only identity.
1305 if (ToType->isExtVectorType()) {
1306 // There are no conversions between extended vector types other than the
1307 // identity conversion.
1308 if (FromType->isExtVectorType())
1309 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001310
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001311 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001312 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001313 ICK = ICK_Vector_Splat;
1314 return true;
1315 }
1316 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001317
1318 // We can perform the conversion between vector types in the following cases:
1319 // 1)vector types are equivalent AltiVec and GCC vector types
1320 // 2)lax vector conversions are permitted and the vector types are of the
1321 // same size
1322 if (ToType->isVectorType() && FromType->isVectorType()) {
1323 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001324 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001325 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001326 ICK = ICK_Vector_Conversion;
1327 return true;
1328 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001329 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001330
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001331 return false;
1332}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001333
Douglas Gregor7d000652012-04-12 20:48:09 +00001334static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1335 bool InOverloadResolution,
1336 StandardConversionSequence &SCS,
1337 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001338
Douglas Gregor60d62c22008-10-31 16:23:19 +00001339/// IsStandardConversion - Determines whether there is a standard
1340/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1341/// expression From to the type ToType. Standard conversion sequences
1342/// only consider non-class types; for conversions that involve class
1343/// types, use TryImplicitConversion. If a conversion exists, SCS will
1344/// contain the standard conversion sequence required to perform this
1345/// conversion and this routine will return true. Otherwise, this
1346/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001347static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1348 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001349 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001350 bool CStyle,
1351 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001352 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001353
Douglas Gregor60d62c22008-10-31 16:23:19 +00001354 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001355 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001356 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001357 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001358 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001359 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001360
Douglas Gregorf9201e02009-02-11 23:02:49 +00001361 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001362 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001363 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001364 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001365 return false;
1366
Mike Stump1eb44332009-09-09 15:08:12 +00001367 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001368 }
1369
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001370 // The first conversion can be an lvalue-to-rvalue conversion,
1371 // array-to-pointer conversion, or function-to-pointer conversion
1372 // (C++ 4p1).
1373
John McCall120d63c2010-08-24 20:38:10 +00001374 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001375 DeclAccessPair AccessPair;
1376 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001377 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001378 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001379 // We were able to resolve the address of the overloaded function,
1380 // so we can convert to the type of that function.
1381 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001382
1383 // we can sometimes resolve &foo<int> regardless of ToType, so check
1384 // if the type matches (identity) or we are converting to bool
1385 if (!S.Context.hasSameUnqualifiedType(
1386 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1387 QualType resultTy;
1388 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001389 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001390 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1391 // otherwise, only a boolean conversion is standard
1392 if (!ToType->isBooleanType())
1393 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001394 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001395
Chandler Carruth90434232011-03-29 08:08:18 +00001396 // Check if the "from" expression is taking the address of an overloaded
1397 // function and recompute the FromType accordingly. Take advantage of the
1398 // fact that non-static member functions *must* have such an address-of
1399 // expression.
1400 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1401 if (Method && !Method->isStatic()) {
1402 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1403 "Non-unary operator on non-static member address");
1404 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1405 == UO_AddrOf &&
1406 "Non-address-of operator on non-static member address");
1407 const Type *ClassType
1408 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1409 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001410 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1411 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1412 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001413 "Non-address-of operator for overloaded function expression");
1414 FromType = S.Context.getPointerType(FromType);
1415 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001416
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001417 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001418 assert(S.Context.hasSameType(
1419 FromType,
1420 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001421 } else {
1422 return false;
1423 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001424 }
John McCall21480112011-08-30 00:57:29 +00001425 // Lvalue-to-rvalue conversion (C++11 4.1):
1426 // A glvalue (3.10) of a non-function, non-array type T can
1427 // be converted to a prvalue.
1428 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001429 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001430 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001431 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001432 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001433
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001434 // C11 6.3.2.1p2:
1435 // ... if the lvalue has atomic type, the value has the non-atomic version
1436 // of the type of the lvalue ...
1437 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1438 FromType = Atomic->getValueType();
1439
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001440 // If T is a non-class type, the type of the rvalue is the
1441 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001442 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1443 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001444 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001445 } else if (FromType->isArrayType()) {
1446 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001447 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001448
1449 // An lvalue or rvalue of type "array of N T" or "array of unknown
1450 // bound of T" can be converted to an rvalue of type "pointer to
1451 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001452 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001453
John McCall120d63c2010-08-24 20:38:10 +00001454 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001455 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001456 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001457
1458 // For the purpose of ranking in overload resolution
1459 // (13.3.3.1.1), this conversion is considered an
1460 // array-to-pointer conversion followed by a qualification
1461 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001462 SCS.Second = ICK_Identity;
1463 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001464 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001465 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001466 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001467 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001468 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001469 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001470 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001471
1472 // An lvalue of function type T can be converted to an rvalue of
1473 // type "pointer to T." The result is a pointer to the
1474 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001475 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001476 } else {
1477 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001478 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001479 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001480 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001481
1482 // The second conversion can be an integral promotion, floating
1483 // point promotion, integral conversion, floating point conversion,
1484 // floating-integral conversion, pointer conversion,
1485 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001486 // For overloading in C, this can also be a "compatible-type"
1487 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001488 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001489 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001490 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001491 // The unqualified versions of the types are the same: there's no
1492 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001493 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001494 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001495 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001496 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001497 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001498 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001499 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001502 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001503 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001504 SCS.Second = ICK_Complex_Promotion;
1505 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001506 } else if (ToType->isBooleanType() &&
1507 (FromType->isArithmeticType() ||
1508 FromType->isAnyPointerType() ||
1509 FromType->isBlockPointerType() ||
1510 FromType->isMemberPointerType() ||
1511 FromType->isNullPtrType())) {
1512 // Boolean conversions (C++ 4.12).
1513 SCS.Second = ICK_Boolean_Conversion;
1514 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001515 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001516 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001517 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001518 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001519 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001520 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001521 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001522 SCS.Second = ICK_Complex_Conversion;
1523 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001524 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1525 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001526 // Complex-real conversions (C99 6.3.1.7)
1527 SCS.Second = ICK_Complex_Real;
1528 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001529 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001530 // Floating point conversions (C++ 4.8).
1531 SCS.Second = ICK_Floating_Conversion;
1532 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001533 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001534 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001535 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001536 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001537 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001538 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001540 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001541 SCS.Second = ICK_Block_Pointer_Conversion;
1542 } else if (AllowObjCWritebackConversion &&
1543 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1544 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001545 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1546 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001547 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001548 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001549 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001550 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001551 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001552 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001553 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001554 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001555 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001556 SCS.Second = SecondICK;
1557 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001558 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001559 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001560 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001561 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001562 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001563 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001564 // Treat a conversion that strips "noreturn" as an identity conversion.
1565 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001566 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1567 InOverloadResolution,
1568 SCS, CStyle)) {
1569 SCS.Second = ICK_TransparentUnionConversion;
1570 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001571 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1572 CStyle)) {
1573 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001574 // appropriately.
1575 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001576 } else {
1577 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001578 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001579 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001580 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001581
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001582 QualType CanonFrom;
1583 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001584 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001585 bool ObjCLifetimeConversion;
1586 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1587 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001588 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001589 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001590 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001591 CanonFrom = S.Context.getCanonicalType(FromType);
1592 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001593 } else {
1594 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001595 SCS.Third = ICK_Identity;
1596
Mike Stump1eb44332009-09-09 15:08:12 +00001597 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001598 // [...] Any difference in top-level cv-qualification is
1599 // subsumed by the initialization itself and does not constitute
1600 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001601 CanonFrom = S.Context.getCanonicalType(FromType);
1602 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001604 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001605 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001606 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1607 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001608 FromType = ToType;
1609 CanonFrom = CanonTo;
1610 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001611 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001612 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001613
1614 // If we have not converted the argument type to the parameter type,
1615 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001616 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001617 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001618
Douglas Gregor60d62c22008-10-31 16:23:19 +00001619 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001620}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001621
1622static bool
1623IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1624 QualType &ToType,
1625 bool InOverloadResolution,
1626 StandardConversionSequence &SCS,
1627 bool CStyle) {
1628
1629 const RecordType *UT = ToType->getAsUnionType();
1630 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1631 return false;
1632 // The field to initialize within the transparent union.
1633 RecordDecl *UD = UT->getDecl();
1634 // It's compatible if the expression matches any of the fields.
1635 for (RecordDecl::field_iterator it = UD->field_begin(),
1636 itend = UD->field_end();
1637 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001638 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1639 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001640 ToType = it->getType();
1641 return true;
1642 }
1643 }
1644 return false;
1645}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001646
1647/// IsIntegralPromotion - Determines whether the conversion from the
1648/// expression From (whose potentially-adjusted type is FromType) to
1649/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1650/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001651bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001652 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001653 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001654 if (!To) {
1655 return false;
1656 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657
1658 // An rvalue of type char, signed char, unsigned char, short int, or
1659 // unsigned short int can be converted to an rvalue of type int if
1660 // int can represent all the values of the source type; otherwise,
1661 // the source rvalue can be converted to an rvalue of type unsigned
1662 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001663 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1664 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 if (// We can promote any signed, promotable integer type to an int
1666 (FromType->isSignedIntegerType() ||
1667 // We can promote any unsigned integer type whose size is
1668 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001669 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001670 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001671 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001672 }
1673
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001674 return To->getKind() == BuiltinType::UInt;
1675 }
1676
Richard Smithe7ff9192012-09-13 21:18:54 +00001677 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678 // A prvalue of an unscoped enumeration type whose underlying type is not
1679 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1680 // following types that can represent all the values of the enumeration
1681 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1682 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001683 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001684 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001685 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001686 // with lowest integer conversion rank (4.13) greater than the rank of long
1687 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001688 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001689 // C++11 [conv.prom]p4:
1690 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1691 // can be converted to a prvalue of its underlying type. Moreover, if
1692 // integral promotion can be applied to its underlying type, a prvalue of an
1693 // unscoped enumeration type whose underlying type is fixed can also be
1694 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001695 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1696 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1697 // provided for a scoped enumeration.
1698 if (FromEnumType->getDecl()->isScoped())
1699 return false;
1700
Richard Smithe7ff9192012-09-13 21:18:54 +00001701 // We can perform an integral promotion to the underlying type of the enum,
1702 // even if that's not the promoted type.
1703 if (FromEnumType->getDecl()->isFixed()) {
1704 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1705 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1706 IsIntegralPromotion(From, Underlying, ToType);
1707 }
1708
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001709 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001710 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001711 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001712 return Context.hasSameUnqualifiedType(ToType,
1713 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001714 }
John McCall842aef82009-12-09 09:09:27 +00001715
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001716 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001717 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1718 // to an rvalue a prvalue of the first of the following types that can
1719 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001720 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001721 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001722 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001723 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001724 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001725 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001726 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001727 // Determine whether the type we're converting from is signed or
1728 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001729 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001730 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001731
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001732 // The types we'll try to promote to, in the appropriate
1733 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001734 QualType PromoteTypes[6] = {
1735 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001736 Context.LongTy, Context.UnsignedLongTy ,
1737 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001738 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001739 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001740 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1741 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001742 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001743 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1744 // We found the type that we can promote to. If this is the
1745 // type we wanted, we have a promotion. Otherwise, no
1746 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001747 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001748 }
1749 }
1750 }
1751
1752 // An rvalue for an integral bit-field (9.6) can be converted to an
1753 // rvalue of type int if int can represent all the values of the
1754 // bit-field; otherwise, it can be converted to unsigned int if
1755 // unsigned int can represent all the values of the bit-field. If
1756 // the bit-field is larger yet, no integral promotion applies to
1757 // it. If the bit-field has an enumerated type, it is treated as any
1758 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001759 // FIXME: We should delay checking of bit-fields until we actually perform the
1760 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001761 using llvm::APSInt;
1762 if (From)
1763 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001764 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001765 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001766 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1767 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1768 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Douglas Gregor86f19402008-12-20 23:49:58 +00001770 // Are we promoting to an int from a bitfield that fits in an int?
1771 if (BitWidth < ToSize ||
1772 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1773 return To->getKind() == BuiltinType::Int;
1774 }
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Douglas Gregor86f19402008-12-20 23:49:58 +00001776 // Are we promoting to an unsigned int from an unsigned bitfield
1777 // that fits into an unsigned int?
1778 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1779 return To->getKind() == BuiltinType::UInt;
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Douglas Gregor86f19402008-12-20 23:49:58 +00001782 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001783 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001786 // An rvalue of type bool can be converted to an rvalue of type int,
1787 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001789 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001790 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001791
1792 return false;
1793}
1794
1795/// IsFloatingPointPromotion - Determines whether the conversion from
1796/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1797/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001798bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001799 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1800 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001801 /// An rvalue of type float can be converted to an rvalue of type
1802 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001803 if (FromBuiltin->getKind() == BuiltinType::Float &&
1804 ToBuiltin->getKind() == BuiltinType::Double)
1805 return true;
1806
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001807 // C99 6.3.1.5p1:
1808 // When a float is promoted to double or long double, or a
1809 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001810 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001811 (FromBuiltin->getKind() == BuiltinType::Float ||
1812 FromBuiltin->getKind() == BuiltinType::Double) &&
1813 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1814 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001815
1816 // Half can be promoted to float.
1817 if (FromBuiltin->getKind() == BuiltinType::Half &&
1818 ToBuiltin->getKind() == BuiltinType::Float)
1819 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001820 }
1821
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001822 return false;
1823}
1824
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001825/// \brief Determine if a conversion is a complex promotion.
1826///
1827/// A complex promotion is defined as a complex -> complex conversion
1828/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001829/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001830bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001831 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001832 if (!FromComplex)
1833 return false;
1834
John McCall183700f2009-09-21 23:43:11 +00001835 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001836 if (!ToComplex)
1837 return false;
1838
1839 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001840 ToComplex->getElementType()) ||
1841 IsIntegralPromotion(0, FromComplex->getElementType(),
1842 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001843}
1844
Douglas Gregorcb7de522008-11-26 23:31:11 +00001845/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1846/// the pointer type FromPtr to a pointer to type ToPointee, with the
1847/// same type qualifiers as FromPtr has on its pointee type. ToType,
1848/// if non-empty, will be a pointer to ToType that may or may not have
1849/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001850///
Mike Stump1eb44332009-09-09 15:08:12 +00001851static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001852BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001853 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001854 ASTContext &Context,
1855 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001856 assert((FromPtr->getTypeClass() == Type::Pointer ||
1857 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1858 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001859
John McCallf85e1932011-06-15 23:02:42 +00001860 /// Conversions to 'id' subsume cv-qualifier conversions.
1861 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001862 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863
1864 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001865 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001866 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001867 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001868
John McCallf85e1932011-06-15 23:02:42 +00001869 if (StripObjCLifetime)
1870 Quals.removeObjCLifetime();
1871
Mike Stump1eb44332009-09-09 15:08:12 +00001872 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001873 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001874 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001875 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001876 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001877
1878 // Build a pointer to ToPointee. It has the right qualifiers
1879 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001880 if (isa<ObjCObjectPointerType>(ToType))
1881 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001882 return Context.getPointerType(ToPointee);
1883 }
1884
1885 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001886 QualType QualifiedCanonToPointee
1887 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001888
Douglas Gregorda80f742010-12-01 21:43:58 +00001889 if (isa<ObjCObjectPointerType>(ToType))
1890 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1891 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001892}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893
Mike Stump1eb44332009-09-09 15:08:12 +00001894static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001895 bool InOverloadResolution,
1896 ASTContext &Context) {
1897 // Handle value-dependent integral null pointer constants correctly.
1898 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1899 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001900 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001901 return !InOverloadResolution;
1902
Douglas Gregorce940492009-09-25 04:25:58 +00001903 return Expr->isNullPointerConstant(Context,
1904 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1905 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001906}
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001908/// IsPointerConversion - Determines whether the conversion of the
1909/// expression From, which has the (possibly adjusted) type FromType,
1910/// can be converted to the type ToType via a pointer conversion (C++
1911/// 4.10). If so, returns true and places the converted type (that
1912/// might differ from ToType in its cv-qualifiers at some level) into
1913/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001914///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001915/// This routine also supports conversions to and from block pointers
1916/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1917/// pointers to interfaces. FIXME: Once we've determined the
1918/// appropriate overloading rules for Objective-C, we may want to
1919/// split the Objective-C checks into a different routine; however,
1920/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001921/// conversions, so for now they live here. IncompatibleObjC will be
1922/// set if the conversion is an allowed Objective-C conversion that
1923/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001924bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001925 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001926 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001927 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001928 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001929 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1930 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001931 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001932
Mike Stump1eb44332009-09-09 15:08:12 +00001933 // Conversion from a null pointer constant to any Objective-C pointer type.
1934 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001935 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001936 ConvertedType = ToType;
1937 return true;
1938 }
1939
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001940 // Blocks: Block pointers can be converted to void*.
1941 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001942 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001943 ConvertedType = ToType;
1944 return true;
1945 }
1946 // Blocks: A null pointer constant can be converted to a block
1947 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001948 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001949 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001950 ConvertedType = ToType;
1951 return true;
1952 }
1953
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001954 // If the left-hand-side is nullptr_t, the right side can be a null
1955 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001956 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001957 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001958 ConvertedType = ToType;
1959 return true;
1960 }
1961
Ted Kremenek6217b802009-07-29 21:53:49 +00001962 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001963 if (!ToTypePtr)
1964 return false;
1965
1966 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001967 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001968 ConvertedType = ToType;
1969 return true;
1970 }
Sebastian Redl07779722008-10-31 14:43:28 +00001971
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001972 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001973 // , including objective-c pointers.
1974 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001975 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001976 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001977 ConvertedType = BuildSimilarlyQualifiedPointerType(
1978 FromType->getAs<ObjCObjectPointerType>(),
1979 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001980 ToType, Context);
1981 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001982 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001983 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001984 if (!FromTypePtr)
1985 return false;
1986
1987 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001988
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001989 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001990 // pointer conversion, so don't do all of the work below.
1991 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1992 return false;
1993
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001994 // An rvalue of type "pointer to cv T," where T is an object type,
1995 // can be converted to an rvalue of type "pointer to cv void" (C++
1996 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001997 if (FromPointeeType->isIncompleteOrObjectType() &&
1998 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001999 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002000 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002001 ToType, Context,
2002 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002003 return true;
2004 }
2005
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002006 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002007 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002008 ToPointeeType->isVoidType()) {
2009 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2010 ToPointeeType,
2011 ToType, Context);
2012 return true;
2013 }
2014
Douglas Gregorf9201e02009-02-11 23:02:49 +00002015 // When we're overloading in C, we allow a special kind of pointer
2016 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002017 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002018 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002020 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002021 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002022 return true;
2023 }
2024
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002025 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002026 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002027 // An rvalue of type "pointer to cv D," where D is a class type,
2028 // can be converted to an rvalue of type "pointer to cv B," where
2029 // B is a base class (clause 10) of D. If B is an inaccessible
2030 // (clause 11) or ambiguous (10.2) base class of D, a program that
2031 // necessitates this conversion is ill-formed. The result of the
2032 // conversion is a pointer to the base class sub-object of the
2033 // derived class object. The null pointer value is converted to
2034 // the null pointer value of the destination type.
2035 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002036 // Note that we do not check for ambiguity or inaccessibility
2037 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002038 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002039 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002040 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002041 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002042 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002043 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002044 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002045 ToType, Context);
2046 return true;
2047 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002048
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002049 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2050 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2052 ToPointeeType,
2053 ToType, Context);
2054 return true;
2055 }
2056
Douglas Gregorc7887512008-12-19 19:13:09 +00002057 return false;
2058}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002059
2060/// \brief Adopt the given qualifiers for the given type.
2061static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2062 Qualifiers TQs = T.getQualifiers();
2063
2064 // Check whether qualifiers already match.
2065 if (TQs == Qs)
2066 return T;
2067
2068 if (Qs.compatiblyIncludes(TQs))
2069 return Context.getQualifiedType(T, Qs);
2070
2071 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2072}
Douglas Gregorc7887512008-12-19 19:13:09 +00002073
2074/// isObjCPointerConversion - Determines whether this is an
2075/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2076/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002077bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002078 QualType& ConvertedType,
2079 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002080 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002081 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002082
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002083 // The set of qualifiers on the type we're converting from.
2084 Qualifiers FromQualifiers = FromType.getQualifiers();
2085
Steve Naroff14108da2009-07-10 23:34:53 +00002086 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002087 const ObjCObjectPointerType* ToObjCPtr =
2088 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002089 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002090 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002091
Steve Naroff14108da2009-07-10 23:34:53 +00002092 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002093 // If the pointee types are the same (ignoring qualifications),
2094 // then this is not a pointer conversion.
2095 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2096 FromObjCPtr->getPointeeType()))
2097 return false;
2098
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002099 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002100 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002101 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002102 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002103 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002104 return true;
2105 }
2106 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002107 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002108 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002109 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002110 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002111 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002112 return true;
2113 }
2114 // Objective C++: We're able to convert from a pointer to an
2115 // interface to a pointer to a different interface.
2116 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002117 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2118 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002119 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002120 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2121 FromObjCPtr->getPointeeType()))
2122 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002124 ToObjCPtr->getPointeeType(),
2125 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002126 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002127 return true;
2128 }
2129
2130 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2131 // Okay: this is some kind of implicit downcast of Objective-C
2132 // interfaces, which is permitted. However, we're going to
2133 // complain about it.
2134 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002136 ToObjCPtr->getPointeeType(),
2137 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002138 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002139 return true;
2140 }
Mike Stump1eb44332009-09-09 15:08:12 +00002141 }
Steve Naroff14108da2009-07-10 23:34:53 +00002142 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002143 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002144 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002145 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002147 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002148 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002149 // to a block pointer type.
2150 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002151 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002152 return true;
2153 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002154 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002155 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002156 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002157 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002158 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002159 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002160 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002161 return true;
2162 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002163 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002164 return false;
2165
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002166 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002167 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002168 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002169 else if (const BlockPointerType *FromBlockPtr =
2170 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002171 FromPointeeType = FromBlockPtr->getPointeeType();
2172 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002173 return false;
2174
Douglas Gregorc7887512008-12-19 19:13:09 +00002175 // If we have pointers to pointers, recursively check whether this
2176 // is an Objective-C conversion.
2177 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2178 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2179 IncompatibleObjC)) {
2180 // We always complain about this conversion.
2181 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002182 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002183 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002184 return true;
2185 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002186 // Allow conversion of pointee being objective-c pointer to another one;
2187 // as in I* to id.
2188 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2189 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2190 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2191 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002192
Douglas Gregorda80f742010-12-01 21:43:58 +00002193 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002194 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002195 return true;
2196 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002197
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002198 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002199 // differences in the argument and result types are in Objective-C
2200 // pointer conversions. If so, we permit the conversion (but
2201 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002202 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002203 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002204 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002205 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002206 if (FromFunctionType && ToFunctionType) {
2207 // If the function types are exactly the same, this isn't an
2208 // Objective-C pointer conversion.
2209 if (Context.getCanonicalType(FromPointeeType)
2210 == Context.getCanonicalType(ToPointeeType))
2211 return false;
2212
2213 // Perform the quick checks that will tell us whether these
2214 // function types are obviously different.
2215 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2216 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2217 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2218 return false;
2219
2220 bool HasObjCConversion = false;
2221 if (Context.getCanonicalType(FromFunctionType->getResultType())
2222 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2223 // Okay, the types match exactly. Nothing to do.
2224 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2225 ToFunctionType->getResultType(),
2226 ConvertedType, IncompatibleObjC)) {
2227 // Okay, we have an Objective-C pointer conversion.
2228 HasObjCConversion = true;
2229 } else {
2230 // Function types are too different. Abort.
2231 return false;
2232 }
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Douglas Gregorc7887512008-12-19 19:13:09 +00002234 // Check argument types.
2235 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2236 ArgIdx != NumArgs; ++ArgIdx) {
2237 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2238 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2239 if (Context.getCanonicalType(FromArgType)
2240 == Context.getCanonicalType(ToArgType)) {
2241 // Okay, the types match exactly. Nothing to do.
2242 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2243 ConvertedType, IncompatibleObjC)) {
2244 // Okay, we have an Objective-C pointer conversion.
2245 HasObjCConversion = true;
2246 } else {
2247 // Argument types are too different. Abort.
2248 return false;
2249 }
2250 }
2251
2252 if (HasObjCConversion) {
2253 // We had an Objective-C conversion. Allow this pointer
2254 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002255 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002256 IncompatibleObjC = true;
2257 return true;
2258 }
2259 }
2260
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002261 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002262}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263
John McCallf85e1932011-06-15 23:02:42 +00002264/// \brief Determine whether this is an Objective-C writeback conversion,
2265/// used for parameter passing when performing automatic reference counting.
2266///
2267/// \param FromType The type we're converting form.
2268///
2269/// \param ToType The type we're converting to.
2270///
2271/// \param ConvertedType The type that will be produced after applying
2272/// this conversion.
2273bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2274 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002275 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002276 Context.hasSameUnqualifiedType(FromType, ToType))
2277 return false;
2278
2279 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2280 QualType ToPointee;
2281 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2282 ToPointee = ToPointer->getPointeeType();
2283 else
2284 return false;
2285
2286 Qualifiers ToQuals = ToPointee.getQualifiers();
2287 if (!ToPointee->isObjCLifetimeType() ||
2288 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002289 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002290 return false;
2291
2292 // Argument must be a pointer to __strong to __weak.
2293 QualType FromPointee;
2294 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2295 FromPointee = FromPointer->getPointeeType();
2296 else
2297 return false;
2298
2299 Qualifiers FromQuals = FromPointee.getQualifiers();
2300 if (!FromPointee->isObjCLifetimeType() ||
2301 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2302 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2303 return false;
2304
2305 // Make sure that we have compatible qualifiers.
2306 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2307 if (!ToQuals.compatiblyIncludes(FromQuals))
2308 return false;
2309
2310 // Remove qualifiers from the pointee type we're converting from; they
2311 // aren't used in the compatibility check belong, and we'll be adding back
2312 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2313 FromPointee = FromPointee.getUnqualifiedType();
2314
2315 // The unqualified form of the pointee types must be compatible.
2316 ToPointee = ToPointee.getUnqualifiedType();
2317 bool IncompatibleObjC;
2318 if (Context.typesAreCompatible(FromPointee, ToPointee))
2319 FromPointee = ToPointee;
2320 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2321 IncompatibleObjC))
2322 return false;
2323
2324 /// \brief Construct the type we're converting to, which is a pointer to
2325 /// __autoreleasing pointee.
2326 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2327 ConvertedType = Context.getPointerType(FromPointee);
2328 return true;
2329}
2330
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002331bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2332 QualType& ConvertedType) {
2333 QualType ToPointeeType;
2334 if (const BlockPointerType *ToBlockPtr =
2335 ToType->getAs<BlockPointerType>())
2336 ToPointeeType = ToBlockPtr->getPointeeType();
2337 else
2338 return false;
2339
2340 QualType FromPointeeType;
2341 if (const BlockPointerType *FromBlockPtr =
2342 FromType->getAs<BlockPointerType>())
2343 FromPointeeType = FromBlockPtr->getPointeeType();
2344 else
2345 return false;
2346 // We have pointer to blocks, check whether the only
2347 // differences in the argument and result types are in Objective-C
2348 // pointer conversions. If so, we permit the conversion.
2349
2350 const FunctionProtoType *FromFunctionType
2351 = FromPointeeType->getAs<FunctionProtoType>();
2352 const FunctionProtoType *ToFunctionType
2353 = ToPointeeType->getAs<FunctionProtoType>();
2354
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002355 if (!FromFunctionType || !ToFunctionType)
2356 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002357
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002358 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002359 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002360
2361 // Perform the quick checks that will tell us whether these
2362 // function types are obviously different.
2363 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2364 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2365 return false;
2366
2367 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2368 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2369 if (FromEInfo != ToEInfo)
2370 return false;
2371
2372 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002373 if (Context.hasSameType(FromFunctionType->getResultType(),
2374 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002375 // Okay, the types match exactly. Nothing to do.
2376 } else {
2377 QualType RHS = FromFunctionType->getResultType();
2378 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002379 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002380 !RHS.hasQualifiers() && LHS.hasQualifiers())
2381 LHS = LHS.getUnqualifiedType();
2382
2383 if (Context.hasSameType(RHS,LHS)) {
2384 // OK exact match.
2385 } else if (isObjCPointerConversion(RHS, LHS,
2386 ConvertedType, IncompatibleObjC)) {
2387 if (IncompatibleObjC)
2388 return false;
2389 // Okay, we have an Objective-C pointer conversion.
2390 }
2391 else
2392 return false;
2393 }
2394
2395 // Check argument types.
2396 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2397 ArgIdx != NumArgs; ++ArgIdx) {
2398 IncompatibleObjC = false;
2399 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2400 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2401 if (Context.hasSameType(FromArgType, ToArgType)) {
2402 // Okay, the types match exactly. Nothing to do.
2403 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2404 ConvertedType, IncompatibleObjC)) {
2405 if (IncompatibleObjC)
2406 return false;
2407 // Okay, we have an Objective-C pointer conversion.
2408 } else
2409 // Argument types are too different. Abort.
2410 return false;
2411 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002412 if (LangOpts.ObjCAutoRefCount &&
2413 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2414 ToFunctionType))
2415 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002416
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002417 ConvertedType = ToType;
2418 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002419}
2420
Richard Trieu6efd4c52011-11-23 22:32:32 +00002421enum {
2422 ft_default,
2423 ft_different_class,
2424 ft_parameter_arity,
2425 ft_parameter_mismatch,
2426 ft_return_type,
2427 ft_qualifer_mismatch
2428};
2429
2430/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2431/// function types. Catches different number of parameter, mismatch in
2432/// parameter types, and different return types.
2433void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2434 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002435 // If either type is not valid, include no extra info.
2436 if (FromType.isNull() || ToType.isNull()) {
2437 PDiag << ft_default;
2438 return;
2439 }
2440
Richard Trieu6efd4c52011-11-23 22:32:32 +00002441 // Get the function type from the pointers.
2442 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2443 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2444 *ToMember = ToType->getAs<MemberPointerType>();
2445 if (FromMember->getClass() != ToMember->getClass()) {
2446 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2447 << QualType(FromMember->getClass(), 0);
2448 return;
2449 }
2450 FromType = FromMember->getPointeeType();
2451 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002452 }
2453
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002454 if (FromType->isPointerType())
2455 FromType = FromType->getPointeeType();
2456 if (ToType->isPointerType())
2457 ToType = ToType->getPointeeType();
2458
2459 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002460 FromType = FromType.getNonReferenceType();
2461 ToType = ToType.getNonReferenceType();
2462
Richard Trieu6efd4c52011-11-23 22:32:32 +00002463 // Don't print extra info for non-specialized template functions.
2464 if (FromType->isInstantiationDependentType() &&
2465 !FromType->getAs<TemplateSpecializationType>()) {
2466 PDiag << ft_default;
2467 return;
2468 }
2469
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002470 // No extra info for same types.
2471 if (Context.hasSameType(FromType, ToType)) {
2472 PDiag << ft_default;
2473 return;
2474 }
2475
Richard Trieu6efd4c52011-11-23 22:32:32 +00002476 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2477 *ToFunction = ToType->getAs<FunctionProtoType>();
2478
2479 // Both types need to be function types.
2480 if (!FromFunction || !ToFunction) {
2481 PDiag << ft_default;
2482 return;
2483 }
2484
2485 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2486 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2487 << FromFunction->getNumArgs();
2488 return;
2489 }
2490
2491 // Handle different parameter types.
2492 unsigned ArgPos;
2493 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2494 PDiag << ft_parameter_mismatch << ArgPos + 1
2495 << ToFunction->getArgType(ArgPos)
2496 << FromFunction->getArgType(ArgPos);
2497 return;
2498 }
2499
2500 // Handle different return type.
2501 if (!Context.hasSameType(FromFunction->getResultType(),
2502 ToFunction->getResultType())) {
2503 PDiag << ft_return_type << ToFunction->getResultType()
2504 << FromFunction->getResultType();
2505 return;
2506 }
2507
2508 unsigned FromQuals = FromFunction->getTypeQuals(),
2509 ToQuals = ToFunction->getTypeQuals();
2510 if (FromQuals != ToQuals) {
2511 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2512 return;
2513 }
2514
2515 // Unable to find a difference, so add no extra info.
2516 PDiag << ft_default;
2517}
2518
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002519/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002520/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002521/// they have same number of arguments. This routine assumes that Objective-C
2522/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002523/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002524/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002525bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002526 const FunctionProtoType *NewType,
2527 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002528 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002529 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2530 N = NewType->arg_type_begin(),
2531 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2532 if (!Context.hasSameType(*O, *N)) {
2533 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2534 return false;
2535 }
2536 }
2537 return true;
2538 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002539
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002540 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2541 N = NewType->arg_type_begin(),
2542 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2543 QualType ToType = (*O);
2544 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002545 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002546 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2547 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002548 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2549 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2550 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2551 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002552 continue;
2553 }
John McCallc12c5bb2010-05-15 11:32:37 +00002554 else if (const ObjCObjectPointerType *PTTo =
2555 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002556 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002557 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002558 if (Context.hasSameUnqualifiedType(
2559 PTTo->getObjectType()->getBaseType(),
2560 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002561 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002562 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002563 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002564 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002565 }
2566 }
2567 return true;
2568}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002569
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002570/// CheckPointerConversion - Check the pointer conversion from the
2571/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002572/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002573/// conversions for which IsPointerConversion has already returned
2574/// true. It returns true and produces a diagnostic if there was an
2575/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002576bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002577 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002578 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002579 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002580 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002581 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002582
John McCalldaa8e4e2010-11-15 09:13:47 +00002583 Kind = CK_BitCast;
2584
David Blaikie50800fc2012-08-08 17:33:31 +00002585 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2586 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2587 Expr::NPCK_ZeroExpression) {
2588 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2589 DiagRuntimeBehavior(From->getExprLoc(), From,
2590 PDiag(diag::warn_impcast_bool_to_null_pointer)
2591 << ToType << From->getSourceRange());
2592 else if (!isUnevaluatedContext())
2593 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2594 << ToType << From->getSourceRange();
2595 }
John McCall1d9b3b22011-09-09 05:25:32 +00002596 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2597 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002598 QualType FromPointeeType = FromPtrType->getPointeeType(),
2599 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002600
Douglas Gregor5fccd362010-03-03 23:55:11 +00002601 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2602 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002603 // We must have a derived-to-base conversion. Check an
2604 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002605 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2606 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002607 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002608 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002609 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002610
Anders Carlsson61faec12009-09-12 04:46:44 +00002611 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002612 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002613 }
2614 }
John McCall1d9b3b22011-09-09 05:25:32 +00002615 } else if (const ObjCObjectPointerType *ToPtrType =
2616 ToType->getAs<ObjCObjectPointerType>()) {
2617 if (const ObjCObjectPointerType *FromPtrType =
2618 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002619 // Objective-C++ conversions are always okay.
2620 // FIXME: We should have a different class of conversions for the
2621 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002622 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002623 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002624 } else if (FromType->isBlockPointerType()) {
2625 Kind = CK_BlockPointerToObjCPointerCast;
2626 } else {
2627 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002628 }
John McCall1d9b3b22011-09-09 05:25:32 +00002629 } else if (ToType->isBlockPointerType()) {
2630 if (!FromType->isBlockPointerType())
2631 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002632 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002633
2634 // We shouldn't fall into this case unless it's valid for other
2635 // reasons.
2636 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2637 Kind = CK_NullToPointer;
2638
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002639 return false;
2640}
2641
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002642/// IsMemberPointerConversion - Determines whether the conversion of the
2643/// expression From, which has the (possibly adjusted) type FromType, can be
2644/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2645/// If so, returns true and places the converted type (that might differ from
2646/// ToType in its cv-qualifiers at some level) into ConvertedType.
2647bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002648 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002649 bool InOverloadResolution,
2650 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002651 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002652 if (!ToTypePtr)
2653 return false;
2654
2655 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002656 if (From->isNullPointerConstant(Context,
2657 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2658 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002659 ConvertedType = ToType;
2660 return true;
2661 }
2662
2663 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002664 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002665 if (!FromTypePtr)
2666 return false;
2667
2668 // A pointer to member of B can be converted to a pointer to member of D,
2669 // where D is derived from B (C++ 4.11p2).
2670 QualType FromClass(FromTypePtr->getClass(), 0);
2671 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002672
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002673 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002674 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002675 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002676 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2677 ToClass.getTypePtr());
2678 return true;
2679 }
2680
2681 return false;
2682}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002683
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002684/// CheckMemberPointerConversion - Check the member pointer conversion from the
2685/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002686/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002687/// for which IsMemberPointerConversion has already returned true. It returns
2688/// true and produces a diagnostic if there was an error, or returns false
2689/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002690bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002691 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002692 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002693 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002694 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002695 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002696 if (!FromPtrType) {
2697 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002698 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002699 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002700 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002701 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002702 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002703 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002704
Ted Kremenek6217b802009-07-29 21:53:49 +00002705 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002706 assert(ToPtrType && "No member pointer cast has a target type "
2707 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002708
Sebastian Redl21593ac2009-01-28 18:33:18 +00002709 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2710 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002711
Sebastian Redl21593ac2009-01-28 18:33:18 +00002712 // FIXME: What about dependent types?
2713 assert(FromClass->isRecordType() && "Pointer into non-class.");
2714 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002715
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002716 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002717 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002718 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2719 assert(DerivationOkay &&
2720 "Should not have been called if derivation isn't OK.");
2721 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002722
Sebastian Redl21593ac2009-01-28 18:33:18 +00002723 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2724 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002725 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2726 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2727 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2728 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002729 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002730
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002731 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002732 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2733 << FromClass << ToClass << QualType(VBase, 0)
2734 << From->getSourceRange();
2735 return true;
2736 }
2737
John McCall6b2accb2010-02-10 09:31:12 +00002738 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002739 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2740 Paths.front(),
2741 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002742
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002743 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002744 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002745 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002746 return false;
2747}
2748
Douglas Gregor98cd5992008-10-21 23:43:52 +00002749/// IsQualificationConversion - Determines whether the conversion from
2750/// an rvalue of type FromType to ToType is a qualification conversion
2751/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002752///
2753/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2754/// when the qualification conversion involves a change in the Objective-C
2755/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002756bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002757Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002758 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002759 FromType = Context.getCanonicalType(FromType);
2760 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002761 ObjCLifetimeConversion = false;
2762
Douglas Gregor98cd5992008-10-21 23:43:52 +00002763 // If FromType and ToType are the same type, this is not a
2764 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002765 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002766 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002767
Douglas Gregor98cd5992008-10-21 23:43:52 +00002768 // (C++ 4.4p4):
2769 // A conversion can add cv-qualifiers at levels other than the first
2770 // in multi-level pointers, subject to the following rules: [...]
2771 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002772 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002773 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002774 // Within each iteration of the loop, we check the qualifiers to
2775 // determine if this still looks like a qualification
2776 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002777 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002778 // until there are no more pointers or pointers-to-members left to
2779 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002780 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002781
Douglas Gregor621c92a2011-04-25 18:40:17 +00002782 Qualifiers FromQuals = FromType.getQualifiers();
2783 Qualifiers ToQuals = ToType.getQualifiers();
2784
John McCallf85e1932011-06-15 23:02:42 +00002785 // Objective-C ARC:
2786 // Check Objective-C lifetime conversions.
2787 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2788 UnwrappedAnyPointer) {
2789 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2790 ObjCLifetimeConversion = true;
2791 FromQuals.removeObjCLifetime();
2792 ToQuals.removeObjCLifetime();
2793 } else {
2794 // Qualification conversions cannot cast between different
2795 // Objective-C lifetime qualifiers.
2796 return false;
2797 }
2798 }
2799
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002800 // Allow addition/removal of GC attributes but not changing GC attributes.
2801 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2802 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2803 FromQuals.removeObjCGCAttr();
2804 ToQuals.removeObjCGCAttr();
2805 }
2806
Douglas Gregor98cd5992008-10-21 23:43:52 +00002807 // -- for every j > 0, if const is in cv 1,j then const is in cv
2808 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002809 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002810 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Douglas Gregor98cd5992008-10-21 23:43:52 +00002812 // -- if the cv 1,j and cv 2,j are different, then const is in
2813 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002814 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002815 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002816 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Douglas Gregor98cd5992008-10-21 23:43:52 +00002818 // Keep track of whether all prior cv-qualifiers in the "to" type
2819 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002820 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002821 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002822 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002823
2824 // We are left with FromType and ToType being the pointee types
2825 // after unwrapping the original FromType and ToType the same number
2826 // of types. If we unwrapped any pointers, and if FromType and
2827 // ToType have the same unqualified type (since we checked
2828 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002829 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002830}
2831
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002832/// \brief - Determine whether this is a conversion from a scalar type to an
2833/// atomic type.
2834///
2835/// If successful, updates \c SCS's second and third steps in the conversion
2836/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002837static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2838 bool InOverloadResolution,
2839 StandardConversionSequence &SCS,
2840 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002841 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2842 if (!ToAtomic)
2843 return false;
2844
2845 StandardConversionSequence InnerSCS;
2846 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2847 InOverloadResolution, InnerSCS,
2848 CStyle, /*AllowObjCWritebackConversion=*/false))
2849 return false;
2850
2851 SCS.Second = InnerSCS.Second;
2852 SCS.setToType(1, InnerSCS.getToType(1));
2853 SCS.Third = InnerSCS.Third;
2854 SCS.QualificationIncludesObjCLifetime
2855 = InnerSCS.QualificationIncludesObjCLifetime;
2856 SCS.setToType(2, InnerSCS.getToType(2));
2857 return true;
2858}
2859
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002860static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2861 CXXConstructorDecl *Constructor,
2862 QualType Type) {
2863 const FunctionProtoType *CtorType =
2864 Constructor->getType()->getAs<FunctionProtoType>();
2865 if (CtorType->getNumArgs() > 0) {
2866 QualType FirstArg = CtorType->getArgType(0);
2867 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2868 return true;
2869 }
2870 return false;
2871}
2872
Sebastian Redl56a04282012-02-11 23:51:08 +00002873static OverloadingResult
2874IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2875 CXXRecordDecl *To,
2876 UserDefinedConversionSequence &User,
2877 OverloadCandidateSet &CandidateSet,
2878 bool AllowExplicit) {
2879 DeclContext::lookup_iterator Con, ConEnd;
2880 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2881 Con != ConEnd; ++Con) {
2882 NamedDecl *D = *Con;
2883 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2884
2885 // Find the constructor (which may be a template).
2886 CXXConstructorDecl *Constructor = 0;
2887 FunctionTemplateDecl *ConstructorTmpl
2888 = dyn_cast<FunctionTemplateDecl>(D);
2889 if (ConstructorTmpl)
2890 Constructor
2891 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2892 else
2893 Constructor = cast<CXXConstructorDecl>(D);
2894
2895 bool Usable = !Constructor->isInvalidDecl() &&
2896 S.isInitListConstructor(Constructor) &&
2897 (AllowExplicit || !Constructor->isExplicit());
2898 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002899 // If the first argument is (a reference to) the target type,
2900 // suppress conversions.
2901 bool SuppressUserConversions =
2902 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002903 if (ConstructorTmpl)
2904 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2905 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002906 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002907 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002908 else
2909 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002910 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002911 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002912 }
2913 }
2914
2915 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2916
2917 OverloadCandidateSet::iterator Best;
2918 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2919 case OR_Success: {
2920 // Record the standard conversion we used and the conversion function.
2921 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2922 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2923
2924 QualType ThisType = Constructor->getThisType(S.Context);
2925 // Initializer lists don't have conversions as such.
2926 User.Before.setAsIdentityConversion();
2927 User.HadMultipleCandidates = HadMultipleCandidates;
2928 User.ConversionFunction = Constructor;
2929 User.FoundConversionFunction = Best->FoundDecl;
2930 User.After.setAsIdentityConversion();
2931 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2932 User.After.setAllToTypes(ToType);
2933 return OR_Success;
2934 }
2935
2936 case OR_No_Viable_Function:
2937 return OR_No_Viable_Function;
2938 case OR_Deleted:
2939 return OR_Deleted;
2940 case OR_Ambiguous:
2941 return OR_Ambiguous;
2942 }
2943
2944 llvm_unreachable("Invalid OverloadResult!");
2945}
2946
Douglas Gregor734d9862009-01-30 23:27:23 +00002947/// Determines whether there is a user-defined conversion sequence
2948/// (C++ [over.ics.user]) that converts expression From to the type
2949/// ToType. If such a conversion exists, User will contain the
2950/// user-defined conversion sequence that performs such a conversion
2951/// and this routine will return true. Otherwise, this routine returns
2952/// false and User is unspecified.
2953///
Douglas Gregor734d9862009-01-30 23:27:23 +00002954/// \param AllowExplicit true if the conversion should consider C++0x
2955/// "explicit" conversion functions as well as non-explicit conversion
2956/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002957static OverloadingResult
2958IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002959 UserDefinedConversionSequence &User,
2960 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002961 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002962 // Whether we will only visit constructors.
2963 bool ConstructorsOnly = false;
2964
2965 // If the type we are conversion to is a class type, enumerate its
2966 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002967 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002968 // C++ [over.match.ctor]p1:
2969 // When objects of class type are direct-initialized (8.5), or
2970 // copy-initialized from an expression of the same or a
2971 // derived class type (8.5), overload resolution selects the
2972 // constructor. [...] For copy-initialization, the candidate
2973 // functions are all the converting constructors (12.3.1) of
2974 // that class. The argument list is the expression-list within
2975 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002976 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002977 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002978 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002979 ConstructorsOnly = true;
2980
Douglas Gregord10099e2012-05-04 16:32:21 +00002981 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002982 // RequireCompleteType may have returned true due to some invalid decl
2983 // during template instantiation, but ToType may be complete enough now
2984 // to try to recover.
2985 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002986 // We're not going to find any constructors.
2987 } else if (CXXRecordDecl *ToRecordDecl
2988 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002989
2990 Expr **Args = &From;
2991 unsigned NumArgs = 1;
2992 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002993 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002994 // But first, see if there is an init-list-contructor that will work.
2995 OverloadingResult Result = IsInitializerListConstructorConversion(
2996 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2997 if (Result != OR_No_Viable_Function)
2998 return Result;
2999 // Never mind.
3000 CandidateSet.clear();
3001
3002 // If we're list-initializing, we pass the individual elements as
3003 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003004 Args = InitList->getInits();
3005 NumArgs = InitList->getNumInits();
3006 ListInitializing = true;
3007 }
3008
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003009 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00003010 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003011 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003012 NamedDecl *D = *Con;
3013 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3014
Douglas Gregordec06662009-08-21 18:42:58 +00003015 // Find the constructor (which may be a template).
3016 CXXConstructorDecl *Constructor = 0;
3017 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003018 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003019 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003020 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003021 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3022 else
John McCall9aa472c2010-03-19 07:35:19 +00003023 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003024
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003025 bool Usable = !Constructor->isInvalidDecl();
3026 if (ListInitializing)
3027 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3028 else
3029 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3030 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003031 bool SuppressUserConversions = !ConstructorsOnly;
3032 if (SuppressUserConversions && ListInitializing) {
3033 SuppressUserConversions = false;
3034 if (NumArgs == 1) {
3035 // If the first argument is (a reference to) the target type,
3036 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003037 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3038 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003039 }
3040 }
Douglas Gregordec06662009-08-21 18:42:58 +00003041 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003042 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3043 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003044 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003045 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003046 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003047 // Allow one user-defined conversion when user specifies a
3048 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003049 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003050 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003051 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003052 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003053 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003054 }
3055 }
3056
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003057 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003058 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003059 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003060 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003061 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003062 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003063 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003064 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3065 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003066 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003067 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003068 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003069 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003070 DeclAccessPair FoundDecl = I.getPair();
3071 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003072 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3073 if (isa<UsingShadowDecl>(D))
3074 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3075
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003076 CXXConversionDecl *Conv;
3077 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003078 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3079 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003080 else
John McCall32daa422010-03-31 01:36:47 +00003081 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003082
3083 if (AllowExplicit || !Conv->isExplicit()) {
3084 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003085 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3086 ActingContext, From, ToType,
3087 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003088 else
John McCall120d63c2010-08-24 20:38:10 +00003089 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3090 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003091 }
3092 }
3093 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003094 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003095
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003096 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3097
Douglas Gregor60d62c22008-10-31 16:23:19 +00003098 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003099 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003100 case OR_Success:
3101 // Record the standard conversion we used and the conversion function.
3102 if (CXXConstructorDecl *Constructor
3103 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003104 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003105
John McCall120d63c2010-08-24 20:38:10 +00003106 // C++ [over.ics.user]p1:
3107 // If the user-defined conversion is specified by a
3108 // constructor (12.3.1), the initial standard conversion
3109 // sequence converts the source type to the type required by
3110 // the argument of the constructor.
3111 //
3112 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003113 if (isa<InitListExpr>(From)) {
3114 // Initializer lists don't have conversions as such.
3115 User.Before.setAsIdentityConversion();
3116 } else {
3117 if (Best->Conversions[0].isEllipsis())
3118 User.EllipsisConversion = true;
3119 else {
3120 User.Before = Best->Conversions[0].Standard;
3121 User.EllipsisConversion = false;
3122 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003123 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003124 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003125 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003126 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003127 User.After.setAsIdentityConversion();
3128 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3129 User.After.setAllToTypes(ToType);
3130 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003131 }
3132 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003133 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003134 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003135
John McCall120d63c2010-08-24 20:38:10 +00003136 // C++ [over.ics.user]p1:
3137 //
3138 // [...] If the user-defined conversion is specified by a
3139 // conversion function (12.3.2), the initial standard
3140 // conversion sequence converts the source type to the
3141 // implicit object parameter of the conversion function.
3142 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003143 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003144 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003145 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003146 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003147
John McCall120d63c2010-08-24 20:38:10 +00003148 // C++ [over.ics.user]p2:
3149 // The second standard conversion sequence converts the
3150 // result of the user-defined conversion to the target type
3151 // for the sequence. Since an implicit conversion sequence
3152 // is an initialization, the special rules for
3153 // initialization by user-defined conversion apply when
3154 // selecting the best user-defined conversion for a
3155 // user-defined conversion sequence (see 13.3.3 and
3156 // 13.3.3.1).
3157 User.After = Best->FinalConversion;
3158 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003159 }
David Blaikie7530c032012-01-17 06:56:22 +00003160 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003161
John McCall120d63c2010-08-24 20:38:10 +00003162 case OR_No_Viable_Function:
3163 return OR_No_Viable_Function;
3164 case OR_Deleted:
3165 // No conversion here! We're done.
3166 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003167
John McCall120d63c2010-08-24 20:38:10 +00003168 case OR_Ambiguous:
3169 return OR_Ambiguous;
3170 }
3171
David Blaikie7530c032012-01-17 06:56:22 +00003172 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003173}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003174
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003175bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003176Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003177 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003178 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003179 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003180 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003181 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003182 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003183 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003184 diag::err_typecheck_ambiguous_condition)
3185 << From->getType() << ToType << From->getSourceRange();
3186 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003187 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003188 diag::err_typecheck_nonviable_condition)
3189 << From->getType() << ToType << From->getSourceRange();
3190 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003191 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003192 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003194}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003195
Douglas Gregorb734e242012-02-22 17:32:19 +00003196/// \brief Compare the user-defined conversion functions or constructors
3197/// of two user-defined conversion sequences to determine whether any ordering
3198/// is possible.
3199static ImplicitConversionSequence::CompareKind
3200compareConversionFunctions(Sema &S,
3201 FunctionDecl *Function1,
3202 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003203 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003204 return ImplicitConversionSequence::Indistinguishable;
3205
3206 // Objective-C++:
3207 // If both conversion functions are implicitly-declared conversions from
3208 // a lambda closure type to a function pointer and a block pointer,
3209 // respectively, always prefer the conversion to a function pointer,
3210 // because the function pointer is more lightweight and is more likely
3211 // to keep code working.
3212 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3213 if (!Conv1)
3214 return ImplicitConversionSequence::Indistinguishable;
3215
3216 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3217 if (!Conv2)
3218 return ImplicitConversionSequence::Indistinguishable;
3219
3220 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3221 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3222 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3223 if (Block1 != Block2)
3224 return Block1? ImplicitConversionSequence::Worse
3225 : ImplicitConversionSequence::Better;
3226 }
3227
3228 return ImplicitConversionSequence::Indistinguishable;
3229}
3230
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003231/// CompareImplicitConversionSequences - Compare two implicit
3232/// conversion sequences to determine whether one is better than the
3233/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003234static ImplicitConversionSequence::CompareKind
3235CompareImplicitConversionSequences(Sema &S,
3236 const ImplicitConversionSequence& ICS1,
3237 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003238{
3239 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3240 // conversion sequences (as defined in 13.3.3.1)
3241 // -- a standard conversion sequence (13.3.3.1.1) is a better
3242 // conversion sequence than a user-defined conversion sequence or
3243 // an ellipsis conversion sequence, and
3244 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3245 // conversion sequence than an ellipsis conversion sequence
3246 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003247 //
John McCall1d318332010-01-12 00:44:57 +00003248 // C++0x [over.best.ics]p10:
3249 // For the purpose of ranking implicit conversion sequences as
3250 // described in 13.3.3.2, the ambiguous conversion sequence is
3251 // treated as a user-defined sequence that is indistinguishable
3252 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003253 if (ICS1.getKindRank() < ICS2.getKindRank())
3254 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003255 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003256 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003257
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003258 // The following checks require both conversion sequences to be of
3259 // the same kind.
3260 if (ICS1.getKind() != ICS2.getKind())
3261 return ImplicitConversionSequence::Indistinguishable;
3262
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003263 ImplicitConversionSequence::CompareKind Result =
3264 ImplicitConversionSequence::Indistinguishable;
3265
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003266 // Two implicit conversion sequences of the same form are
3267 // indistinguishable conversion sequences unless one of the
3268 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003269 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003270 Result = CompareStandardConversionSequences(S,
3271 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003272 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003273 // User-defined conversion sequence U1 is a better conversion
3274 // sequence than another user-defined conversion sequence U2 if
3275 // they contain the same user-defined conversion function or
3276 // constructor and if the second standard conversion sequence of
3277 // U1 is better than the second standard conversion sequence of
3278 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003279 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003280 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003281 Result = CompareStandardConversionSequences(S,
3282 ICS1.UserDefined.After,
3283 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003284 else
3285 Result = compareConversionFunctions(S,
3286 ICS1.UserDefined.ConversionFunction,
3287 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003288 }
3289
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003290 // List-initialization sequence L1 is a better conversion sequence than
3291 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3292 // for some X and L2 does not.
3293 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003294 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003295 ICS1.isListInitializationSequence() &&
3296 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003297 if (ICS1.isStdInitializerListElement() &&
3298 !ICS2.isStdInitializerListElement())
3299 return ImplicitConversionSequence::Better;
3300 if (!ICS1.isStdInitializerListElement() &&
3301 ICS2.isStdInitializerListElement())
3302 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003303 }
3304
3305 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003306}
3307
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003308static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3309 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3310 Qualifiers Quals;
3311 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003312 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003314
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003315 return Context.hasSameUnqualifiedType(T1, T2);
3316}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003317
Douglas Gregorad323a82010-01-27 03:51:04 +00003318// Per 13.3.3.2p3, compare the given standard conversion sequences to
3319// determine if one is a proper subset of the other.
3320static ImplicitConversionSequence::CompareKind
3321compareStandardConversionSubsets(ASTContext &Context,
3322 const StandardConversionSequence& SCS1,
3323 const StandardConversionSequence& SCS2) {
3324 ImplicitConversionSequence::CompareKind Result
3325 = ImplicitConversionSequence::Indistinguishable;
3326
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003328 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003329 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3330 return ImplicitConversionSequence::Better;
3331 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3332 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003333
Douglas Gregorad323a82010-01-27 03:51:04 +00003334 if (SCS1.Second != SCS2.Second) {
3335 if (SCS1.Second == ICK_Identity)
3336 Result = ImplicitConversionSequence::Better;
3337 else if (SCS2.Second == ICK_Identity)
3338 Result = ImplicitConversionSequence::Worse;
3339 else
3340 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003341 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003342 return ImplicitConversionSequence::Indistinguishable;
3343
3344 if (SCS1.Third == SCS2.Third) {
3345 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3346 : ImplicitConversionSequence::Indistinguishable;
3347 }
3348
3349 if (SCS1.Third == ICK_Identity)
3350 return Result == ImplicitConversionSequence::Worse
3351 ? ImplicitConversionSequence::Indistinguishable
3352 : ImplicitConversionSequence::Better;
3353
3354 if (SCS2.Third == ICK_Identity)
3355 return Result == ImplicitConversionSequence::Better
3356 ? ImplicitConversionSequence::Indistinguishable
3357 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358
Douglas Gregorad323a82010-01-27 03:51:04 +00003359 return ImplicitConversionSequence::Indistinguishable;
3360}
3361
Douglas Gregor440a4832011-01-26 14:52:12 +00003362/// \brief Determine whether one of the given reference bindings is better
3363/// than the other based on what kind of bindings they are.
3364static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3365 const StandardConversionSequence &SCS2) {
3366 // C++0x [over.ics.rank]p3b4:
3367 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3368 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003370 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003372 // reference*.
3373 //
3374 // FIXME: Rvalue references. We're going rogue with the above edits,
3375 // because the semantics in the current C++0x working paper (N3225 at the
3376 // time of this writing) break the standard definition of std::forward
3377 // and std::reference_wrapper when dealing with references to functions.
3378 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003379 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3380 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3381 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003382
Douglas Gregor440a4832011-01-26 14:52:12 +00003383 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3384 SCS2.IsLvalueReference) ||
3385 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3386 !SCS2.IsLvalueReference);
3387}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003389/// CompareStandardConversionSequences - Compare two standard
3390/// conversion sequences to determine whether one is better than the
3391/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003392static ImplicitConversionSequence::CompareKind
3393CompareStandardConversionSequences(Sema &S,
3394 const StandardConversionSequence& SCS1,
3395 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003396{
3397 // Standard conversion sequence S1 is a better conversion sequence
3398 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3399
3400 // -- S1 is a proper subsequence of S2 (comparing the conversion
3401 // sequences in the canonical form defined by 13.3.3.1.1,
3402 // excluding any Lvalue Transformation; the identity conversion
3403 // sequence is considered to be a subsequence of any
3404 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003405 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003406 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003407 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003408
3409 // -- the rank of S1 is better than the rank of S2 (by the rules
3410 // defined below), or, if not that,
3411 ImplicitConversionRank Rank1 = SCS1.getRank();
3412 ImplicitConversionRank Rank2 = SCS2.getRank();
3413 if (Rank1 < Rank2)
3414 return ImplicitConversionSequence::Better;
3415 else if (Rank2 < Rank1)
3416 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003417
Douglas Gregor57373262008-10-22 14:17:15 +00003418 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3419 // are indistinguishable unless one of the following rules
3420 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003421
Douglas Gregor57373262008-10-22 14:17:15 +00003422 // A conversion that is not a conversion of a pointer, or
3423 // pointer to member, to bool is better than another conversion
3424 // that is such a conversion.
3425 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3426 return SCS2.isPointerConversionToBool()
3427 ? ImplicitConversionSequence::Better
3428 : ImplicitConversionSequence::Worse;
3429
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003430 // C++ [over.ics.rank]p4b2:
3431 //
3432 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003433 // conversion of B* to A* is better than conversion of B* to
3434 // void*, and conversion of A* to void* is better than conversion
3435 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003436 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003437 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003438 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003439 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003440 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3441 // Exactly one of the conversion sequences is a conversion to
3442 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003443 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3444 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003445 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3446 // Neither conversion sequence converts to a void pointer; compare
3447 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003448 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003449 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003450 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003451 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3452 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003453 // Both conversion sequences are conversions to void
3454 // pointers. Compare the source types to determine if there's an
3455 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003456 QualType FromType1 = SCS1.getFromType();
3457 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003458
3459 // Adjust the types we're converting from via the array-to-pointer
3460 // conversion, if we need to.
3461 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003462 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003463 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003464 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003465
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003466 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3467 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003468
John McCall120d63c2010-08-24 20:38:10 +00003469 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003470 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003471 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003472 return ImplicitConversionSequence::Worse;
3473
3474 // Objective-C++: If one interface is more specific than the
3475 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003476 const ObjCObjectPointerType* FromObjCPtr1
3477 = FromType1->getAs<ObjCObjectPointerType>();
3478 const ObjCObjectPointerType* FromObjCPtr2
3479 = FromType2->getAs<ObjCObjectPointerType>();
3480 if (FromObjCPtr1 && FromObjCPtr2) {
3481 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3482 FromObjCPtr2);
3483 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3484 FromObjCPtr1);
3485 if (AssignLeft != AssignRight) {
3486 return AssignLeft? ImplicitConversionSequence::Better
3487 : ImplicitConversionSequence::Worse;
3488 }
Douglas Gregor01919692009-12-13 21:37:05 +00003489 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003490 }
Douglas Gregor57373262008-10-22 14:17:15 +00003491
3492 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3493 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003494 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003495 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003496 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003497
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003498 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003499 // Check for a better reference binding based on the kind of bindings.
3500 if (isBetterReferenceBindingKind(SCS1, SCS2))
3501 return ImplicitConversionSequence::Better;
3502 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3503 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003505 // C++ [over.ics.rank]p3b4:
3506 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3507 // which the references refer are the same type except for
3508 // top-level cv-qualifiers, and the type to which the reference
3509 // initialized by S2 refers is more cv-qualified than the type
3510 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003511 QualType T1 = SCS1.getToType(2);
3512 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003513 T1 = S.Context.getCanonicalType(T1);
3514 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003515 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003516 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3517 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003518 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003519 // Objective-C++ ARC: If the references refer to objects with different
3520 // lifetimes, prefer bindings that don't change lifetime.
3521 if (SCS1.ObjCLifetimeConversionBinding !=
3522 SCS2.ObjCLifetimeConversionBinding) {
3523 return SCS1.ObjCLifetimeConversionBinding
3524 ? ImplicitConversionSequence::Worse
3525 : ImplicitConversionSequence::Better;
3526 }
3527
Chandler Carruth6df868e2010-12-12 08:17:55 +00003528 // If the type is an array type, promote the element qualifiers to the
3529 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003530 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003531 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003532 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003533 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003534 if (T2.isMoreQualifiedThan(T1))
3535 return ImplicitConversionSequence::Better;
3536 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003537 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003538 }
3539 }
Douglas Gregor57373262008-10-22 14:17:15 +00003540
Francois Pichet1c98d622011-09-18 21:37:37 +00003541 // In Microsoft mode, prefer an integral conversion to a
3542 // floating-to-integral conversion if the integral conversion
3543 // is between types of the same size.
3544 // For example:
3545 // void f(float);
3546 // void f(int);
3547 // int main {
3548 // long a;
3549 // f(a);
3550 // }
3551 // Here, MSVC will call f(int) instead of generating a compile error
3552 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003553 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003554 SCS1.Second == ICK_Integral_Conversion &&
3555 SCS2.Second == ICK_Floating_Integral &&
3556 S.Context.getTypeSize(SCS1.getFromType()) ==
3557 S.Context.getTypeSize(SCS1.getToType(2)))
3558 return ImplicitConversionSequence::Better;
3559
Douglas Gregor57373262008-10-22 14:17:15 +00003560 return ImplicitConversionSequence::Indistinguishable;
3561}
3562
3563/// CompareQualificationConversions - Compares two standard conversion
3564/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003565/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3566ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003567CompareQualificationConversions(Sema &S,
3568 const StandardConversionSequence& SCS1,
3569 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003570 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003571 // -- S1 and S2 differ only in their qualification conversion and
3572 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3573 // cv-qualification signature of type T1 is a proper subset of
3574 // the cv-qualification signature of type T2, and S1 is not the
3575 // deprecated string literal array-to-pointer conversion (4.2).
3576 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3577 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3578 return ImplicitConversionSequence::Indistinguishable;
3579
3580 // FIXME: the example in the standard doesn't use a qualification
3581 // conversion (!)
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);
Douglas Gregor57373262008-10-22 14:17:15 +00003589
3590 // If the types are the same, we won't learn anything by unwrapped
3591 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003592 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003593 return ImplicitConversionSequence::Indistinguishable;
3594
Chandler Carruth28e318c2009-12-29 07:16:59 +00003595 // If the type is an array type, promote the element qualifiers to the type
3596 // for comparison.
3597 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003598 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003599 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003600 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003601
Mike Stump1eb44332009-09-09 15:08:12 +00003602 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003603 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003604
3605 // Objective-C++ ARC:
3606 // Prefer qualification conversions not involving a change in lifetime
3607 // to qualification conversions that do not change lifetime.
3608 if (SCS1.QualificationIncludesObjCLifetime !=
3609 SCS2.QualificationIncludesObjCLifetime) {
3610 Result = SCS1.QualificationIncludesObjCLifetime
3611 ? ImplicitConversionSequence::Worse
3612 : ImplicitConversionSequence::Better;
3613 }
3614
John McCall120d63c2010-08-24 20:38:10 +00003615 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003616 // Within each iteration of the loop, we check the qualifiers to
3617 // determine if this still looks like a qualification
3618 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003619 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003620 // until there are no more pointers or pointers-to-members left
3621 // to unwrap. This essentially mimics what
3622 // IsQualificationConversion does, but here we're checking for a
3623 // strict subset of qualifiers.
3624 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3625 // The qualifiers are the same, so this doesn't tell us anything
3626 // about how the sequences rank.
3627 ;
3628 else if (T2.isMoreQualifiedThan(T1)) {
3629 // T1 has fewer qualifiers, so it could be the better sequence.
3630 if (Result == ImplicitConversionSequence::Worse)
3631 // Neither has qualifiers that are a subset of the other's
3632 // qualifiers.
3633 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Douglas Gregor57373262008-10-22 14:17:15 +00003635 Result = ImplicitConversionSequence::Better;
3636 } else if (T1.isMoreQualifiedThan(T2)) {
3637 // T2 has fewer qualifiers, so it could be the better sequence.
3638 if (Result == ImplicitConversionSequence::Better)
3639 // Neither has qualifiers that are a subset of the other's
3640 // qualifiers.
3641 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Douglas Gregor57373262008-10-22 14:17:15 +00003643 Result = ImplicitConversionSequence::Worse;
3644 } else {
3645 // Qualifiers are disjoint.
3646 return ImplicitConversionSequence::Indistinguishable;
3647 }
3648
3649 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003650 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003651 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003652 }
3653
Douglas Gregor57373262008-10-22 14:17:15 +00003654 // Check that the winning standard conversion sequence isn't using
3655 // the deprecated string literal array to pointer conversion.
3656 switch (Result) {
3657 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003658 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003659 Result = ImplicitConversionSequence::Indistinguishable;
3660 break;
3661
3662 case ImplicitConversionSequence::Indistinguishable:
3663 break;
3664
3665 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003666 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003667 Result = ImplicitConversionSequence::Indistinguishable;
3668 break;
3669 }
3670
3671 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003672}
3673
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003674/// CompareDerivedToBaseConversions - Compares two standard conversion
3675/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003676/// various kinds of derived-to-base conversions (C++
3677/// [over.ics.rank]p4b3). As part of these checks, we also look at
3678/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003679ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003680CompareDerivedToBaseConversions(Sema &S,
3681 const StandardConversionSequence& SCS1,
3682 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003683 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003684 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003685 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003686 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003687
3688 // Adjust the types we're converting from via the array-to-pointer
3689 // conversion, if we need to.
3690 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003691 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003692 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003693 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003694
3695 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003696 FromType1 = S.Context.getCanonicalType(FromType1);
3697 ToType1 = S.Context.getCanonicalType(ToType1);
3698 FromType2 = S.Context.getCanonicalType(FromType2);
3699 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003700
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003701 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003702 //
3703 // If class B is derived directly or indirectly from class A and
3704 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003705 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003706 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003707 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003708 SCS2.Second == ICK_Pointer_Conversion &&
3709 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3710 FromType1->isPointerType() && FromType2->isPointerType() &&
3711 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003712 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003713 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003714 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003715 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003716 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003717 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003718 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003719 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003720
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003721 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003722 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003723 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003724 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003725 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726 return ImplicitConversionSequence::Worse;
3727 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003728
3729 // -- conversion of B* to A* is better than conversion of C* to A*,
3730 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003731 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003732 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003733 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003734 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003735 }
3736 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3737 SCS2.Second == ICK_Pointer_Conversion) {
3738 const ObjCObjectPointerType *FromPtr1
3739 = FromType1->getAs<ObjCObjectPointerType>();
3740 const ObjCObjectPointerType *FromPtr2
3741 = FromType2->getAs<ObjCObjectPointerType>();
3742 const ObjCObjectPointerType *ToPtr1
3743 = ToType1->getAs<ObjCObjectPointerType>();
3744 const ObjCObjectPointerType *ToPtr2
3745 = ToType2->getAs<ObjCObjectPointerType>();
3746
3747 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3748 // Apply the same conversion ranking rules for Objective-C pointer types
3749 // that we do for C++ pointers to class types. However, we employ the
3750 // Objective-C pseudo-subtyping relationship used for assignment of
3751 // Objective-C pointer types.
3752 bool FromAssignLeft
3753 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3754 bool FromAssignRight
3755 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3756 bool ToAssignLeft
3757 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3758 bool ToAssignRight
3759 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3760
3761 // A conversion to an a non-id object pointer type or qualified 'id'
3762 // type is better than a conversion to 'id'.
3763 if (ToPtr1->isObjCIdType() &&
3764 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3765 return ImplicitConversionSequence::Worse;
3766 if (ToPtr2->isObjCIdType() &&
3767 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3768 return ImplicitConversionSequence::Better;
3769
3770 // A conversion to a non-id object pointer type is better than a
3771 // conversion to a qualified 'id' type
3772 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3773 return ImplicitConversionSequence::Worse;
3774 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3775 return ImplicitConversionSequence::Better;
3776
3777 // A conversion to an a non-Class object pointer type or qualified 'Class'
3778 // type is better than a conversion to 'Class'.
3779 if (ToPtr1->isObjCClassType() &&
3780 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3781 return ImplicitConversionSequence::Worse;
3782 if (ToPtr2->isObjCClassType() &&
3783 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3784 return ImplicitConversionSequence::Better;
3785
3786 // A conversion to a non-Class object pointer type is better than a
3787 // conversion to a qualified 'Class' type.
3788 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3789 return ImplicitConversionSequence::Worse;
3790 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3791 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Douglas Gregor395cc372011-01-31 18:51:41 +00003793 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3794 if (S.Context.hasSameType(FromType1, FromType2) &&
3795 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3796 (ToAssignLeft != ToAssignRight))
3797 return ToAssignLeft? ImplicitConversionSequence::Worse
3798 : ImplicitConversionSequence::Better;
3799
3800 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3801 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3802 (FromAssignLeft != FromAssignRight))
3803 return FromAssignLeft? ImplicitConversionSequence::Better
3804 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003805 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003806 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003807
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003808 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003809 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3810 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3811 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003812 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003813 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003815 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003817 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003819 ToType2->getAs<MemberPointerType>();
3820 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3821 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3822 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3823 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3824 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3825 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3826 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3827 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003828 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003829 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003830 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003831 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003832 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003833 return ImplicitConversionSequence::Better;
3834 }
3835 // conversion of B::* to C::* is better than conversion of A::* to C::*
3836 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003837 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003838 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003839 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003840 return ImplicitConversionSequence::Worse;
3841 }
3842 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003843
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003844 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003845 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003846 // -- binding of an expression of type C to a reference of type
3847 // B& is better than binding an expression of type C to a
3848 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003849 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3850 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3851 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003852 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003853 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003854 return ImplicitConversionSequence::Worse;
3855 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003856
Douglas Gregor225c41e2008-11-03 19:09:14 +00003857 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003858 // -- binding of an expression of type B to a reference of type
3859 // A& is better than binding an expression of type C to a
3860 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003861 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3862 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3863 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003864 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003865 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003866 return ImplicitConversionSequence::Worse;
3867 }
3868 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003869
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003870 return ImplicitConversionSequence::Indistinguishable;
3871}
3872
Douglas Gregorabe183d2010-04-13 16:31:36 +00003873/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3874/// determine whether they are reference-related,
3875/// reference-compatible, reference-compatible with added
3876/// qualification, or incompatible, for use in C++ initialization by
3877/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3878/// type, and the first type (T1) is the pointee type of the reference
3879/// type being initialized.
3880Sema::ReferenceCompareResult
3881Sema::CompareReferenceRelationship(SourceLocation Loc,
3882 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003883 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003884 bool &ObjCConversion,
3885 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003886 assert(!OrigT1->isReferenceType() &&
3887 "T1 must be the pointee type of the reference type");
3888 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3889
3890 QualType T1 = Context.getCanonicalType(OrigT1);
3891 QualType T2 = Context.getCanonicalType(OrigT2);
3892 Qualifiers T1Quals, T2Quals;
3893 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3894 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3895
3896 // C++ [dcl.init.ref]p4:
3897 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3898 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3899 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003900 DerivedToBase = false;
3901 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003902 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003903 if (UnqualT1 == UnqualT2) {
3904 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003905 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003906 IsDerivedFrom(UnqualT2, UnqualT1))
3907 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003908 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3909 UnqualT2->isObjCObjectOrInterfaceType() &&
3910 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3911 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003912 else
3913 return Ref_Incompatible;
3914
3915 // At this point, we know that T1 and T2 are reference-related (at
3916 // least).
3917
3918 // If the type is an array type, promote the element qualifiers to the type
3919 // for comparison.
3920 if (isa<ArrayType>(T1) && T1Quals)
3921 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3922 if (isa<ArrayType>(T2) && T2Quals)
3923 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3924
3925 // C++ [dcl.init.ref]p4:
3926 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3927 // reference-related to T2 and cv1 is the same cv-qualification
3928 // as, or greater cv-qualification than, cv2. For purposes of
3929 // overload resolution, cases for which cv1 is greater
3930 // cv-qualification than cv2 are identified as
3931 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003932 //
3933 // Note that we also require equivalence of Objective-C GC and address-space
3934 // qualifiers when performing these computations, so that e.g., an int in
3935 // address space 1 is not reference-compatible with an int in address
3936 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003937 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3938 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3939 T1Quals.removeObjCLifetime();
3940 T2Quals.removeObjCLifetime();
3941 ObjCLifetimeConversion = true;
3942 }
3943
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003944 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003945 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003946 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003947 return Ref_Compatible_With_Added_Qualification;
3948 else
3949 return Ref_Related;
3950}
3951
Douglas Gregor604eb652010-08-11 02:15:33 +00003952/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003953/// with DeclType. Return true if something definite is found.
3954static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003955FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3956 QualType DeclType, SourceLocation DeclLoc,
3957 Expr *Init, QualType T2, bool AllowRvalues,
3958 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003959 assert(T2->isRecordType() && "Can only find conversions of record types.");
3960 CXXRecordDecl *T2RecordDecl
3961 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3962
3963 OverloadCandidateSet CandidateSet(DeclLoc);
3964 const UnresolvedSetImpl *Conversions
3965 = T2RecordDecl->getVisibleConversionFunctions();
3966 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3967 E = Conversions->end(); I != E; ++I) {
3968 NamedDecl *D = *I;
3969 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3970 if (isa<UsingShadowDecl>(D))
3971 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3972
3973 FunctionTemplateDecl *ConvTemplate
3974 = dyn_cast<FunctionTemplateDecl>(D);
3975 CXXConversionDecl *Conv;
3976 if (ConvTemplate)
3977 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3978 else
3979 Conv = cast<CXXConversionDecl>(D);
3980
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003981 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003982 // explicit conversions, skip it.
3983 if (!AllowExplicit && Conv->isExplicit())
3984 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003985
Douglas Gregor604eb652010-08-11 02:15:33 +00003986 if (AllowRvalues) {
3987 bool DerivedToBase = false;
3988 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003989 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003990
3991 // If we are initializing an rvalue reference, don't permit conversion
3992 // functions that return lvalues.
3993 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3994 const ReferenceType *RefType
3995 = Conv->getConversionType()->getAs<LValueReferenceType>();
3996 if (RefType && !RefType->getPointeeType()->isFunctionType())
3997 continue;
3998 }
3999
Douglas Gregor604eb652010-08-11 02:15:33 +00004000 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004001 S.CompareReferenceRelationship(
4002 DeclLoc,
4003 Conv->getConversionType().getNonReferenceType()
4004 .getUnqualifiedType(),
4005 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004006 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004007 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004008 continue;
4009 } else {
4010 // If the conversion function doesn't return a reference type,
4011 // it can't be considered for this conversion. An rvalue reference
4012 // is only acceptable if its referencee is a function type.
4013
4014 const ReferenceType *RefType =
4015 Conv->getConversionType()->getAs<ReferenceType>();
4016 if (!RefType ||
4017 (!RefType->isLValueReferenceType() &&
4018 !RefType->getPointeeType()->isFunctionType()))
4019 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004020 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004021
Douglas Gregor604eb652010-08-11 02:15:33 +00004022 if (ConvTemplate)
4023 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004024 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004025 else
4026 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004027 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004028 }
4029
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004030 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4031
Sebastian Redl4680bf22010-06-30 18:13:39 +00004032 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004033 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004034 case OR_Success:
4035 // C++ [over.ics.ref]p1:
4036 //
4037 // [...] If the parameter binds directly to the result of
4038 // applying a conversion function to the argument
4039 // expression, the implicit conversion sequence is a
4040 // user-defined conversion sequence (13.3.3.1.2), with the
4041 // second standard conversion sequence either an identity
4042 // conversion or, if the conversion function returns an
4043 // entity of a type that is a derived class of the parameter
4044 // type, a derived-to-base Conversion.
4045 if (!Best->FinalConversion.DirectBinding)
4046 return false;
4047
Chandler Carruth25ca4212011-02-25 19:41:05 +00004048 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004049 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004050 ICS.setUserDefined();
4051 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4052 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004053 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004054 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004055 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004056 ICS.UserDefined.EllipsisConversion = false;
4057 assert(ICS.UserDefined.After.ReferenceBinding &&
4058 ICS.UserDefined.After.DirectBinding &&
4059 "Expected a direct reference binding!");
4060 return true;
4061
4062 case OR_Ambiguous:
4063 ICS.setAmbiguous();
4064 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4065 Cand != CandidateSet.end(); ++Cand)
4066 if (Cand->Viable)
4067 ICS.Ambiguous.addConversion(Cand->Function);
4068 return true;
4069
4070 case OR_No_Viable_Function:
4071 case OR_Deleted:
4072 // There was no suitable conversion, or we found a deleted
4073 // conversion; continue with other checks.
4074 return false;
4075 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004076
David Blaikie7530c032012-01-17 06:56:22 +00004077 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004078}
4079
Douglas Gregorabe183d2010-04-13 16:31:36 +00004080/// \brief Compute an implicit conversion sequence for reference
4081/// initialization.
4082static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004083TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004084 SourceLocation DeclLoc,
4085 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004086 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004087 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4088
4089 // Most paths end in a failed conversion.
4090 ImplicitConversionSequence ICS;
4091 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4092
4093 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4094 QualType T2 = Init->getType();
4095
4096 // If the initializer is the address of an overloaded function, try
4097 // to resolve the overloaded function. If all goes well, T2 is the
4098 // type of the resulting function.
4099 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4100 DeclAccessPair Found;
4101 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4102 false, Found))
4103 T2 = Fn->getType();
4104 }
4105
4106 // Compute some basic properties of the types and the initializer.
4107 bool isRValRef = DeclType->isRValueReferenceType();
4108 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004109 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004110 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004111 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004112 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004113 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004114 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004115
Douglas Gregorabe183d2010-04-13 16:31:36 +00004116
Sebastian Redl4680bf22010-06-30 18:13:39 +00004117 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004118 // A reference to type "cv1 T1" is initialized by an expression
4119 // of type "cv2 T2" as follows:
4120
Sebastian Redl4680bf22010-06-30 18:13:39 +00004121 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004122 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004123 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4124 // reference-compatible with "cv2 T2," or
4125 //
4126 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4127 if (InitCategory.isLValue() &&
4128 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004129 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004130 // When a parameter of reference type binds directly (8.5.3)
4131 // to an argument expression, the implicit conversion sequence
4132 // is the identity conversion, unless the argument expression
4133 // has a type that is a derived class of the parameter type,
4134 // in which case the implicit conversion sequence is a
4135 // derived-to-base Conversion (13.3.3.1).
4136 ICS.setStandard();
4137 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004138 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4139 : ObjCConversion? ICK_Compatible_Conversion
4140 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004141 ICS.Standard.Third = ICK_Identity;
4142 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4143 ICS.Standard.setToType(0, T2);
4144 ICS.Standard.setToType(1, T1);
4145 ICS.Standard.setToType(2, T1);
4146 ICS.Standard.ReferenceBinding = true;
4147 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004148 ICS.Standard.IsLvalueReference = !isRValRef;
4149 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4150 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004151 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004152 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004153 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004154
Sebastian Redl4680bf22010-06-30 18:13:39 +00004155 // Nothing more to do: the inaccessibility/ambiguity check for
4156 // derived-to-base conversions is suppressed when we're
4157 // computing the implicit conversion sequence (C++
4158 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004159 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004160 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004161
Sebastian Redl4680bf22010-06-30 18:13:39 +00004162 // -- has a class type (i.e., T2 is a class type), where T1 is
4163 // not reference-related to T2, and can be implicitly
4164 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4165 // is reference-compatible with "cv3 T3" 92) (this
4166 // conversion is selected by enumerating the applicable
4167 // conversion functions (13.3.1.6) and choosing the best
4168 // one through overload resolution (13.3)),
4169 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004170 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004171 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004172 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4173 Init, T2, /*AllowRvalues=*/false,
4174 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004175 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004176 }
4177 }
4178
Sebastian Redl4680bf22010-06-30 18:13:39 +00004179 // -- Otherwise, the reference shall be an lvalue reference to a
4180 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004181 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004182 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004183 // We actually handle one oddity of C++ [over.ics.ref] at this
4184 // point, which is that, due to p2 (which short-circuits reference
4185 // binding by only attempting a simple conversion for non-direct
4186 // bindings) and p3's strange wording, we allow a const volatile
4187 // reference to bind to an rvalue. Hence the check for the presence
4188 // of "const" rather than checking for "const" being the only
4189 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004190 // This is also the point where rvalue references and lvalue inits no longer
4191 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004192 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004193 return ICS;
4194
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004195 // -- If the initializer expression
4196 //
4197 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004198 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004199 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4200 (InitCategory.isXValue() ||
4201 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4202 (InitCategory.isLValue() && T2->isFunctionType()))) {
4203 ICS.setStandard();
4204 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004205 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004206 : ObjCConversion? ICK_Compatible_Conversion
4207 : ICK_Identity;
4208 ICS.Standard.Third = ICK_Identity;
4209 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4210 ICS.Standard.setToType(0, T2);
4211 ICS.Standard.setToType(1, T1);
4212 ICS.Standard.setToType(2, T1);
4213 ICS.Standard.ReferenceBinding = true;
4214 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4215 // binding unless we're binding to a class prvalue.
4216 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4217 // allow the use of rvalue references in C++98/03 for the benefit of
4218 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004219 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004220 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004221 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004222 ICS.Standard.IsLvalueReference = !isRValRef;
4223 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004224 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004225 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004226 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004227 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004228 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004229 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004230
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004231 // -- has a class type (i.e., T2 is a class type), where T1 is not
4232 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004233 // an xvalue, class prvalue, or function lvalue of type
4234 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004235 // "cv3 T3",
4236 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004238 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004240 // class subobject).
4241 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004242 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004243 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4244 Init, T2, /*AllowRvalues=*/true,
4245 AllowExplicit)) {
4246 // In the second case, if the reference is an rvalue reference
4247 // and the second standard conversion sequence of the
4248 // user-defined conversion sequence includes an lvalue-to-rvalue
4249 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004250 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004251 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4252 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4253
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004254 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004256
Douglas Gregorabe183d2010-04-13 16:31:36 +00004257 // -- Otherwise, a temporary of type "cv1 T1" is created and
4258 // initialized from the initializer expression using the
4259 // rules for a non-reference copy initialization (8.5). The
4260 // reference is then bound to the temporary. If T1 is
4261 // reference-related to T2, cv1 must be the same
4262 // cv-qualification as, or greater cv-qualification than,
4263 // cv2; otherwise, the program is ill-formed.
4264 if (RefRelationship == Sema::Ref_Related) {
4265 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4266 // we would be reference-compatible or reference-compatible with
4267 // added qualification. But that wasn't the case, so the reference
4268 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004269 //
4270 // Note that we only want to check address spaces and cvr-qualifiers here.
4271 // ObjC GC and lifetime qualifiers aren't important.
4272 Qualifiers T1Quals = T1.getQualifiers();
4273 Qualifiers T2Quals = T2.getQualifiers();
4274 T1Quals.removeObjCGCAttr();
4275 T1Quals.removeObjCLifetime();
4276 T2Quals.removeObjCGCAttr();
4277 T2Quals.removeObjCLifetime();
4278 if (!T1Quals.compatiblyIncludes(T2Quals))
4279 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004280 }
4281
4282 // If at least one of the types is a class type, the types are not
4283 // related, and we aren't allowed any user conversions, the
4284 // reference binding fails. This case is important for breaking
4285 // recursion, since TryImplicitConversion below will attempt to
4286 // create a temporary through the use of a copy constructor.
4287 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4288 (T1->isRecordType() || T2->isRecordType()))
4289 return ICS;
4290
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004291 // If T1 is reference-related to T2 and the reference is an rvalue
4292 // reference, the initializer expression shall not be an lvalue.
4293 if (RefRelationship >= Sema::Ref_Related &&
4294 isRValRef && Init->Classify(S.Context).isLValue())
4295 return ICS;
4296
Douglas Gregorabe183d2010-04-13 16:31:36 +00004297 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004298 // When a parameter of reference type is not bound directly to
4299 // an argument expression, the conversion sequence is the one
4300 // required to convert the argument expression to the
4301 // underlying type of the reference according to
4302 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4303 // to copy-initializing a temporary of the underlying type with
4304 // the argument expression. Any difference in top-level
4305 // cv-qualification is subsumed by the initialization itself
4306 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004307 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4308 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004309 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004310 /*CStyle=*/false,
4311 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004312
4313 // Of course, that's still a reference binding.
4314 if (ICS.isStandard()) {
4315 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004316 ICS.Standard.IsLvalueReference = !isRValRef;
4317 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4318 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004319 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004320 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004321 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004322 // Don't allow rvalue references to bind to lvalues.
4323 if (DeclType->isRValueReferenceType()) {
4324 if (const ReferenceType *RefType
4325 = ICS.UserDefined.ConversionFunction->getResultType()
4326 ->getAs<LValueReferenceType>()) {
4327 if (!RefType->getPointeeType()->isFunctionType()) {
4328 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4329 DeclType);
4330 return ICS;
4331 }
4332 }
4333 }
4334
Douglas Gregorabe183d2010-04-13 16:31:36 +00004335 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004336 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4337 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4338 ICS.UserDefined.After.BindsToRvalue = true;
4339 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4340 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004341 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004342
Douglas Gregorabe183d2010-04-13 16:31:36 +00004343 return ICS;
4344}
4345
Sebastian Redl5405b812011-10-16 18:19:34 +00004346static ImplicitConversionSequence
4347TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4348 bool SuppressUserConversions,
4349 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004350 bool AllowObjCWritebackConversion,
4351 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004352
4353/// TryListConversion - Try to copy-initialize a value of type ToType from the
4354/// initializer list From.
4355static ImplicitConversionSequence
4356TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4357 bool SuppressUserConversions,
4358 bool InOverloadResolution,
4359 bool AllowObjCWritebackConversion) {
4360 // C++11 [over.ics.list]p1:
4361 // When an argument is an initializer list, it is not an expression and
4362 // special rules apply for converting it to a parameter type.
4363
4364 ImplicitConversionSequence Result;
4365 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004366 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004367
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004368 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004369 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004370 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004371 return Result;
4372
Sebastian Redl5405b812011-10-16 18:19:34 +00004373 // C++11 [over.ics.list]p2:
4374 // If the parameter type is std::initializer_list<X> or "array of X" and
4375 // all the elements can be implicitly converted to X, the implicit
4376 // conversion sequence is the worst conversion necessary to convert an
4377 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004378 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004379 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004380 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004381 X = S.Context.getBaseElementType(ToType);
4382 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004383 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004384 if (!X.isNull()) {
4385 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4386 Expr *Init = From->getInit(i);
4387 ImplicitConversionSequence ICS =
4388 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4389 InOverloadResolution,
4390 AllowObjCWritebackConversion);
4391 // If a single element isn't convertible, fail.
4392 if (ICS.isBad()) {
4393 Result = ICS;
4394 break;
4395 }
4396 // Otherwise, look for the worst conversion.
4397 if (Result.isBad() ||
4398 CompareImplicitConversionSequences(S, ICS, Result) ==
4399 ImplicitConversionSequence::Worse)
4400 Result = ICS;
4401 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004402
4403 // For an empty list, we won't have computed any conversion sequence.
4404 // Introduce the identity conversion sequence.
4405 if (From->getNumInits() == 0) {
4406 Result.setStandard();
4407 Result.Standard.setAsIdentityConversion();
4408 Result.Standard.setFromType(ToType);
4409 Result.Standard.setAllToTypes(ToType);
4410 }
4411
Sebastian Redlfe592282012-01-17 22:49:48 +00004412 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004413 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004414 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004415 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004416
4417 // C++11 [over.ics.list]p3:
4418 // Otherwise, if the parameter is a non-aggregate class X and overload
4419 // resolution chooses a single best constructor [...] the implicit
4420 // conversion sequence is a user-defined conversion sequence. If multiple
4421 // constructors are viable but none is better than the others, the
4422 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004423 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4424 // This function can deal with initializer lists.
4425 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4426 /*AllowExplicit=*/false,
4427 InOverloadResolution, /*CStyle=*/false,
4428 AllowObjCWritebackConversion);
4429 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004430 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004431 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004432
4433 // C++11 [over.ics.list]p4:
4434 // Otherwise, if the parameter has an aggregate type which can be
4435 // initialized from the initializer list [...] the implicit conversion
4436 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004437 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004438 // Type is an aggregate, argument is an init list. At this point it comes
4439 // down to checking whether the initialization works.
4440 // FIXME: Find out whether this parameter is consumed or not.
4441 InitializedEntity Entity =
4442 InitializedEntity::InitializeParameter(S.Context, ToType,
4443 /*Consumed=*/false);
4444 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4445 Result.setUserDefined();
4446 Result.UserDefined.Before.setAsIdentityConversion();
4447 // Initializer lists don't have a type.
4448 Result.UserDefined.Before.setFromType(QualType());
4449 Result.UserDefined.Before.setAllToTypes(QualType());
4450
4451 Result.UserDefined.After.setAsIdentityConversion();
4452 Result.UserDefined.After.setFromType(ToType);
4453 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004454 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004455 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004456 return Result;
4457 }
4458
4459 // C++11 [over.ics.list]p5:
4460 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004461 if (ToType->isReferenceType()) {
4462 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4463 // mention initializer lists in any way. So we go by what list-
4464 // initialization would do and try to extrapolate from that.
4465
4466 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4467
4468 // If the initializer list has a single element that is reference-related
4469 // to the parameter type, we initialize the reference from that.
4470 if (From->getNumInits() == 1) {
4471 Expr *Init = From->getInit(0);
4472
4473 QualType T2 = Init->getType();
4474
4475 // If the initializer is the address of an overloaded function, try
4476 // to resolve the overloaded function. If all goes well, T2 is the
4477 // type of the resulting function.
4478 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4479 DeclAccessPair Found;
4480 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4481 Init, ToType, false, Found))
4482 T2 = Fn->getType();
4483 }
4484
4485 // Compute some basic properties of the types and the initializer.
4486 bool dummy1 = false;
4487 bool dummy2 = false;
4488 bool dummy3 = false;
4489 Sema::ReferenceCompareResult RefRelationship
4490 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4491 dummy2, dummy3);
4492
4493 if (RefRelationship >= Sema::Ref_Related)
4494 return TryReferenceInit(S, Init, ToType,
4495 /*FIXME:*/From->getLocStart(),
4496 SuppressUserConversions,
4497 /*AllowExplicit=*/false);
4498 }
4499
4500 // Otherwise, we bind the reference to a temporary created from the
4501 // initializer list.
4502 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4503 InOverloadResolution,
4504 AllowObjCWritebackConversion);
4505 if (Result.isFailure())
4506 return Result;
4507 assert(!Result.isEllipsis() &&
4508 "Sub-initialization cannot result in ellipsis conversion.");
4509
4510 // Can we even bind to a temporary?
4511 if (ToType->isRValueReferenceType() ||
4512 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4513 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4514 Result.UserDefined.After;
4515 SCS.ReferenceBinding = true;
4516 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4517 SCS.BindsToRvalue = true;
4518 SCS.BindsToFunctionLvalue = false;
4519 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4520 SCS.ObjCLifetimeConversionBinding = false;
4521 } else
4522 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4523 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004524 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004525 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004526
4527 // C++11 [over.ics.list]p6:
4528 // Otherwise, if the parameter type is not a class:
4529 if (!ToType->isRecordType()) {
4530 // - if the initializer list has one element, the implicit conversion
4531 // sequence is the one required to convert the element to the
4532 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004533 unsigned NumInits = From->getNumInits();
4534 if (NumInits == 1)
4535 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4536 SuppressUserConversions,
4537 InOverloadResolution,
4538 AllowObjCWritebackConversion);
4539 // - if the initializer list has no elements, the implicit conversion
4540 // sequence is the identity conversion.
4541 else if (NumInits == 0) {
4542 Result.setStandard();
4543 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004544 Result.Standard.setFromType(ToType);
4545 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004546 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004547 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004548 return Result;
4549 }
4550
4551 // C++11 [over.ics.list]p7:
4552 // In all cases other than those enumerated above, no conversion is possible
4553 return Result;
4554}
4555
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004556/// TryCopyInitialization - Try to copy-initialize a value of type
4557/// ToType from the expression From. Return the implicit conversion
4558/// sequence required to pass this argument, which may be a bad
4559/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004560/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004561/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004562static ImplicitConversionSequence
4563TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004564 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004565 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004566 bool AllowObjCWritebackConversion,
4567 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004568 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4569 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4570 InOverloadResolution,AllowObjCWritebackConversion);
4571
Douglas Gregorabe183d2010-04-13 16:31:36 +00004572 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004573 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004574 /*FIXME:*/From->getLocStart(),
4575 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004576 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004577
John McCall120d63c2010-08-24 20:38:10 +00004578 return TryImplicitConversion(S, From, ToType,
4579 SuppressUserConversions,
4580 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004581 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004582 /*CStyle=*/false,
4583 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004584}
4585
Anna Zaksf3546ee2011-07-28 19:46:48 +00004586static bool TryCopyInitialization(const CanQualType FromQTy,
4587 const CanQualType ToQTy,
4588 Sema &S,
4589 SourceLocation Loc,
4590 ExprValueKind FromVK) {
4591 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4592 ImplicitConversionSequence ICS =
4593 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4594
4595 return !ICS.isBad();
4596}
4597
Douglas Gregor96176b32008-11-18 23:14:02 +00004598/// TryObjectArgumentInitialization - Try to initialize the object
4599/// parameter of the given member function (@c Method) from the
4600/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004601static ImplicitConversionSequence
4602TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004603 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004604 CXXMethodDecl *Method,
4605 CXXRecordDecl *ActingContext) {
4606 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004607 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4608 // const volatile object.
4609 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4610 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004611 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004612
4613 // Set up the conversion sequence as a "bad" conversion, to allow us
4614 // to exit early.
4615 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004616
4617 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004618 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004619 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004620 FromType = PT->getPointeeType();
4621
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004622 // When we had a pointer, it's implicitly dereferenced, so we
4623 // better have an lvalue.
4624 assert(FromClassification.isLValue());
4625 }
4626
Anders Carlssona552f7c2009-05-01 18:34:30 +00004627 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004628
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004629 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004630 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004631 // parameter is
4632 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004633 // - "lvalue reference to cv X" for functions declared without a
4634 // ref-qualifier or with the & ref-qualifier
4635 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004636 // ref-qualifier
4637 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004638 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004639 // cv-qualification on the member function declaration.
4640 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004641 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004642 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004643 // (C++ [over.match.funcs]p5). We perform a simplified version of
4644 // reference binding here, that allows class rvalues to bind to
4645 // non-constant references.
4646
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004647 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004648 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004649 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004650 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004651 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004652 ICS.setBad(BadConversionSequence::bad_qualifiers,
4653 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004654 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004655 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004656
4657 // Check that we have either the same type or a derived type. It
4658 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004659 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004660 ImplicitConversionKind SecondKind;
4661 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4662 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004663 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004664 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004665 else {
John McCallb1bdc622010-02-25 01:37:24 +00004666 ICS.setBad(BadConversionSequence::unrelated_class,
4667 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004668 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004669 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004670
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004671 // Check the ref-qualifier.
4672 switch (Method->getRefQualifier()) {
4673 case RQ_None:
4674 // Do nothing; we don't care about lvalueness or rvalueness.
4675 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004676
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004677 case RQ_LValue:
4678 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4679 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004681 ImplicitParamType);
4682 return ICS;
4683 }
4684 break;
4685
4686 case RQ_RValue:
4687 if (!FromClassification.isRValue()) {
4688 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004689 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004690 ImplicitParamType);
4691 return ICS;
4692 }
4693 break;
4694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004695
Douglas Gregor96176b32008-11-18 23:14:02 +00004696 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004697 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004698 ICS.Standard.setAsIdentityConversion();
4699 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004700 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004701 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004702 ICS.Standard.ReferenceBinding = true;
4703 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004704 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004705 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004706 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4707 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4708 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004709 return ICS;
4710}
4711
4712/// PerformObjectArgumentInitialization - Perform initialization of
4713/// the implicit object parameter for the given Method with the given
4714/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004715ExprResult
4716Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004718 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004719 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004720 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004721 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004722 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004724 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004725 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004726 FromRecordType = PT->getPointeeType();
4727 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004728 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004729 } else {
4730 FromRecordType = From->getType();
4731 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004732 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004733 }
4734
John McCall701c89e2009-12-03 04:06:58 +00004735 // Note that we always use the true parent context when performing
4736 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004737 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004738 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4739 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004740 if (ICS.isBad()) {
4741 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4742 Qualifiers FromQs = FromRecordType.getQualifiers();
4743 Qualifiers ToQs = DestType.getQualifiers();
4744 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4745 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004746 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004747 diag::err_member_function_call_bad_cvr)
4748 << Method->getDeclName() << FromRecordType << (CVR - 1)
4749 << From->getSourceRange();
4750 Diag(Method->getLocation(), diag::note_previous_decl)
4751 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004752 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004753 }
4754 }
4755
Daniel Dunbar96a00142012-03-09 18:35:03 +00004756 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004757 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004758 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004759 }
Mike Stump1eb44332009-09-09 15:08:12 +00004760
John Wiegley429bb272011-04-08 18:41:53 +00004761 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4762 ExprResult FromRes =
4763 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4764 if (FromRes.isInvalid())
4765 return ExprError();
4766 From = FromRes.take();
4767 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004768
Douglas Gregor5fccd362010-03-03 23:55:11 +00004769 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004770 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004771 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004772 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004773}
4774
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004775/// TryContextuallyConvertToBool - Attempt to contextually convert the
4776/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004777static ImplicitConversionSequence
4778TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004779 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004780 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004781 // FIXME: Are these flags correct?
4782 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004783 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004784 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004785 /*CStyle=*/false,
4786 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004787}
4788
4789/// PerformContextuallyConvertToBool - Perform a contextual conversion
4790/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004791ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004792 if (checkPlaceholderForOverload(*this, From))
4793 return ExprError();
4794
John McCall120d63c2010-08-24 20:38:10 +00004795 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004796 if (!ICS.isBad())
4797 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004798
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004799 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004800 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004801 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004802 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004803 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004804}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004805
Richard Smith8ef7b202012-01-18 23:55:52 +00004806/// Check that the specified conversion is permitted in a converted constant
4807/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4808/// is acceptable.
4809static bool CheckConvertedConstantConversions(Sema &S,
4810 StandardConversionSequence &SCS) {
4811 // Since we know that the target type is an integral or unscoped enumeration
4812 // type, most conversion kinds are impossible. All possible First and Third
4813 // conversions are fine.
4814 switch (SCS.Second) {
4815 case ICK_Identity:
4816 case ICK_Integral_Promotion:
4817 case ICK_Integral_Conversion:
4818 return true;
4819
4820 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004821 // Conversion from an integral or unscoped enumeration type to bool is
4822 // classified as ICK_Boolean_Conversion, but it's also an integral
4823 // conversion, so it's permitted in a converted constant expression.
4824 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4825 SCS.getToType(2)->isBooleanType();
4826
Richard Smith8ef7b202012-01-18 23:55:52 +00004827 case ICK_Floating_Integral:
4828 case ICK_Complex_Real:
4829 return false;
4830
4831 case ICK_Lvalue_To_Rvalue:
4832 case ICK_Array_To_Pointer:
4833 case ICK_Function_To_Pointer:
4834 case ICK_NoReturn_Adjustment:
4835 case ICK_Qualification:
4836 case ICK_Compatible_Conversion:
4837 case ICK_Vector_Conversion:
4838 case ICK_Vector_Splat:
4839 case ICK_Derived_To_Base:
4840 case ICK_Pointer_Conversion:
4841 case ICK_Pointer_Member:
4842 case ICK_Block_Pointer_Conversion:
4843 case ICK_Writeback_Conversion:
4844 case ICK_Floating_Promotion:
4845 case ICK_Complex_Promotion:
4846 case ICK_Complex_Conversion:
4847 case ICK_Floating_Conversion:
4848 case ICK_TransparentUnionConversion:
4849 llvm_unreachable("unexpected second conversion kind");
4850
4851 case ICK_Num_Conversion_Kinds:
4852 break;
4853 }
4854
4855 llvm_unreachable("unknown conversion kind");
4856}
4857
4858/// CheckConvertedConstantExpression - Check that the expression From is a
4859/// converted constant expression of type T, perform the conversion and produce
4860/// the converted expression, per C++11 [expr.const]p3.
4861ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4862 llvm::APSInt &Value,
4863 CCEKind CCE) {
4864 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4865 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4866
4867 if (checkPlaceholderForOverload(*this, From))
4868 return ExprError();
4869
4870 // C++11 [expr.const]p3 with proposed wording fixes:
4871 // A converted constant expression of type T is a core constant expression,
4872 // implicitly converted to a prvalue of type T, where the converted
4873 // expression is a literal constant expression and the implicit conversion
4874 // sequence contains only user-defined conversions, lvalue-to-rvalue
4875 // conversions, integral promotions, and integral conversions other than
4876 // narrowing conversions.
4877 ImplicitConversionSequence ICS =
4878 TryImplicitConversion(From, T,
4879 /*SuppressUserConversions=*/false,
4880 /*AllowExplicit=*/false,
4881 /*InOverloadResolution=*/false,
4882 /*CStyle=*/false,
4883 /*AllowObjcWritebackConversion=*/false);
4884 StandardConversionSequence *SCS = 0;
4885 switch (ICS.getKind()) {
4886 case ImplicitConversionSequence::StandardConversion:
4887 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004888 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004889 diag::err_typecheck_converted_constant_expression_disallowed)
4890 << From->getType() << From->getSourceRange() << T;
4891 SCS = &ICS.Standard;
4892 break;
4893 case ImplicitConversionSequence::UserDefinedConversion:
4894 // We are converting from class type to an integral or enumeration type, so
4895 // the Before sequence must be trivial.
4896 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004897 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004898 diag::err_typecheck_converted_constant_expression_disallowed)
4899 << From->getType() << From->getSourceRange() << T;
4900 SCS = &ICS.UserDefined.After;
4901 break;
4902 case ImplicitConversionSequence::AmbiguousConversion:
4903 case ImplicitConversionSequence::BadConversion:
4904 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004905 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004906 diag::err_typecheck_converted_constant_expression)
4907 << From->getType() << From->getSourceRange() << T;
4908 return ExprError();
4909
4910 case ImplicitConversionSequence::EllipsisConversion:
4911 llvm_unreachable("ellipsis conversion in converted constant expression");
4912 }
4913
4914 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4915 if (Result.isInvalid())
4916 return Result;
4917
4918 // Check for a narrowing implicit conversion.
4919 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004920 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004921 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4922 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004923 case NK_Variable_Narrowing:
4924 // Implicit conversion to a narrower type, and the value is not a constant
4925 // expression. We'll diagnose this in a moment.
4926 case NK_Not_Narrowing:
4927 break;
4928
4929 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004930 Diag(From->getLocStart(),
4931 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4932 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004933 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004934 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004935 break;
4936
4937 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004938 Diag(From->getLocStart(),
4939 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4940 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004941 << CCE << /*Constant*/0 << From->getType() << T;
4942 break;
4943 }
4944
4945 // Check the expression is a constant expression.
4946 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4947 Expr::EvalResult Eval;
4948 Eval.Diag = &Notes;
4949
4950 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4951 // The expression can't be folded, so we can't keep it at this position in
4952 // the AST.
4953 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004954 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004955 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004956
4957 if (Notes.empty()) {
4958 // It's a constant expression.
4959 return Result;
4960 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004961 }
4962
4963 // It's not a constant expression. Produce an appropriate diagnostic.
4964 if (Notes.size() == 1 &&
4965 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4966 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4967 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004968 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004969 << CCE << From->getSourceRange();
4970 for (unsigned I = 0; I < Notes.size(); ++I)
4971 Diag(Notes[I].first, Notes[I].second);
4972 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004973 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004974}
4975
John McCall0bcc9bc2011-09-09 06:11:02 +00004976/// dropPointerConversions - If the given standard conversion sequence
4977/// involves any pointer conversions, remove them. This may change
4978/// the result type of the conversion sequence.
4979static void dropPointerConversion(StandardConversionSequence &SCS) {
4980 if (SCS.Second == ICK_Pointer_Conversion) {
4981 SCS.Second = ICK_Identity;
4982 SCS.Third = ICK_Identity;
4983 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4984 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004985}
John McCall120d63c2010-08-24 20:38:10 +00004986
John McCall0bcc9bc2011-09-09 06:11:02 +00004987/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4988/// convert the expression From to an Objective-C pointer type.
4989static ImplicitConversionSequence
4990TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4991 // Do an implicit conversion to 'id'.
4992 QualType Ty = S.Context.getObjCIdType();
4993 ImplicitConversionSequence ICS
4994 = TryImplicitConversion(S, From, Ty,
4995 // FIXME: Are these flags correct?
4996 /*SuppressUserConversions=*/false,
4997 /*AllowExplicit=*/true,
4998 /*InOverloadResolution=*/false,
4999 /*CStyle=*/false,
5000 /*AllowObjCWritebackConversion=*/false);
5001
5002 // Strip off any final conversions to 'id'.
5003 switch (ICS.getKind()) {
5004 case ImplicitConversionSequence::BadConversion:
5005 case ImplicitConversionSequence::AmbiguousConversion:
5006 case ImplicitConversionSequence::EllipsisConversion:
5007 break;
5008
5009 case ImplicitConversionSequence::UserDefinedConversion:
5010 dropPointerConversion(ICS.UserDefined.After);
5011 break;
5012
5013 case ImplicitConversionSequence::StandardConversion:
5014 dropPointerConversion(ICS.Standard);
5015 break;
5016 }
5017
5018 return ICS;
5019}
5020
5021/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5022/// conversion of the expression From to an Objective-C pointer type.
5023ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005024 if (checkPlaceholderForOverload(*this, From))
5025 return ExprError();
5026
John McCallc12c5bb2010-05-15 11:32:37 +00005027 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005028 ImplicitConversionSequence ICS =
5029 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005030 if (!ICS.isBad())
5031 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005032 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005033}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005034
Richard Smithf39aec12012-02-04 07:07:42 +00005035/// Determine whether the provided type is an integral type, or an enumeration
5036/// type of a permitted flavor.
5037static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5038 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5039 : T->isIntegralOrUnscopedEnumerationType();
5040}
5041
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005042/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005043/// enumeration type.
5044///
5045/// This routine will attempt to convert an expression of class type to an
5046/// integral or enumeration type, if that class type only has a single
5047/// conversion to an integral or enumeration type.
5048///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005049/// \param Loc The source location of the construct that requires the
5050/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005051///
James Dennett40ae6662012-06-22 08:52:37 +00005052/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005053///
James Dennett40ae6662012-06-22 08:52:37 +00005054/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005055///
Richard Smithf39aec12012-02-04 07:07:42 +00005056/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5057/// enumerations should be considered.
5058///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005059/// \returns The expression, converted to an integral or enumeration type if
5060/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005061ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005062Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005063 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005064 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005065 // We can't perform any more checking for type-dependent expressions.
5066 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005067 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005068
Eli Friedmanceccab92012-01-26 00:26:18 +00005069 // Process placeholders immediately.
5070 if (From->hasPlaceholderType()) {
5071 ExprResult result = CheckPlaceholderExpr(From);
5072 if (result.isInvalid()) return result;
5073 From = result.take();
5074 }
5075
Douglas Gregorc30614b2010-06-29 23:17:37 +00005076 // If the expression already has integral or enumeration type, we're golden.
5077 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005078 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005079 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005080
5081 // FIXME: Check for missing '()' if T is a function type?
5082
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005083 // 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 +00005084 // expression of integral or enumeration type.
5085 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005086 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005087 if (!Diagnoser.Suppress)
5088 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005089 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005090 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091
Douglas Gregorc30614b2010-06-29 23:17:37 +00005092 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005093 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005094 ICEConvertDiagnoser &Diagnoser;
5095 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005096
Douglas Gregorab41fe92012-05-04 22:38:52 +00005097 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5098 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005099
5100 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005101 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005102 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005103 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005104
5105 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005106 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005107
Douglas Gregorc30614b2010-06-29 23:17:37 +00005108 // Look for a conversion to an integral or enumeration type.
5109 UnresolvedSet<4> ViableConversions;
5110 UnresolvedSet<4> ExplicitConversions;
5111 const UnresolvedSetImpl *Conversions
5112 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005113
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005114 bool HadMultipleCandidates = (Conversions->size() > 1);
5115
Douglas Gregorc30614b2010-06-29 23:17:37 +00005116 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005117 E = Conversions->end();
5118 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005119 ++I) {
5120 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005121 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5122 if (isIntegralOrEnumerationType(
5123 Conversion->getConversionType().getNonReferenceType(),
5124 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005125 if (Conversion->isExplicit())
5126 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5127 else
5128 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5129 }
Richard Smithf39aec12012-02-04 07:07:42 +00005130 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005132
Douglas Gregorc30614b2010-06-29 23:17:37 +00005133 switch (ViableConversions.size()) {
5134 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005135 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005136 DeclAccessPair Found = ExplicitConversions[0];
5137 CXXConversionDecl *Conversion
5138 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005139
Douglas Gregorc30614b2010-06-29 23:17:37 +00005140 // The user probably meant to invoke the given explicit
5141 // conversion; use it.
5142 QualType ConvTy
5143 = Conversion->getConversionType().getNonReferenceType();
5144 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005145 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005146
Douglas Gregorab41fe92012-05-04 22:38:52 +00005147 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005148 << FixItHint::CreateInsertion(From->getLocStart(),
5149 "static_cast<" + TypeStr + ">(")
5150 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5151 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005152 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005153
5154 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005155 // explicit conversion function.
5156 if (isSFINAEContext())
5157 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005158
Douglas Gregorc30614b2010-06-29 23:17:37 +00005159 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005160 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5161 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005162 if (Result.isInvalid())
5163 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005164 // Record usage of conversion in an implicit cast.
5165 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5166 CK_UserDefinedConversion,
5167 Result.get(), 0,
5168 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005170
Douglas Gregorc30614b2010-06-29 23:17:37 +00005171 // We'll complain below about a non-integral condition type.
5172 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005173
Douglas Gregorc30614b2010-06-29 23:17:37 +00005174 case 1: {
5175 // Apply this conversion.
5176 DeclAccessPair Found = ViableConversions[0];
5177 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005178
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005179 CXXConversionDecl *Conversion
5180 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5181 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005182 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005183 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005184 if (isSFINAEContext())
5185 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005186
Douglas Gregorab41fe92012-05-04 22:38:52 +00005187 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5188 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005189 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005190
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005191 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5192 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005193 if (Result.isInvalid())
5194 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005195 // Record usage of conversion in an implicit cast.
5196 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5197 CK_UserDefinedConversion,
5198 Result.get(), 0,
5199 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005200 break;
5201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005202
Douglas Gregorc30614b2010-06-29 23:17:37 +00005203 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005204 if (Diagnoser.Suppress)
5205 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005206
Douglas Gregorab41fe92012-05-04 22:38:52 +00005207 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005208 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5209 CXXConversionDecl *Conv
5210 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5211 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005212 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005213 }
John McCall9ae2f072010-08-23 23:25:46 +00005214 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005215 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005216
Richard Smith282e7e62012-02-04 09:53:13 +00005217 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005218 !Diagnoser.Suppress) {
5219 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5220 << From->getSourceRange();
5221 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005222
Eli Friedmanceccab92012-01-26 00:26:18 +00005223 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005224}
5225
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005226/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005227/// candidate functions, using the given function call arguments. If
5228/// @p SuppressUserConversions, then don't allow user-defined
5229/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005230///
James Dennett699c9042012-06-15 07:13:21 +00005231/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005232/// based on an incomplete set of function arguments. This feature is used by
5233/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005234void
5235Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005236 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005237 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005238 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005239 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005240 bool PartialOverloading,
5241 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005242 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005243 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005244 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005245 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005246 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005247
Douglas Gregor88a35142008-12-22 05:46:06 +00005248 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005249 if (!isa<CXXConstructorDecl>(Method)) {
5250 // If we get here, it's because we're calling a member function
5251 // that is named without a member access expression (e.g.,
5252 // "this->f") that was either written explicitly or created
5253 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005254 // function, e.g., X::f(). We use an empty type for the implied
5255 // object argument (C++ [over.call.func]p3), and the acting context
5256 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005257 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005259 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005260 return;
5261 }
5262 // We treat a constructor like a non-member function, since its object
5263 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005264 }
5265
Douglas Gregorfd476482009-11-13 23:59:09 +00005266 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005267 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005268
Douglas Gregor7edfb692009-11-23 12:27:39 +00005269 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005270 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005271
Douglas Gregor66724ea2009-11-14 01:20:54 +00005272 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5273 // C++ [class.copy]p3:
5274 // A member function template is never instantiated to perform the copy
5275 // of a class object to an object of its class type.
5276 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005277 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005278 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005279 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5280 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005281 return;
5282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005283
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005284 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005285 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005286 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005287 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005288 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005289 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005290 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005291 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005292
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005293 unsigned NumArgsInProto = Proto->getNumArgs();
5294
5295 // (C++ 13.3.2p2): A candidate function having fewer than m
5296 // parameters is viable only if it has an ellipsis in its parameter
5297 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005298 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005299 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005300 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005301 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005302 return;
5303 }
5304
5305 // (C++ 13.3.2p2): A candidate function having more than m parameters
5306 // is viable only if the (m+1)st parameter has a default argument
5307 // (8.3.6). For the purposes of overload resolution, the
5308 // parameter list is truncated on the right, so that there are
5309 // exactly m parameters.
5310 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005311 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005312 // Not enough arguments.
5313 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005314 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005315 return;
5316 }
5317
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005318 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005319 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005320 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5321 if (CheckCUDATarget(Caller, Function)) {
5322 Candidate.Viable = false;
5323 Candidate.FailureKind = ovl_fail_bad_target;
5324 return;
5325 }
5326
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005327 // Determine the implicit conversion sequences for each of the
5328 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005329 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005330 if (ArgIdx < NumArgsInProto) {
5331 // (C++ 13.3.2p3): for F to be a viable function, there shall
5332 // exist for each argument an implicit conversion sequence
5333 // (13.3.3.1) that converts that argument to the corresponding
5334 // parameter of F.
5335 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005336 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005337 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005338 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005339 /*InOverloadResolution=*/true,
5340 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005341 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005342 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005343 if (Candidate.Conversions[ArgIdx].isBad()) {
5344 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005345 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005346 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005347 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005348 } else {
5349 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5350 // argument for which there is no corresponding parameter is
5351 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005352 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005353 }
5354 }
5355}
5356
Douglas Gregor063daf62009-03-13 18:40:31 +00005357/// \brief Add all of the function declarations in the given function set to
5358/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005359void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005360 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005361 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005362 bool SuppressUserConversions,
5363 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005364 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005365 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5366 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005367 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005368 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005369 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005370 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005371 Args.slice(1), CandidateSet,
5372 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005373 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005374 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005375 SuppressUserConversions);
5376 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005377 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005378 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5379 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005380 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005381 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005382 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005383 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005384 Args[0]->Classify(Context), Args.slice(1),
5385 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005386 else
John McCall9aa472c2010-03-19 07:35:19 +00005387 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005388 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005389 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005390 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005391 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005392}
5393
John McCall314be4e2009-11-17 07:50:12 +00005394/// AddMethodCandidate - Adds a named decl (which is some kind of
5395/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005396void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005397 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005398 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005399 Expr **Args, unsigned NumArgs,
5400 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005401 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005402 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005403 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005404
5405 if (isa<UsingShadowDecl>(Decl))
5406 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005407
John McCall314be4e2009-11-17 07:50:12 +00005408 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5409 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5410 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005411 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5412 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005413 ObjectType, ObjectClassification,
5414 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005415 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005416 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005417 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005418 ObjectType, ObjectClassification,
5419 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005420 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005421 }
5422}
5423
Douglas Gregor96176b32008-11-18 23:14:02 +00005424/// AddMethodCandidate - Adds the given C++ member function to the set
5425/// of candidate functions, using the given function call arguments
5426/// and the object argument (@c Object). For example, in a call
5427/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5428/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5429/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005430/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005431void
John McCall9aa472c2010-03-19 07:35:19 +00005432Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005433 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005434 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005435 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005436 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005437 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005438 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005439 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005440 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005441 assert(!isa<CXXConstructorDecl>(Method) &&
5442 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005443
Douglas Gregor3f396022009-09-28 04:47:19 +00005444 if (!CandidateSet.isNewCandidate(Method))
5445 return;
5446
Douglas Gregor7edfb692009-11-23 12:27:39 +00005447 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005448 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005449
Douglas Gregor96176b32008-11-18 23:14:02 +00005450 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005451 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005452 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005453 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005454 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005455 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005456 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005457
5458 unsigned NumArgsInProto = Proto->getNumArgs();
5459
5460 // (C++ 13.3.2p2): A candidate function having fewer than m
5461 // parameters is viable only if it has an ellipsis in its parameter
5462 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005463 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005464 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005465 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005466 return;
5467 }
5468
5469 // (C++ 13.3.2p2): A candidate function having more than m parameters
5470 // is viable only if the (m+1)st parameter has a default argument
5471 // (8.3.6). For the purposes of overload resolution, the
5472 // parameter list is truncated on the right, so that there are
5473 // exactly m parameters.
5474 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005475 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005476 // Not enough arguments.
5477 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005478 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005479 return;
5480 }
5481
5482 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005483
John McCall701c89e2009-12-03 04:06:58 +00005484 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005485 // The implicit object argument is ignored.
5486 Candidate.IgnoreObjectArgument = true;
5487 else {
5488 // Determine the implicit conversion sequence for the object
5489 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005490 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005491 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5492 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005493 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005494 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005495 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005496 return;
5497 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005498 }
5499
5500 // Determine the implicit conversion sequences for each of the
5501 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005502 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005503 if (ArgIdx < NumArgsInProto) {
5504 // (C++ 13.3.2p3): for F to be a viable function, there shall
5505 // exist for each argument an implicit conversion sequence
5506 // (13.3.3.1) that converts that argument to the corresponding
5507 // parameter of F.
5508 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005509 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005510 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005511 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005512 /*InOverloadResolution=*/true,
5513 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005514 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005515 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005516 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005517 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005518 break;
5519 }
5520 } else {
5521 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5522 // argument for which there is no corresponding parameter is
5523 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005524 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005525 }
5526 }
5527}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005528
Douglas Gregor6b906862009-08-21 00:16:32 +00005529/// \brief Add a C++ member function template as a candidate to the candidate
5530/// set, using template argument deduction to produce an appropriate member
5531/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005532void
Douglas Gregor6b906862009-08-21 00:16:32 +00005533Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005534 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005535 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005536 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005537 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005538 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005539 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005540 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005541 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005542 if (!CandidateSet.isNewCandidate(MethodTmpl))
5543 return;
5544
Douglas Gregor6b906862009-08-21 00:16:32 +00005545 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005546 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005547 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005548 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005549 // candidate functions in the usual way.113) A given name can refer to one
5550 // or more function templates and also to a set of overloaded non-template
5551 // functions. In such a case, the candidate functions generated from each
5552 // function template are combined with the set of non-template candidate
5553 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005554 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005555 FunctionDecl *Specialization = 0;
5556 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005557 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5558 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005559 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005560 Candidate.FoundDecl = FoundDecl;
5561 Candidate.Function = MethodTmpl->getTemplatedDecl();
5562 Candidate.Viable = false;
5563 Candidate.FailureKind = ovl_fail_bad_deduction;
5564 Candidate.IsSurrogate = false;
5565 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005566 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005567 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005568 Info);
5569 return;
5570 }
Mike Stump1eb44332009-09-09 15:08:12 +00005571
Douglas Gregor6b906862009-08-21 00:16:32 +00005572 // Add the function template specialization produced by template argument
5573 // deduction as a candidate.
5574 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005575 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005576 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005577 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005578 ActingContext, ObjectType, ObjectClassification, Args,
5579 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005580}
5581
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005582/// \brief Add a C++ function template specialization as a candidate
5583/// in the candidate set, using template argument deduction to produce
5584/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005585void
Douglas Gregore53060f2009-06-25 22:08:12 +00005586Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005587 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005588 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005589 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005590 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005591 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005592 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5593 return;
5594
Douglas Gregore53060f2009-06-25 22:08:12 +00005595 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005596 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005597 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005598 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005599 // candidate functions in the usual way.113) A given name can refer to one
5600 // or more function templates and also to a set of overloaded non-template
5601 // functions. In such a case, the candidate functions generated from each
5602 // function template are combined with the set of non-template candidate
5603 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005604 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005605 FunctionDecl *Specialization = 0;
5606 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005607 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5608 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005609 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005610 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005611 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5612 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005613 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005614 Candidate.IsSurrogate = false;
5615 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005616 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005617 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005618 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005619 return;
5620 }
Mike Stump1eb44332009-09-09 15:08:12 +00005621
Douglas Gregore53060f2009-06-25 22:08:12 +00005622 // Add the function template specialization produced by template argument
5623 // deduction as a candidate.
5624 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005625 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005626 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005627}
Mike Stump1eb44332009-09-09 15:08:12 +00005628
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005629/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005630/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005631/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005632/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005633/// (which may or may not be the same type as the type that the
5634/// conversion function produces).
5635void
5636Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005637 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005638 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005639 Expr *From, QualType ToType,
5640 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005641 assert(!Conversion->getDescribedFunctionTemplate() &&
5642 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005643 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005644 if (!CandidateSet.isNewCandidate(Conversion))
5645 return;
5646
Douglas Gregor7edfb692009-11-23 12:27:39 +00005647 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005648 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005649
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005650 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005651 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005652 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005653 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005654 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005655 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005656 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005657 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005658 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005659 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005660 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005661
Douglas Gregorbca39322010-08-19 15:37:02 +00005662 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005663 // For conversion functions, the function is considered to be a member of
5664 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005665 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005666 //
5667 // Determine the implicit conversion sequence for the implicit
5668 // object parameter.
5669 QualType ImplicitParamType = From->getType();
5670 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5671 ImplicitParamType = FromPtrType->getPointeeType();
5672 CXXRecordDecl *ConversionContext
5673 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005674
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005675 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005676 = TryObjectArgumentInitialization(*this, From->getType(),
5677 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005678 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005679
John McCall1d318332010-01-12 00:44:57 +00005680 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005681 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005682 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005683 return;
5684 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005685
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005686 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005687 // derived to base as such conversions are given Conversion Rank. They only
5688 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5689 QualType FromCanon
5690 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5691 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5692 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5693 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005694 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005695 return;
5696 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005697
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005698 // To determine what the conversion from the result of calling the
5699 // conversion function to the type we're eventually trying to
5700 // convert to (ToType), we need to synthesize a call to the
5701 // conversion function and attempt copy initialization from it. This
5702 // makes sure that we get the right semantics with respect to
5703 // lvalues/rvalues and the type. Fortunately, we can allocate this
5704 // call on the stack and we don't need its arguments to be
5705 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005706 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005707 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005708 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5709 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005710 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005711 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005712
Richard Smith87c1f1f2011-07-13 22:53:21 +00005713 QualType ConversionType = Conversion->getConversionType();
5714 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005715 Candidate.Viable = false;
5716 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5717 return;
5718 }
5719
Richard Smith87c1f1f2011-07-13 22:53:21 +00005720 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005721
Mike Stump1eb44332009-09-09 15:08:12 +00005722 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005723 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5724 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005725 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005726 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005727 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005728 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005729 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005730 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005731 /*InOverloadResolution=*/false,
5732 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005733
John McCall1d318332010-01-12 00:44:57 +00005734 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005735 case ImplicitConversionSequence::StandardConversion:
5736 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005737
Douglas Gregorc520c842010-04-12 23:42:09 +00005738 // C++ [over.ics.user]p3:
5739 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005740 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005741 // shall have exact match rank.
5742 if (Conversion->getPrimaryTemplate() &&
5743 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5744 Candidate.Viable = false;
5745 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005747
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005748 // C++0x [dcl.init.ref]p5:
5749 // In the second case, if the reference is an rvalue reference and
5750 // the second standard conversion sequence of the user-defined
5751 // conversion sequence includes an lvalue-to-rvalue conversion, the
5752 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005753 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005754 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5755 Candidate.Viable = false;
5756 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5757 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005758 break;
5759
5760 case ImplicitConversionSequence::BadConversion:
5761 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005762 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005763 break;
5764
5765 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005766 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005767 "Can only end up with a standard conversion sequence or failure");
5768 }
5769}
5770
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005771/// \brief Adds a conversion function template specialization
5772/// candidate to the overload set, using template argument deduction
5773/// to deduce the template arguments of the conversion function
5774/// template from the type that we are converting to (C++
5775/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005776void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005777Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005778 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005779 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005780 Expr *From, QualType ToType,
5781 OverloadCandidateSet &CandidateSet) {
5782 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5783 "Only conversion function templates permitted here");
5784
Douglas Gregor3f396022009-09-28 04:47:19 +00005785 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5786 return;
5787
Craig Topper93e45992012-09-19 02:26:47 +00005788 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005789 CXXConversionDecl *Specialization = 0;
5790 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005791 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005792 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005793 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005794 Candidate.FoundDecl = FoundDecl;
5795 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5796 Candidate.Viable = false;
5797 Candidate.FailureKind = ovl_fail_bad_deduction;
5798 Candidate.IsSurrogate = false;
5799 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005800 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005801 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005802 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005803 return;
5804 }
Mike Stump1eb44332009-09-09 15:08:12 +00005805
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005806 // Add the conversion function template specialization produced by
5807 // template argument deduction as a candidate.
5808 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005809 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005810 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005811}
5812
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005813/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5814/// converts the given @c Object to a function pointer via the
5815/// conversion function @c Conversion, and then attempts to call it
5816/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5817/// the type of function that we'll eventually be calling.
5818void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005819 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005820 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005821 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005822 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005823 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005824 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005825 if (!CandidateSet.isNewCandidate(Conversion))
5826 return;
5827
Douglas Gregor7edfb692009-11-23 12:27:39 +00005828 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005829 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005830
Ahmed Charles13a140c2012-02-25 11:00:22 +00005831 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005832 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005833 Candidate.Function = 0;
5834 Candidate.Surrogate = Conversion;
5835 Candidate.Viable = true;
5836 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005837 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005838 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005839
5840 // Determine the implicit conversion sequence for the implicit
5841 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005842 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005843 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005844 Object->Classify(Context),
5845 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005846 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005847 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005848 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005849 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005850 return;
5851 }
5852
5853 // The first conversion is actually a user-defined conversion whose
5854 // first conversion is ObjectInit's standard conversion (which is
5855 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005856 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005857 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005858 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005859 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005860 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005861 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005862 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005863 = Candidate.Conversions[0].UserDefined.Before;
5864 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5865
Mike Stump1eb44332009-09-09 15:08:12 +00005866 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005867 unsigned NumArgsInProto = Proto->getNumArgs();
5868
5869 // (C++ 13.3.2p2): A candidate function having fewer than m
5870 // parameters is viable only if it has an ellipsis in its parameter
5871 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005872 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005873 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005874 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005875 return;
5876 }
5877
5878 // Function types don't have any default arguments, so just check if
5879 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005880 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005881 // Not enough arguments.
5882 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005883 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005884 return;
5885 }
5886
5887 // Determine the implicit conversion sequences for each of the
5888 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005889 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005890 if (ArgIdx < NumArgsInProto) {
5891 // (C++ 13.3.2p3): for F to be a viable function, there shall
5892 // exist for each argument an implicit conversion sequence
5893 // (13.3.3.1) that converts that argument to the corresponding
5894 // parameter of F.
5895 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005896 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005897 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005898 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005899 /*InOverloadResolution=*/false,
5900 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005901 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005902 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005903 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005904 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005905 break;
5906 }
5907 } else {
5908 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5909 // argument for which there is no corresponding parameter is
5910 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005911 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005912 }
5913 }
5914}
5915
Douglas Gregor063daf62009-03-13 18:40:31 +00005916/// \brief Add overload candidates for overloaded operators that are
5917/// member functions.
5918///
5919/// Add the overloaded operator candidates that are member functions
5920/// for the operator Op that was used in an operator expression such
5921/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5922/// CandidateSet will store the added overload candidates. (C++
5923/// [over.match.oper]).
5924void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5925 SourceLocation OpLoc,
5926 Expr **Args, unsigned NumArgs,
5927 OverloadCandidateSet& CandidateSet,
5928 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005929 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5930
5931 // C++ [over.match.oper]p3:
5932 // For a unary operator @ with an operand of a type whose
5933 // cv-unqualified version is T1, and for a binary operator @ with
5934 // a left operand of a type whose cv-unqualified version is T1 and
5935 // a right operand of a type whose cv-unqualified version is T2,
5936 // three sets of candidate functions, designated member
5937 // candidates, non-member candidates and built-in candidates, are
5938 // constructed as follows:
5939 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005940
5941 // -- If T1 is a class type, the set of member candidates is the
5942 // result of the qualified lookup of T1::operator@
5943 // (13.3.1.1.1); otherwise, the set of member candidates is
5944 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005945 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005946 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005947 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005948 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005949
John McCalla24dc2e2009-11-17 02:14:36 +00005950 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5951 LookupQualifiedName(Operators, T1Rec->getDecl());
5952 Operators.suppressDiagnostics();
5953
Mike Stump1eb44332009-09-09 15:08:12 +00005954 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005955 OperEnd = Operators.end();
5956 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005957 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005958 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005959 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005960 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005961 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005962 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005963}
5964
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005965/// AddBuiltinCandidate - Add a candidate for a built-in
5966/// operator. ResultTy and ParamTys are the result and parameter types
5967/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005968/// arguments being passed to the candidate. IsAssignmentOperator
5969/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005970/// operator. NumContextualBoolArguments is the number of arguments
5971/// (at the beginning of the argument list) that will be contextually
5972/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005973void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005974 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005975 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005976 bool IsAssignmentOperator,
5977 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005978 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005979 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005980
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005981 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005982 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005983 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005984 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005985 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005986 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005987 Candidate.BuiltinTypes.ResultTy = ResultTy;
5988 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5989 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5990
5991 // Determine the implicit conversion sequences for each of the
5992 // arguments.
5993 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005994 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005995 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005996 // C++ [over.match.oper]p4:
5997 // For the built-in assignment operators, conversions of the
5998 // left operand are restricted as follows:
5999 // -- no temporaries are introduced to hold the left operand, and
6000 // -- no user-defined conversions are applied to the left
6001 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006002 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006003 //
6004 // We block these conversions by turning off user-defined
6005 // conversions, since that is the only way that initialization of
6006 // a reference to a non-class type can occur from something that
6007 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006008 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006009 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006010 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006011 Candidate.Conversions[ArgIdx]
6012 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006013 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006014 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006015 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006016 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006017 /*InOverloadResolution=*/false,
6018 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006019 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006020 }
John McCall1d318332010-01-12 00:44:57 +00006021 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006022 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006023 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006024 break;
6025 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006026 }
6027}
6028
6029/// BuiltinCandidateTypeSet - A set of types that will be used for the
6030/// candidate operator functions for built-in operators (C++
6031/// [over.built]). The types are separated into pointer types and
6032/// enumeration types.
6033class BuiltinCandidateTypeSet {
6034 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006035 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006036
6037 /// PointerTypes - The set of pointer types that will be used in the
6038 /// built-in candidates.
6039 TypeSet PointerTypes;
6040
Sebastian Redl78eb8742009-04-19 21:53:20 +00006041 /// MemberPointerTypes - The set of member pointer types that will be
6042 /// used in the built-in candidates.
6043 TypeSet MemberPointerTypes;
6044
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006045 /// EnumerationTypes - The set of enumeration types that will be
6046 /// used in the built-in candidates.
6047 TypeSet EnumerationTypes;
6048
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006049 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006050 /// candidates.
6051 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006052
6053 /// \brief A flag indicating non-record types are viable candidates
6054 bool HasNonRecordTypes;
6055
6056 /// \brief A flag indicating whether either arithmetic or enumeration types
6057 /// were present in the candidate set.
6058 bool HasArithmeticOrEnumeralTypes;
6059
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006060 /// \brief A flag indicating whether the nullptr type was present in the
6061 /// candidate set.
6062 bool HasNullPtrType;
6063
Douglas Gregor5842ba92009-08-24 15:23:48 +00006064 /// Sema - The semantic analysis instance where we are building the
6065 /// candidate type set.
6066 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006067
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006068 /// Context - The AST context in which we will build the type sets.
6069 ASTContext &Context;
6070
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006071 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6072 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006073 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006074
6075public:
6076 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006077 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006078
Mike Stump1eb44332009-09-09 15:08:12 +00006079 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006080 : HasNonRecordTypes(false),
6081 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006082 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006083 SemaRef(SemaRef),
6084 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006085
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006086 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006087 SourceLocation Loc,
6088 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006089 bool AllowExplicitConversions,
6090 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006091
6092 /// pointer_begin - First pointer type found;
6093 iterator pointer_begin() { return PointerTypes.begin(); }
6094
Sebastian Redl78eb8742009-04-19 21:53:20 +00006095 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006096 iterator pointer_end() { return PointerTypes.end(); }
6097
Sebastian Redl78eb8742009-04-19 21:53:20 +00006098 /// member_pointer_begin - First member pointer type found;
6099 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6100
6101 /// member_pointer_end - Past the last member pointer type found;
6102 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6103
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006104 /// enumeration_begin - First enumeration type found;
6105 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6106
Sebastian Redl78eb8742009-04-19 21:53:20 +00006107 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006108 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006109
Douglas Gregor26bcf672010-05-19 03:21:00 +00006110 iterator vector_begin() { return VectorTypes.begin(); }
6111 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006112
6113 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6114 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006115 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006116};
6117
Sebastian Redl78eb8742009-04-19 21:53:20 +00006118/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006119/// the set of pointer types along with any more-qualified variants of
6120/// that type. For example, if @p Ty is "int const *", this routine
6121/// will add "int const *", "int const volatile *", "int const
6122/// restrict *", and "int const volatile restrict *" to the set of
6123/// pointer types. Returns true if the add of @p Ty itself succeeded,
6124/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006125///
6126/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006127bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006128BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6129 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006130
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006131 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006132 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006133 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006134
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006135 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006136 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006137 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006138 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006139 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6140 PointeeTy = PTy->getPointeeType();
6141 buildObjCPtr = true;
6142 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006143 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006144 }
6145
Sebastian Redla9efada2009-11-18 20:39:26 +00006146 // Don't add qualified variants of arrays. For one, they're not allowed
6147 // (the qualifier would sink to the element type), and for another, the
6148 // only overload situation where it matters is subscript or pointer +- int,
6149 // and those shouldn't have qualifier variants anyway.
6150 if (PointeeTy->isArrayType())
6151 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006152
John McCall0953e762009-09-24 19:53:00 +00006153 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006154 bool hasVolatile = VisibleQuals.hasVolatile();
6155 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006156
John McCall0953e762009-09-24 19:53:00 +00006157 // Iterate through all strict supersets of BaseCVR.
6158 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6159 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006160 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006161 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006162
6163 // Skip over restrict if no restrict found anywhere in the types, or if
6164 // the type cannot be restrict-qualified.
6165 if ((CVR & Qualifiers::Restrict) &&
6166 (!hasRestrict ||
6167 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6168 continue;
6169
6170 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006171 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006172
6173 // Build qualified pointer type.
6174 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006175 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006176 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006177 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006178 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6179
6180 // Insert qualified pointer type.
6181 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006182 }
6183
6184 return true;
6185}
6186
Sebastian Redl78eb8742009-04-19 21:53:20 +00006187/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6188/// to the set of pointer types along with any more-qualified variants of
6189/// that type. For example, if @p Ty is "int const *", this routine
6190/// will add "int const *", "int const volatile *", "int const
6191/// restrict *", and "int const volatile restrict *" to the set of
6192/// pointer types. Returns true if the add of @p Ty itself succeeded,
6193/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006194///
6195/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006196bool
6197BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6198 QualType Ty) {
6199 // Insert this type.
6200 if (!MemberPointerTypes.insert(Ty))
6201 return false;
6202
John McCall0953e762009-09-24 19:53:00 +00006203 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6204 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006205
John McCall0953e762009-09-24 19:53:00 +00006206 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006207 // Don't add qualified variants of arrays. For one, they're not allowed
6208 // (the qualifier would sink to the element type), and for another, the
6209 // only overload situation where it matters is subscript or pointer +- int,
6210 // and those shouldn't have qualifier variants anyway.
6211 if (PointeeTy->isArrayType())
6212 return true;
John McCall0953e762009-09-24 19:53:00 +00006213 const Type *ClassTy = PointerTy->getClass();
6214
6215 // Iterate through all strict supersets of the pointee type's CVR
6216 // qualifiers.
6217 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6218 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6219 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006220
John McCall0953e762009-09-24 19:53:00 +00006221 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006222 MemberPointerTypes.insert(
6223 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006224 }
6225
6226 return true;
6227}
6228
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006229/// AddTypesConvertedFrom - Add each of the types to which the type @p
6230/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006231/// primarily interested in pointer types and enumeration types. We also
6232/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006233/// AllowUserConversions is true if we should look at the conversion
6234/// functions of a class type, and AllowExplicitConversions if we
6235/// should also include the explicit conversion functions of a class
6236/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006237void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006238BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006239 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006240 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006241 bool AllowExplicitConversions,
6242 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006243 // Only deal with canonical types.
6244 Ty = Context.getCanonicalType(Ty);
6245
6246 // Look through reference types; they aren't part of the type of an
6247 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006248 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006249 Ty = RefTy->getPointeeType();
6250
John McCall3b657512011-01-19 10:06:00 +00006251 // If we're dealing with an array type, decay to the pointer.
6252 if (Ty->isArrayType())
6253 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6254
6255 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006256 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006257
Chandler Carruth6a577462010-12-13 01:44:01 +00006258 // Flag if we ever add a non-record type.
6259 const RecordType *TyRec = Ty->getAs<RecordType>();
6260 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6261
Chandler Carruth6a577462010-12-13 01:44:01 +00006262 // Flag if we encounter an arithmetic type.
6263 HasArithmeticOrEnumeralTypes =
6264 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6265
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006266 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6267 PointerTypes.insert(Ty);
6268 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006269 // Insert our type, and its more-qualified variants, into the set
6270 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006271 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006272 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006273 } else if (Ty->isMemberPointerType()) {
6274 // Member pointers are far easier, since the pointee can't be converted.
6275 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6276 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006277 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006278 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006279 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006280 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006281 // We treat vector types as arithmetic types in many contexts as an
6282 // extension.
6283 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006284 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006285 } else if (Ty->isNullPtrType()) {
6286 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006287 } else if (AllowUserConversions && TyRec) {
6288 // No conversion functions in incomplete types.
6289 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6290 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006291
Chandler Carruth6a577462010-12-13 01:44:01 +00006292 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6293 const UnresolvedSetImpl *Conversions
6294 = ClassDecl->getVisibleConversionFunctions();
6295 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6296 E = Conversions->end(); I != E; ++I) {
6297 NamedDecl *D = I.getDecl();
6298 if (isa<UsingShadowDecl>(D))
6299 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006300
Chandler Carruth6a577462010-12-13 01:44:01 +00006301 // Skip conversion function templates; they don't tell us anything
6302 // about which builtin types we can convert to.
6303 if (isa<FunctionTemplateDecl>(D))
6304 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006305
Chandler Carruth6a577462010-12-13 01:44:01 +00006306 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6307 if (AllowExplicitConversions || !Conv->isExplicit()) {
6308 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6309 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006310 }
6311 }
6312 }
6313}
6314
Douglas Gregor19b7b152009-08-24 13:43:27 +00006315/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6316/// the volatile- and non-volatile-qualified assignment operators for the
6317/// given type to the candidate set.
6318static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6319 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006320 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006321 unsigned NumArgs,
6322 OverloadCandidateSet &CandidateSet) {
6323 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006324
Douglas Gregor19b7b152009-08-24 13:43:27 +00006325 // T& operator=(T&, T)
6326 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6327 ParamTypes[1] = T;
6328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6329 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006330
Douglas Gregor19b7b152009-08-24 13:43:27 +00006331 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6332 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006333 ParamTypes[0]
6334 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006335 ParamTypes[1] = T;
6336 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006337 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006338 }
6339}
Mike Stump1eb44332009-09-09 15:08:12 +00006340
Sebastian Redl9994a342009-10-25 17:03:50 +00006341/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6342/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006343static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6344 Qualifiers VRQuals;
6345 const RecordType *TyRec;
6346 if (const MemberPointerType *RHSMPType =
6347 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006348 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006349 else
6350 TyRec = ArgExpr->getType()->getAs<RecordType>();
6351 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006352 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006353 VRQuals.addVolatile();
6354 VRQuals.addRestrict();
6355 return VRQuals;
6356 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006357
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006358 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006359 if (!ClassDecl->hasDefinition())
6360 return VRQuals;
6361
John McCalleec51cf2010-01-20 00:46:10 +00006362 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006363 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006364
John McCalleec51cf2010-01-20 00:46:10 +00006365 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006366 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006367 NamedDecl *D = I.getDecl();
6368 if (isa<UsingShadowDecl>(D))
6369 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6370 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006371 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6372 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6373 CanTy = ResTypeRef->getPointeeType();
6374 // Need to go down the pointer/mempointer chain and add qualifiers
6375 // as see them.
6376 bool done = false;
6377 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006378 if (CanTy.isRestrictQualified())
6379 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006380 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6381 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006382 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006383 CanTy->getAs<MemberPointerType>())
6384 CanTy = ResTypeMPtr->getPointeeType();
6385 else
6386 done = true;
6387 if (CanTy.isVolatileQualified())
6388 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006389 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6390 return VRQuals;
6391 }
6392 }
6393 }
6394 return VRQuals;
6395}
John McCall00071ec2010-11-13 05:51:15 +00006396
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006397namespace {
John McCall00071ec2010-11-13 05:51:15 +00006398
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006399/// \brief Helper class to manage the addition of builtin operator overload
6400/// candidates. It provides shared state and utility methods used throughout
6401/// the process, as well as a helper method to add each group of builtin
6402/// operator overloads from the standard to a candidate set.
6403class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006404 // Common instance state available to all overload candidate addition methods.
6405 Sema &S;
6406 Expr **Args;
6407 unsigned NumArgs;
6408 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006409 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006410 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006411 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006412
Chandler Carruth6d695582010-12-12 10:35:00 +00006413 // Define some constants used to index and iterate over the arithemetic types
6414 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006415 // The "promoted arithmetic types" are the arithmetic
6416 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006417 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006418 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006419 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006420 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006421 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006422 LastPromotedArithmeticType = 11;
6423 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006424
Chandler Carruth6d695582010-12-12 10:35:00 +00006425 /// \brief Get the canonical type for a given arithmetic type index.
6426 CanQualType getArithmeticType(unsigned index) {
6427 assert(index < NumArithmeticTypes);
6428 static CanQualType ASTContext::* const
6429 ArithmeticTypes[NumArithmeticTypes] = {
6430 // Start of promoted types.
6431 &ASTContext::FloatTy,
6432 &ASTContext::DoubleTy,
6433 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006434
Chandler Carruth6d695582010-12-12 10:35:00 +00006435 // Start of integral types.
6436 &ASTContext::IntTy,
6437 &ASTContext::LongTy,
6438 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006439 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006440 &ASTContext::UnsignedIntTy,
6441 &ASTContext::UnsignedLongTy,
6442 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006443 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006444 // End of promoted types.
6445
6446 &ASTContext::BoolTy,
6447 &ASTContext::CharTy,
6448 &ASTContext::WCharTy,
6449 &ASTContext::Char16Ty,
6450 &ASTContext::Char32Ty,
6451 &ASTContext::SignedCharTy,
6452 &ASTContext::ShortTy,
6453 &ASTContext::UnsignedCharTy,
6454 &ASTContext::UnsignedShortTy,
6455 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006456 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006457 };
6458 return S.Context.*ArithmeticTypes[index];
6459 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006460
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006461 /// \brief Gets the canonical type resulting from the usual arithemetic
6462 /// converions for the given arithmetic types.
6463 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6464 // Accelerator table for performing the usual arithmetic conversions.
6465 // The rules are basically:
6466 // - if either is floating-point, use the wider floating-point
6467 // - if same signedness, use the higher rank
6468 // - if same size, use unsigned of the higher rank
6469 // - use the larger type
6470 // These rules, together with the axiom that higher ranks are
6471 // never smaller, are sufficient to precompute all of these results
6472 // *except* when dealing with signed types of higher rank.
6473 // (we could precompute SLL x UI for all known platforms, but it's
6474 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006475 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006476 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006477 Dep=-1,
6478 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006479 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006480 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006481 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006482/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6483/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6484/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6485/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6486/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6487/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6488/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6489/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6490/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6491/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6492/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006493 };
6494
6495 assert(L < LastPromotedArithmeticType);
6496 assert(R < LastPromotedArithmeticType);
6497 int Idx = ConversionsTable[L][R];
6498
6499 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006500 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006501
6502 // Slow path: we need to compare widths.
6503 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006504 CanQualType LT = getArithmeticType(L),
6505 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006506 unsigned LW = S.Context.getIntWidth(LT),
6507 RW = S.Context.getIntWidth(RT);
6508
6509 // If they're different widths, use the signed type.
6510 if (LW > RW) return LT;
6511 else if (LW < RW) return RT;
6512
6513 // Otherwise, use the unsigned type of the signed type's rank.
6514 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6515 assert(L == SLL || R == SLL);
6516 return S.Context.UnsignedLongLongTy;
6517 }
6518
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006519 /// \brief Helper method to factor out the common pattern of adding overloads
6520 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006521 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006522 bool HasVolatile,
6523 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006524 QualType ParamTypes[2] = {
6525 S.Context.getLValueReferenceType(CandidateTy),
6526 S.Context.IntTy
6527 };
6528
6529 // Non-volatile version.
6530 if (NumArgs == 1)
6531 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6532 else
6533 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6534
6535 // Use a heuristic to reduce number of builtin candidates in the set:
6536 // add volatile version only if there are conversions to a volatile type.
6537 if (HasVolatile) {
6538 ParamTypes[0] =
6539 S.Context.getLValueReferenceType(
6540 S.Context.getVolatileType(CandidateTy));
6541 if (NumArgs == 1)
6542 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6543 else
6544 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6545 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006546
6547 // Add restrict version only if there are conversions to a restrict type
6548 // and our candidate type is a non-restrict-qualified pointer.
6549 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6550 !CandidateTy.isRestrictQualified()) {
6551 ParamTypes[0]
6552 = S.Context.getLValueReferenceType(
6553 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6554 if (NumArgs == 1)
6555 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6556 else
6557 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6558
6559 if (HasVolatile) {
6560 ParamTypes[0]
6561 = S.Context.getLValueReferenceType(
6562 S.Context.getCVRQualifiedType(CandidateTy,
6563 (Qualifiers::Volatile |
6564 Qualifiers::Restrict)));
6565 if (NumArgs == 1)
6566 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6567 CandidateSet);
6568 else
6569 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6570 }
6571 }
6572
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006573 }
6574
6575public:
6576 BuiltinOperatorOverloadBuilder(
6577 Sema &S, Expr **Args, unsigned NumArgs,
6578 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006579 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006580 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006581 OverloadCandidateSet &CandidateSet)
6582 : S(S), Args(Args), NumArgs(NumArgs),
6583 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006584 HasArithmeticOrEnumeralCandidateType(
6585 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006586 CandidateTypes(CandidateTypes),
6587 CandidateSet(CandidateSet) {
6588 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006589 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006590 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006591 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006592 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006593 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006594 assert(getArithmeticType(FirstPromotedArithmeticType)
6595 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006596 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006597 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006598 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006599 "Invalid last promoted arithmetic type");
6600 }
6601
6602 // C++ [over.built]p3:
6603 //
6604 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6605 // is either volatile or empty, there exist candidate operator
6606 // functions of the form
6607 //
6608 // VQ T& operator++(VQ T&);
6609 // T operator++(VQ T&, int);
6610 //
6611 // C++ [over.built]p4:
6612 //
6613 // For every pair (T, VQ), where T is an arithmetic type other
6614 // than bool, and VQ is either volatile or empty, there exist
6615 // candidate operator functions of the form
6616 //
6617 // VQ T& operator--(VQ T&);
6618 // T operator--(VQ T&, int);
6619 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006620 if (!HasArithmeticOrEnumeralCandidateType)
6621 return;
6622
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006623 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6624 Arith < NumArithmeticTypes; ++Arith) {
6625 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006626 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006627 VisibleTypeConversionsQuals.hasVolatile(),
6628 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006629 }
6630 }
6631
6632 // C++ [over.built]p5:
6633 //
6634 // For every pair (T, VQ), where T is a cv-qualified or
6635 // cv-unqualified object type, and VQ is either volatile or
6636 // empty, there exist candidate operator functions of the form
6637 //
6638 // T*VQ& operator++(T*VQ&);
6639 // T*VQ& operator--(T*VQ&);
6640 // T* operator++(T*VQ&, int);
6641 // T* operator--(T*VQ&, int);
6642 void addPlusPlusMinusMinusPointerOverloads() {
6643 for (BuiltinCandidateTypeSet::iterator
6644 Ptr = CandidateTypes[0].pointer_begin(),
6645 PtrEnd = CandidateTypes[0].pointer_end();
6646 Ptr != PtrEnd; ++Ptr) {
6647 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006648 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006649 continue;
6650
6651 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006652 (!(*Ptr).isVolatileQualified() &&
6653 VisibleTypeConversionsQuals.hasVolatile()),
6654 (!(*Ptr).isRestrictQualified() &&
6655 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006656 }
6657 }
6658
6659 // C++ [over.built]p6:
6660 // For every cv-qualified or cv-unqualified object type T, there
6661 // exist candidate operator functions of the form
6662 //
6663 // T& operator*(T*);
6664 //
6665 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006666 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006667 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006668 // T& operator*(T*);
6669 void addUnaryStarPointerOverloads() {
6670 for (BuiltinCandidateTypeSet::iterator
6671 Ptr = CandidateTypes[0].pointer_begin(),
6672 PtrEnd = CandidateTypes[0].pointer_end();
6673 Ptr != PtrEnd; ++Ptr) {
6674 QualType ParamTy = *Ptr;
6675 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006676 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6677 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006678
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006679 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6680 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6681 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006682
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006683 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6684 &ParamTy, Args, 1, CandidateSet);
6685 }
6686 }
6687
6688 // C++ [over.built]p9:
6689 // For every promoted arithmetic type T, there exist candidate
6690 // operator functions of the form
6691 //
6692 // T operator+(T);
6693 // T operator-(T);
6694 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006695 if (!HasArithmeticOrEnumeralCandidateType)
6696 return;
6697
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006698 for (unsigned Arith = FirstPromotedArithmeticType;
6699 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006700 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006701 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6702 }
6703
6704 // Extension: We also add these operators for vector types.
6705 for (BuiltinCandidateTypeSet::iterator
6706 Vec = CandidateTypes[0].vector_begin(),
6707 VecEnd = CandidateTypes[0].vector_end();
6708 Vec != VecEnd; ++Vec) {
6709 QualType VecTy = *Vec;
6710 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6711 }
6712 }
6713
6714 // C++ [over.built]p8:
6715 // For every type T, there exist candidate operator functions of
6716 // the form
6717 //
6718 // T* operator+(T*);
6719 void addUnaryPlusPointerOverloads() {
6720 for (BuiltinCandidateTypeSet::iterator
6721 Ptr = CandidateTypes[0].pointer_begin(),
6722 PtrEnd = CandidateTypes[0].pointer_end();
6723 Ptr != PtrEnd; ++Ptr) {
6724 QualType ParamTy = *Ptr;
6725 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6726 }
6727 }
6728
6729 // C++ [over.built]p10:
6730 // For every promoted integral type T, there exist candidate
6731 // operator functions of the form
6732 //
6733 // T operator~(T);
6734 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006735 if (!HasArithmeticOrEnumeralCandidateType)
6736 return;
6737
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006738 for (unsigned Int = FirstPromotedIntegralType;
6739 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006740 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006741 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6742 }
6743
6744 // Extension: We also add this operator for vector types.
6745 for (BuiltinCandidateTypeSet::iterator
6746 Vec = CandidateTypes[0].vector_begin(),
6747 VecEnd = CandidateTypes[0].vector_end();
6748 Vec != VecEnd; ++Vec) {
6749 QualType VecTy = *Vec;
6750 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6751 }
6752 }
6753
6754 // C++ [over.match.oper]p16:
6755 // For every pointer to member type T, there exist candidate operator
6756 // functions of the form
6757 //
6758 // bool operator==(T,T);
6759 // bool operator!=(T,T);
6760 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6761 /// Set of (canonical) types that we've already handled.
6762 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6763
6764 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6765 for (BuiltinCandidateTypeSet::iterator
6766 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6767 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6768 MemPtr != MemPtrEnd;
6769 ++MemPtr) {
6770 // Don't add the same builtin candidate twice.
6771 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6772 continue;
6773
6774 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6775 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6776 CandidateSet);
6777 }
6778 }
6779 }
6780
6781 // C++ [over.built]p15:
6782 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006783 // For every T, where T is an enumeration type, a pointer type, or
6784 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006785 //
6786 // bool operator<(T, T);
6787 // bool operator>(T, T);
6788 // bool operator<=(T, T);
6789 // bool operator>=(T, T);
6790 // bool operator==(T, T);
6791 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006792 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006793 // C++ [over.match.oper]p3:
6794 // [...]the built-in candidates include all of the candidate operator
6795 // functions defined in 13.6 that, compared to the given operator, [...]
6796 // do not have the same parameter-type-list as any non-template non-member
6797 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006798 //
Eli Friedman97c67392012-09-18 21:52:24 +00006799 // Note that in practice, this only affects enumeration types because there
6800 // aren't any built-in candidates of record type, and a user-defined operator
6801 // must have an operand of record or enumeration type. Also, the only other
6802 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006803 // cannot be overloaded for enumeration types, so this is the only place
6804 // where we must suppress candidates like this.
6805 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6806 UserDefinedBinaryOperators;
6807
6808 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6809 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6810 CandidateTypes[ArgIdx].enumeration_end()) {
6811 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6812 CEnd = CandidateSet.end();
6813 C != CEnd; ++C) {
6814 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6815 continue;
6816
Eli Friedman97c67392012-09-18 21:52:24 +00006817 if (C->Function->isFunctionTemplateSpecialization())
6818 continue;
6819
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006820 QualType FirstParamType =
6821 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6822 QualType SecondParamType =
6823 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6824
6825 // Skip if either parameter isn't of enumeral type.
6826 if (!FirstParamType->isEnumeralType() ||
6827 !SecondParamType->isEnumeralType())
6828 continue;
6829
6830 // Add this operator to the set of known user-defined operators.
6831 UserDefinedBinaryOperators.insert(
6832 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6833 S.Context.getCanonicalType(SecondParamType)));
6834 }
6835 }
6836 }
6837
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006838 /// Set of (canonical) types that we've already handled.
6839 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6840
6841 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6842 for (BuiltinCandidateTypeSet::iterator
6843 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6844 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6845 Ptr != PtrEnd; ++Ptr) {
6846 // Don't add the same builtin candidate twice.
6847 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6848 continue;
6849
6850 QualType ParamTypes[2] = { *Ptr, *Ptr };
6851 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6852 CandidateSet);
6853 }
6854 for (BuiltinCandidateTypeSet::iterator
6855 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6856 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6857 Enum != EnumEnd; ++Enum) {
6858 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6859
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006860 // Don't add the same builtin candidate twice, or if a user defined
6861 // candidate exists.
6862 if (!AddedTypes.insert(CanonType) ||
6863 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6864 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006865 continue;
6866
6867 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006868 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6869 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006870 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006871
6872 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6873 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6874 if (AddedTypes.insert(NullPtrTy) &&
6875 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6876 NullPtrTy))) {
6877 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6878 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6879 CandidateSet);
6880 }
6881 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006882 }
6883 }
6884
6885 // C++ [over.built]p13:
6886 //
6887 // For every cv-qualified or cv-unqualified object type T
6888 // there exist candidate operator functions of the form
6889 //
6890 // T* operator+(T*, ptrdiff_t);
6891 // T& operator[](T*, ptrdiff_t); [BELOW]
6892 // T* operator-(T*, ptrdiff_t);
6893 // T* operator+(ptrdiff_t, T*);
6894 // T& operator[](ptrdiff_t, T*); [BELOW]
6895 //
6896 // C++ [over.built]p14:
6897 //
6898 // For every T, where T is a pointer to object type, there
6899 // exist candidate operator functions of the form
6900 //
6901 // ptrdiff_t operator-(T, T);
6902 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6903 /// Set of (canonical) types that we've already handled.
6904 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6905
6906 for (int Arg = 0; Arg < 2; ++Arg) {
6907 QualType AsymetricParamTypes[2] = {
6908 S.Context.getPointerDiffType(),
6909 S.Context.getPointerDiffType(),
6910 };
6911 for (BuiltinCandidateTypeSet::iterator
6912 Ptr = CandidateTypes[Arg].pointer_begin(),
6913 PtrEnd = CandidateTypes[Arg].pointer_end();
6914 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006915 QualType PointeeTy = (*Ptr)->getPointeeType();
6916 if (!PointeeTy->isObjectType())
6917 continue;
6918
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006919 AsymetricParamTypes[Arg] = *Ptr;
6920 if (Arg == 0 || Op == OO_Plus) {
6921 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6922 // T* operator+(ptrdiff_t, T*);
6923 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6924 CandidateSet);
6925 }
6926 if (Op == OO_Minus) {
6927 // ptrdiff_t operator-(T, T);
6928 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6929 continue;
6930
6931 QualType ParamTypes[2] = { *Ptr, *Ptr };
6932 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6933 Args, 2, CandidateSet);
6934 }
6935 }
6936 }
6937 }
6938
6939 // C++ [over.built]p12:
6940 //
6941 // For every pair of promoted arithmetic types L and R, there
6942 // exist candidate operator functions of the form
6943 //
6944 // LR operator*(L, R);
6945 // LR operator/(L, R);
6946 // LR operator+(L, R);
6947 // LR operator-(L, R);
6948 // bool operator<(L, R);
6949 // bool operator>(L, R);
6950 // bool operator<=(L, R);
6951 // bool operator>=(L, R);
6952 // bool operator==(L, R);
6953 // bool operator!=(L, R);
6954 //
6955 // where LR is the result of the usual arithmetic conversions
6956 // between types L and R.
6957 //
6958 // C++ [over.built]p24:
6959 //
6960 // For every pair of promoted arithmetic types L and R, there exist
6961 // candidate operator functions of the form
6962 //
6963 // LR operator?(bool, L, R);
6964 //
6965 // where LR is the result of the usual arithmetic conversions
6966 // between types L and R.
6967 // Our candidates ignore the first parameter.
6968 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006969 if (!HasArithmeticOrEnumeralCandidateType)
6970 return;
6971
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006972 for (unsigned Left = FirstPromotedArithmeticType;
6973 Left < LastPromotedArithmeticType; ++Left) {
6974 for (unsigned Right = FirstPromotedArithmeticType;
6975 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006976 QualType LandR[2] = { getArithmeticType(Left),
6977 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006978 QualType Result =
6979 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006980 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006981 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6982 }
6983 }
6984
6985 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6986 // conditional operator for vector types.
6987 for (BuiltinCandidateTypeSet::iterator
6988 Vec1 = CandidateTypes[0].vector_begin(),
6989 Vec1End = CandidateTypes[0].vector_end();
6990 Vec1 != Vec1End; ++Vec1) {
6991 for (BuiltinCandidateTypeSet::iterator
6992 Vec2 = CandidateTypes[1].vector_begin(),
6993 Vec2End = CandidateTypes[1].vector_end();
6994 Vec2 != Vec2End; ++Vec2) {
6995 QualType LandR[2] = { *Vec1, *Vec2 };
6996 QualType Result = S.Context.BoolTy;
6997 if (!isComparison) {
6998 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6999 Result = *Vec1;
7000 else
7001 Result = *Vec2;
7002 }
7003
7004 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7005 }
7006 }
7007 }
7008
7009 // C++ [over.built]p17:
7010 //
7011 // For every pair of promoted integral types L and R, there
7012 // exist candidate operator functions of the form
7013 //
7014 // LR operator%(L, R);
7015 // LR operator&(L, R);
7016 // LR operator^(L, R);
7017 // LR operator|(L, R);
7018 // L operator<<(L, R);
7019 // L operator>>(L, R);
7020 //
7021 // where LR is the result of the usual arithmetic conversions
7022 // between types L and R.
7023 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007024 if (!HasArithmeticOrEnumeralCandidateType)
7025 return;
7026
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007027 for (unsigned Left = FirstPromotedIntegralType;
7028 Left < LastPromotedIntegralType; ++Left) {
7029 for (unsigned Right = FirstPromotedIntegralType;
7030 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007031 QualType LandR[2] = { getArithmeticType(Left),
7032 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007033 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7034 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007035 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007036 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7037 }
7038 }
7039 }
7040
7041 // C++ [over.built]p20:
7042 //
7043 // For every pair (T, VQ), where T is an enumeration or
7044 // pointer to member type and VQ is either volatile or
7045 // empty, there exist candidate operator functions of the form
7046 //
7047 // VQ T& operator=(VQ T&, T);
7048 void addAssignmentMemberPointerOrEnumeralOverloads() {
7049 /// Set of (canonical) types that we've already handled.
7050 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7051
7052 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7053 for (BuiltinCandidateTypeSet::iterator
7054 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7055 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7056 Enum != EnumEnd; ++Enum) {
7057 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7058 continue;
7059
7060 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7061 CandidateSet);
7062 }
7063
7064 for (BuiltinCandidateTypeSet::iterator
7065 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7066 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7067 MemPtr != MemPtrEnd; ++MemPtr) {
7068 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7069 continue;
7070
7071 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7072 CandidateSet);
7073 }
7074 }
7075 }
7076
7077 // C++ [over.built]p19:
7078 //
7079 // For every pair (T, VQ), where T is any type and VQ is either
7080 // volatile or empty, there exist candidate operator functions
7081 // of the form
7082 //
7083 // T*VQ& operator=(T*VQ&, T*);
7084 //
7085 // C++ [over.built]p21:
7086 //
7087 // For every pair (T, VQ), where T is a cv-qualified or
7088 // cv-unqualified object type and VQ is either volatile or
7089 // empty, there exist candidate operator functions of the form
7090 //
7091 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7092 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7093 void addAssignmentPointerOverloads(bool isEqualOp) {
7094 /// Set of (canonical) types that we've already handled.
7095 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7096
7097 for (BuiltinCandidateTypeSet::iterator
7098 Ptr = CandidateTypes[0].pointer_begin(),
7099 PtrEnd = CandidateTypes[0].pointer_end();
7100 Ptr != PtrEnd; ++Ptr) {
7101 // If this is operator=, keep track of the builtin candidates we added.
7102 if (isEqualOp)
7103 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007104 else if (!(*Ptr)->getPointeeType()->isObjectType())
7105 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007106
7107 // non-volatile version
7108 QualType ParamTypes[2] = {
7109 S.Context.getLValueReferenceType(*Ptr),
7110 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7111 };
7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7113 /*IsAssigmentOperator=*/ isEqualOp);
7114
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007115 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7116 VisibleTypeConversionsQuals.hasVolatile();
7117 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007118 // volatile version
7119 ParamTypes[0] =
7120 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7121 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7122 /*IsAssigmentOperator=*/isEqualOp);
7123 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007124
7125 if (!(*Ptr).isRestrictQualified() &&
7126 VisibleTypeConversionsQuals.hasRestrict()) {
7127 // restrict version
7128 ParamTypes[0]
7129 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7130 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7131 /*IsAssigmentOperator=*/isEqualOp);
7132
7133 if (NeedVolatile) {
7134 // volatile restrict version
7135 ParamTypes[0]
7136 = S.Context.getLValueReferenceType(
7137 S.Context.getCVRQualifiedType(*Ptr,
7138 (Qualifiers::Volatile |
7139 Qualifiers::Restrict)));
7140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7141 CandidateSet,
7142 /*IsAssigmentOperator=*/isEqualOp);
7143 }
7144 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007145 }
7146
7147 if (isEqualOp) {
7148 for (BuiltinCandidateTypeSet::iterator
7149 Ptr = CandidateTypes[1].pointer_begin(),
7150 PtrEnd = CandidateTypes[1].pointer_end();
7151 Ptr != PtrEnd; ++Ptr) {
7152 // Make sure we don't add the same candidate twice.
7153 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7154 continue;
7155
Chandler Carruth6df868e2010-12-12 08:17:55 +00007156 QualType ParamTypes[2] = {
7157 S.Context.getLValueReferenceType(*Ptr),
7158 *Ptr,
7159 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007160
7161 // non-volatile version
7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7163 /*IsAssigmentOperator=*/true);
7164
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007165 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7166 VisibleTypeConversionsQuals.hasVolatile();
7167 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007168 // volatile version
7169 ParamTypes[0] =
7170 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7172 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007173 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007174
7175 if (!(*Ptr).isRestrictQualified() &&
7176 VisibleTypeConversionsQuals.hasRestrict()) {
7177 // restrict version
7178 ParamTypes[0]
7179 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7180 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7181 CandidateSet, /*IsAssigmentOperator=*/true);
7182
7183 if (NeedVolatile) {
7184 // volatile restrict version
7185 ParamTypes[0]
7186 = S.Context.getLValueReferenceType(
7187 S.Context.getCVRQualifiedType(*Ptr,
7188 (Qualifiers::Volatile |
7189 Qualifiers::Restrict)));
7190 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7191 CandidateSet, /*IsAssigmentOperator=*/true);
7192
7193 }
7194 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007195 }
7196 }
7197 }
7198
7199 // C++ [over.built]p18:
7200 //
7201 // For every triple (L, VQ, R), where L is an arithmetic type,
7202 // VQ is either volatile or empty, and R is a promoted
7203 // arithmetic type, there exist candidate operator functions of
7204 // the form
7205 //
7206 // VQ L& operator=(VQ L&, R);
7207 // VQ L& operator*=(VQ L&, R);
7208 // VQ L& operator/=(VQ L&, R);
7209 // VQ L& operator+=(VQ L&, R);
7210 // VQ L& operator-=(VQ L&, R);
7211 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007212 if (!HasArithmeticOrEnumeralCandidateType)
7213 return;
7214
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007215 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7216 for (unsigned Right = FirstPromotedArithmeticType;
7217 Right < LastPromotedArithmeticType; ++Right) {
7218 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007219 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007220
7221 // Add this built-in operator as a candidate (VQ is empty).
7222 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007223 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007224 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7225 /*IsAssigmentOperator=*/isEqualOp);
7226
7227 // Add this built-in operator as a candidate (VQ is 'volatile').
7228 if (VisibleTypeConversionsQuals.hasVolatile()) {
7229 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007230 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007231 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007232 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7233 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007234 /*IsAssigmentOperator=*/isEqualOp);
7235 }
7236 }
7237 }
7238
7239 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7240 for (BuiltinCandidateTypeSet::iterator
7241 Vec1 = CandidateTypes[0].vector_begin(),
7242 Vec1End = CandidateTypes[0].vector_end();
7243 Vec1 != Vec1End; ++Vec1) {
7244 for (BuiltinCandidateTypeSet::iterator
7245 Vec2 = CandidateTypes[1].vector_begin(),
7246 Vec2End = CandidateTypes[1].vector_end();
7247 Vec2 != Vec2End; ++Vec2) {
7248 QualType ParamTypes[2];
7249 ParamTypes[1] = *Vec2;
7250 // Add this built-in operator as a candidate (VQ is empty).
7251 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7253 /*IsAssigmentOperator=*/isEqualOp);
7254
7255 // Add this built-in operator as a candidate (VQ is 'volatile').
7256 if (VisibleTypeConversionsQuals.hasVolatile()) {
7257 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7258 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7260 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007261 /*IsAssigmentOperator=*/isEqualOp);
7262 }
7263 }
7264 }
7265 }
7266
7267 // C++ [over.built]p22:
7268 //
7269 // For every triple (L, VQ, R), where L is an integral type, VQ
7270 // is either volatile or empty, and R is a promoted integral
7271 // type, there exist candidate operator functions of the form
7272 //
7273 // VQ L& operator%=(VQ L&, R);
7274 // VQ L& operator<<=(VQ L&, R);
7275 // VQ L& operator>>=(VQ L&, R);
7276 // VQ L& operator&=(VQ L&, R);
7277 // VQ L& operator^=(VQ L&, R);
7278 // VQ L& operator|=(VQ L&, R);
7279 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007280 if (!HasArithmeticOrEnumeralCandidateType)
7281 return;
7282
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007283 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7284 for (unsigned Right = FirstPromotedIntegralType;
7285 Right < LastPromotedIntegralType; ++Right) {
7286 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007287 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007288
7289 // Add this built-in operator as a candidate (VQ is empty).
7290 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007291 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7293 if (VisibleTypeConversionsQuals.hasVolatile()) {
7294 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007295 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007296 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7297 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7299 CandidateSet);
7300 }
7301 }
7302 }
7303 }
7304
7305 // C++ [over.operator]p23:
7306 //
7307 // There also exist candidate operator functions of the form
7308 //
7309 // bool operator!(bool);
7310 // bool operator&&(bool, bool);
7311 // bool operator||(bool, bool);
7312 void addExclaimOverload() {
7313 QualType ParamTy = S.Context.BoolTy;
7314 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7315 /*IsAssignmentOperator=*/false,
7316 /*NumContextualBoolArguments=*/1);
7317 }
7318 void addAmpAmpOrPipePipeOverload() {
7319 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7320 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7321 /*IsAssignmentOperator=*/false,
7322 /*NumContextualBoolArguments=*/2);
7323 }
7324
7325 // C++ [over.built]p13:
7326 //
7327 // For every cv-qualified or cv-unqualified object type T there
7328 // exist candidate operator functions of the form
7329 //
7330 // T* operator+(T*, ptrdiff_t); [ABOVE]
7331 // T& operator[](T*, ptrdiff_t);
7332 // T* operator-(T*, ptrdiff_t); [ABOVE]
7333 // T* operator+(ptrdiff_t, T*); [ABOVE]
7334 // T& operator[](ptrdiff_t, T*);
7335 void addSubscriptOverloads() {
7336 for (BuiltinCandidateTypeSet::iterator
7337 Ptr = CandidateTypes[0].pointer_begin(),
7338 PtrEnd = CandidateTypes[0].pointer_end();
7339 Ptr != PtrEnd; ++Ptr) {
7340 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7341 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007342 if (!PointeeType->isObjectType())
7343 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007344
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007345 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7346
7347 // T& operator[](T*, ptrdiff_t)
7348 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7349 }
7350
7351 for (BuiltinCandidateTypeSet::iterator
7352 Ptr = CandidateTypes[1].pointer_begin(),
7353 PtrEnd = CandidateTypes[1].pointer_end();
7354 Ptr != PtrEnd; ++Ptr) {
7355 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7356 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007357 if (!PointeeType->isObjectType())
7358 continue;
7359
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007360 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7361
7362 // T& operator[](ptrdiff_t, T*)
7363 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7364 }
7365 }
7366
7367 // C++ [over.built]p11:
7368 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7369 // C1 is the same type as C2 or is a derived class of C2, T is an object
7370 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7371 // there exist candidate operator functions of the form
7372 //
7373 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7374 //
7375 // where CV12 is the union of CV1 and CV2.
7376 void addArrowStarOverloads() {
7377 for (BuiltinCandidateTypeSet::iterator
7378 Ptr = CandidateTypes[0].pointer_begin(),
7379 PtrEnd = CandidateTypes[0].pointer_end();
7380 Ptr != PtrEnd; ++Ptr) {
7381 QualType C1Ty = (*Ptr);
7382 QualType C1;
7383 QualifierCollector Q1;
7384 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7385 if (!isa<RecordType>(C1))
7386 continue;
7387 // heuristic to reduce number of builtin candidates in the set.
7388 // Add volatile/restrict version only if there are conversions to a
7389 // volatile/restrict type.
7390 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7391 continue;
7392 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7393 continue;
7394 for (BuiltinCandidateTypeSet::iterator
7395 MemPtr = CandidateTypes[1].member_pointer_begin(),
7396 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7397 MemPtr != MemPtrEnd; ++MemPtr) {
7398 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7399 QualType C2 = QualType(mptr->getClass(), 0);
7400 C2 = C2.getUnqualifiedType();
7401 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7402 break;
7403 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7404 // build CV12 T&
7405 QualType T = mptr->getPointeeType();
7406 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7407 T.isVolatileQualified())
7408 continue;
7409 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7410 T.isRestrictQualified())
7411 continue;
7412 T = Q1.apply(S.Context, T);
7413 QualType ResultTy = S.Context.getLValueReferenceType(T);
7414 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7415 }
7416 }
7417 }
7418
7419 // Note that we don't consider the first argument, since it has been
7420 // contextually converted to bool long ago. The candidates below are
7421 // therefore added as binary.
7422 //
7423 // C++ [over.built]p25:
7424 // For every type T, where T is a pointer, pointer-to-member, or scoped
7425 // enumeration type, there exist candidate operator functions of the form
7426 //
7427 // T operator?(bool, T, T);
7428 //
7429 void addConditionalOperatorOverloads() {
7430 /// Set of (canonical) types that we've already handled.
7431 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7432
7433 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7434 for (BuiltinCandidateTypeSet::iterator
7435 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7436 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7437 Ptr != PtrEnd; ++Ptr) {
7438 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7439 continue;
7440
7441 QualType ParamTypes[2] = { *Ptr, *Ptr };
7442 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7443 }
7444
7445 for (BuiltinCandidateTypeSet::iterator
7446 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7447 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7448 MemPtr != MemPtrEnd; ++MemPtr) {
7449 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7450 continue;
7451
7452 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7453 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7454 }
7455
David Blaikie4e4d0842012-03-11 07:00:24 +00007456 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007457 for (BuiltinCandidateTypeSet::iterator
7458 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7459 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7460 Enum != EnumEnd; ++Enum) {
7461 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7462 continue;
7463
7464 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7465 continue;
7466
7467 QualType ParamTypes[2] = { *Enum, *Enum };
7468 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7469 }
7470 }
7471 }
7472 }
7473};
7474
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007475} // end anonymous namespace
7476
7477/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7478/// operator overloads to the candidate set (C++ [over.built]), based
7479/// on the operator @p Op and the arguments given. For example, if the
7480/// operator is a binary '+', this routine might add "int
7481/// operator+(int, int)" to cover integer addition.
7482void
7483Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7484 SourceLocation OpLoc,
7485 Expr **Args, unsigned NumArgs,
7486 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007487 // Find all of the types that the arguments can convert to, but only
7488 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007489 // that make use of these types. Also record whether we encounter non-record
7490 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007491 Qualifiers VisibleTypeConversionsQuals;
7492 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007493 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7494 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007495
7496 bool HasNonRecordCandidateType = false;
7497 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007498 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007499 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7500 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7501 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7502 OpLoc,
7503 true,
7504 (Op == OO_Exclaim ||
7505 Op == OO_AmpAmp ||
7506 Op == OO_PipePipe),
7507 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007508 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7509 CandidateTypes[ArgIdx].hasNonRecordTypes();
7510 HasArithmeticOrEnumeralCandidateType =
7511 HasArithmeticOrEnumeralCandidateType ||
7512 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007513 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007514
Chandler Carruth6a577462010-12-13 01:44:01 +00007515 // Exit early when no non-record types have been added to the candidate set
7516 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007517 //
7518 // We can't exit early for !, ||, or &&, since there we have always have
7519 // 'bool' overloads.
7520 if (!HasNonRecordCandidateType &&
7521 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007522 return;
7523
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007524 // Setup an object to manage the common state for building overloads.
7525 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7526 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007527 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007528 CandidateTypes, CandidateSet);
7529
7530 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007531 switch (Op) {
7532 case OO_None:
7533 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007534 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007535
Chandler Carruthabb71842010-12-12 08:51:33 +00007536 case OO_New:
7537 case OO_Delete:
7538 case OO_Array_New:
7539 case OO_Array_Delete:
7540 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007541 llvm_unreachable(
7542 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007543
7544 case OO_Comma:
7545 case OO_Arrow:
7546 // C++ [over.match.oper]p3:
7547 // -- For the operator ',', the unary operator '&', or the
7548 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007549 break;
7550
7551 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007552 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007553 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007554 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007555
7556 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007557 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007558 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007559 } else {
7560 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7561 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7562 }
Douglas Gregor74253732008-11-19 15:42:04 +00007563 break;
7564
Chandler Carruthabb71842010-12-12 08:51:33 +00007565 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007566 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007567 OpBuilder.addUnaryStarPointerOverloads();
7568 else
7569 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7570 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007571
Chandler Carruthabb71842010-12-12 08:51:33 +00007572 case OO_Slash:
7573 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007574 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007575
7576 case OO_PlusPlus:
7577 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007578 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7579 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007580 break;
7581
Douglas Gregor19b7b152009-08-24 13:43:27 +00007582 case OO_EqualEqual:
7583 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007584 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007585 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007586
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007587 case OO_Less:
7588 case OO_Greater:
7589 case OO_LessEqual:
7590 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007591 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007592 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7593 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007594
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007595 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007596 case OO_Caret:
7597 case OO_Pipe:
7598 case OO_LessLess:
7599 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007600 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007601 break;
7602
Chandler Carruthabb71842010-12-12 08:51:33 +00007603 case OO_Amp: // '&' is either unary or binary
7604 if (NumArgs == 1)
7605 // C++ [over.match.oper]p3:
7606 // -- For the operator ',', the unary operator '&', or the
7607 // operator '->', the built-in candidates set is empty.
7608 break;
7609
7610 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7611 break;
7612
7613 case OO_Tilde:
7614 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7615 break;
7616
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007617 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007618 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007619 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007620
7621 case OO_PlusEqual:
7622 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007623 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007624 // Fall through.
7625
7626 case OO_StarEqual:
7627 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007628 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007629 break;
7630
7631 case OO_PercentEqual:
7632 case OO_LessLessEqual:
7633 case OO_GreaterGreaterEqual:
7634 case OO_AmpEqual:
7635 case OO_CaretEqual:
7636 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007637 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007638 break;
7639
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007640 case OO_Exclaim:
7641 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007642 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007643
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007644 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007645 case OO_PipePipe:
7646 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007647 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007648
7649 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007650 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007651 break;
7652
7653 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007654 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007655 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007656
7657 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007658 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007659 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7660 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007661 }
7662}
7663
Douglas Gregorfa047642009-02-04 00:32:51 +00007664/// \brief Add function candidates found via argument-dependent lookup
7665/// to the set of overloading candidates.
7666///
7667/// This routine performs argument-dependent name lookup based on the
7668/// given function name (which may also be an operator name) and adds
7669/// all of the overload candidates found by ADL to the overload
7670/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007671void
Douglas Gregorfa047642009-02-04 00:32:51 +00007672Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007673 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007674 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007675 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007676 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007677 bool PartialOverloading,
7678 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007679 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007680
John McCalla113e722010-01-26 06:04:06 +00007681 // FIXME: This approach for uniquing ADL results (and removing
7682 // redundant candidates from the set) relies on pointer-equality,
7683 // which means we need to key off the canonical decl. However,
7684 // always going back to the canonical decl might not get us the
7685 // right set of default arguments. What default arguments are
7686 // we supposed to consider on ADL candidates, anyway?
7687
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007688 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007689 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007690 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007691
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007692 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007693 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7694 CandEnd = CandidateSet.end();
7695 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007696 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007697 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007698 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007699 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007700 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007701
7702 // For each of the ADL candidates we found, add it to the overload
7703 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007704 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007705 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007706 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007707 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007708 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007709
Ahmed Charles13a140c2012-02-25 11:00:22 +00007710 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7711 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007712 } else
John McCall6e266892010-01-26 03:27:55 +00007713 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007714 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007715 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007716 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007717}
7718
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007719/// isBetterOverloadCandidate - Determines whether the first overload
7720/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007721bool
John McCall120d63c2010-08-24 20:38:10 +00007722isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007723 const OverloadCandidate &Cand1,
7724 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007725 SourceLocation Loc,
7726 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007727 // Define viable functions to be better candidates than non-viable
7728 // functions.
7729 if (!Cand2.Viable)
7730 return Cand1.Viable;
7731 else if (!Cand1.Viable)
7732 return false;
7733
Douglas Gregor88a35142008-12-22 05:46:06 +00007734 // C++ [over.match.best]p1:
7735 //
7736 // -- if F is a static member function, ICS1(F) is defined such
7737 // that ICS1(F) is neither better nor worse than ICS1(G) for
7738 // any function G, and, symmetrically, ICS1(G) is neither
7739 // better nor worse than ICS1(F).
7740 unsigned StartArg = 0;
7741 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7742 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007743
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007744 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007745 // A viable function F1 is defined to be a better function than another
7746 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007747 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007748 unsigned NumArgs = Cand1.NumConversions;
7749 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007750 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007751 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007752 switch (CompareImplicitConversionSequences(S,
7753 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007754 Cand2.Conversions[ArgIdx])) {
7755 case ImplicitConversionSequence::Better:
7756 // Cand1 has a better conversion sequence.
7757 HasBetterConversion = true;
7758 break;
7759
7760 case ImplicitConversionSequence::Worse:
7761 // Cand1 can't be better than Cand2.
7762 return false;
7763
7764 case ImplicitConversionSequence::Indistinguishable:
7765 // Do nothing.
7766 break;
7767 }
7768 }
7769
Mike Stump1eb44332009-09-09 15:08:12 +00007770 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007771 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007772 if (HasBetterConversion)
7773 return true;
7774
Mike Stump1eb44332009-09-09 15:08:12 +00007775 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007776 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007777 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007778 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7779 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007780
7781 // -- F1 and F2 are function template specializations, and the function
7782 // template for F1 is more specialized than the template for F2
7783 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007784 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007785 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007786 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007787 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007788 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7789 Cand2.Function->getPrimaryTemplate(),
7790 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007791 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007792 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007793 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007794 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007795 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007796
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007797 // -- the context is an initialization by user-defined conversion
7798 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7799 // from the return type of F1 to the destination type (i.e.,
7800 // the type of the entity being initialized) is a better
7801 // conversion sequence than the standard conversion sequence
7802 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007803 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007804 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007805 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007806 // First check whether we prefer one of the conversion functions over the
7807 // other. This only distinguishes the results in non-standard, extension
7808 // cases such as the conversion from a lambda closure type to a function
7809 // pointer or block.
7810 ImplicitConversionSequence::CompareKind FuncResult
7811 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7812 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7813 return FuncResult;
7814
John McCall120d63c2010-08-24 20:38:10 +00007815 switch (CompareStandardConversionSequences(S,
7816 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007817 Cand2.FinalConversion)) {
7818 case ImplicitConversionSequence::Better:
7819 // Cand1 has a better conversion sequence.
7820 return true;
7821
7822 case ImplicitConversionSequence::Worse:
7823 // Cand1 can't be better than Cand2.
7824 return false;
7825
7826 case ImplicitConversionSequence::Indistinguishable:
7827 // Do nothing
7828 break;
7829 }
7830 }
7831
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007832 return false;
7833}
7834
Mike Stump1eb44332009-09-09 15:08:12 +00007835/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007836/// within an overload candidate set.
7837///
James Dennettefce31f2012-06-22 08:10:18 +00007838/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007839/// which overload resolution occurs.
7840///
James Dennettefce31f2012-06-22 08:10:18 +00007841/// \param Best If overload resolution was successful or found a deleted
7842/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007843///
7844/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007845OverloadingResult
7846OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007847 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007848 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007849 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007850 Best = end();
7851 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7852 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007853 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007854 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007855 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007856 }
7857
7858 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007859 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007860 return OR_No_Viable_Function;
7861
7862 // Make sure that this function is better than every other viable
7863 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007864 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007865 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007866 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007867 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007868 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007869 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007870 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007871 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007872 }
Mike Stump1eb44332009-09-09 15:08:12 +00007873
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007874 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007875 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007876 (Best->Function->isDeleted() ||
7877 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007878 return OR_Deleted;
7879
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007880 return OR_Success;
7881}
7882
John McCall3c80f572010-01-12 02:15:36 +00007883namespace {
7884
7885enum OverloadCandidateKind {
7886 oc_function,
7887 oc_method,
7888 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007889 oc_function_template,
7890 oc_method_template,
7891 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007892 oc_implicit_default_constructor,
7893 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007894 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007895 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007896 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007897 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007898};
7899
John McCall220ccbf2010-01-13 00:25:19 +00007900OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7901 FunctionDecl *Fn,
7902 std::string &Description) {
7903 bool isTemplate = false;
7904
7905 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7906 isTemplate = true;
7907 Description = S.getTemplateArgumentBindingsText(
7908 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7909 }
John McCallb1622a12010-01-06 09:43:14 +00007910
7911 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007912 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007913 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007914
Sebastian Redlf677ea32011-02-05 19:23:19 +00007915 if (Ctor->getInheritedConstructor())
7916 return oc_implicit_inherited_constructor;
7917
Sean Hunt82713172011-05-25 23:16:36 +00007918 if (Ctor->isDefaultConstructor())
7919 return oc_implicit_default_constructor;
7920
7921 if (Ctor->isMoveConstructor())
7922 return oc_implicit_move_constructor;
7923
7924 assert(Ctor->isCopyConstructor() &&
7925 "unexpected sort of implicit constructor");
7926 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007927 }
7928
7929 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7930 // This actually gets spelled 'candidate function' for now, but
7931 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007932 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007933 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007934
Sean Hunt82713172011-05-25 23:16:36 +00007935 if (Meth->isMoveAssignmentOperator())
7936 return oc_implicit_move_assignment;
7937
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007938 if (Meth->isCopyAssignmentOperator())
7939 return oc_implicit_copy_assignment;
7940
7941 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7942 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007943 }
7944
John McCall220ccbf2010-01-13 00:25:19 +00007945 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007946}
7947
Sebastian Redlf677ea32011-02-05 19:23:19 +00007948void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7949 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7950 if (!Ctor) return;
7951
7952 Ctor = Ctor->getInheritedConstructor();
7953 if (!Ctor) return;
7954
7955 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7956}
7957
John McCall3c80f572010-01-12 02:15:36 +00007958} // end anonymous namespace
7959
7960// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007961void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007962 std::string FnDesc;
7963 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007964 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7965 << (unsigned) K << FnDesc;
7966 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7967 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007968 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007969}
7970
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007971//Notes the location of all overload candidates designated through
7972// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007973void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007974 assert(OverloadedExpr->getType() == Context.OverloadTy);
7975
7976 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7977 OverloadExpr *OvlExpr = Ovl.Expression;
7978
7979 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7980 IEnd = OvlExpr->decls_end();
7981 I != IEnd; ++I) {
7982 if (FunctionTemplateDecl *FunTmpl =
7983 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007984 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007985 } else if (FunctionDecl *Fun
7986 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007987 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007988 }
7989 }
7990}
7991
John McCall1d318332010-01-12 00:44:57 +00007992/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7993/// "lead" diagnostic; it will be given two arguments, the source and
7994/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007995void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7996 Sema &S,
7997 SourceLocation CaretLoc,
7998 const PartialDiagnostic &PDiag) const {
7999 S.Diag(CaretLoc, PDiag)
8000 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00008001 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00008002 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8003 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008004 }
John McCall81201622010-01-08 04:41:39 +00008005}
8006
John McCall1d318332010-01-12 00:44:57 +00008007namespace {
8008
John McCalladbb8f82010-01-13 09:16:55 +00008009void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8010 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8011 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008012 assert(Cand->Function && "for now, candidate must be a function");
8013 FunctionDecl *Fn = Cand->Function;
8014
8015 // There's a conversion slot for the object argument if this is a
8016 // non-constructor method. Note that 'I' corresponds the
8017 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008018 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008019 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008020 if (I == 0)
8021 isObjectArgument = true;
8022 else
8023 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008024 }
8025
John McCall220ccbf2010-01-13 00:25:19 +00008026 std::string FnDesc;
8027 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8028
John McCalladbb8f82010-01-13 09:16:55 +00008029 Expr *FromExpr = Conv.Bad.FromExpr;
8030 QualType FromTy = Conv.Bad.getFromType();
8031 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008032
John McCall5920dbb2010-02-02 02:42:52 +00008033 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008034 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008035 Expr *E = FromExpr->IgnoreParens();
8036 if (isa<UnaryOperator>(E))
8037 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008038 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008039
8040 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8041 << (unsigned) FnKind << FnDesc
8042 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8043 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008044 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008045 return;
8046 }
8047
John McCall258b2032010-01-23 08:10:49 +00008048 // Do some hand-waving analysis to see if the non-viability is due
8049 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008050 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8051 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8052 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8053 CToTy = RT->getPointeeType();
8054 else {
8055 // TODO: detect and diagnose the full richness of const mismatches.
8056 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8057 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8058 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8059 }
8060
8061 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8062 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008063 Qualifiers FromQs = CFromTy.getQualifiers();
8064 Qualifiers ToQs = CToTy.getQualifiers();
8065
8066 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8068 << (unsigned) FnKind << FnDesc
8069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8070 << FromTy
8071 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8072 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008073 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008074 return;
8075 }
8076
John McCallf85e1932011-06-15 23:02:42 +00008077 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008079 << (unsigned) FnKind << FnDesc
8080 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8081 << FromTy
8082 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8083 << (unsigned) isObjectArgument << I+1;
8084 MaybeEmitInheritedConstructorNote(S, Fn);
8085 return;
8086 }
8087
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008088 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8090 << (unsigned) FnKind << FnDesc
8091 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8092 << FromTy
8093 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8094 << (unsigned) isObjectArgument << I+1;
8095 MaybeEmitInheritedConstructorNote(S, Fn);
8096 return;
8097 }
8098
John McCall651f3ee2010-01-14 03:28:57 +00008099 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8100 assert(CVR && "unexpected qualifiers mismatch");
8101
8102 if (isObjectArgument) {
8103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8104 << (unsigned) FnKind << FnDesc
8105 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8106 << FromTy << (CVR - 1);
8107 } else {
8108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8109 << (unsigned) FnKind << FnDesc
8110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8111 << FromTy << (CVR - 1) << I+1;
8112 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008113 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008114 return;
8115 }
8116
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008117 // Special diagnostic for failure to convert an initializer list, since
8118 // telling the user that it has type void is not useful.
8119 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8121 << (unsigned) FnKind << FnDesc
8122 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8123 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8124 MaybeEmitInheritedConstructorNote(S, Fn);
8125 return;
8126 }
8127
John McCall258b2032010-01-23 08:10:49 +00008128 // Diagnose references or pointers to incomplete types differently,
8129 // since it's far from impossible that the incompleteness triggered
8130 // the failure.
8131 QualType TempFromTy = FromTy.getNonReferenceType();
8132 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8133 TempFromTy = PTy->getPointeeType();
8134 if (TempFromTy->isIncompleteType()) {
8135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8136 << (unsigned) FnKind << FnDesc
8137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8138 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008139 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008140 return;
8141 }
8142
Douglas Gregor85789812010-06-30 23:01:39 +00008143 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008144 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008145 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8146 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8147 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8148 FromPtrTy->getPointeeType()) &&
8149 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8150 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008151 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008152 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008153 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008154 }
8155 } else if (const ObjCObjectPointerType *FromPtrTy
8156 = FromTy->getAs<ObjCObjectPointerType>()) {
8157 if (const ObjCObjectPointerType *ToPtrTy
8158 = ToTy->getAs<ObjCObjectPointerType>())
8159 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8160 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8161 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8162 FromPtrTy->getPointeeType()) &&
8163 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008164 BaseToDerivedConversion = 2;
8165 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008166 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8167 !FromTy->isIncompleteType() &&
8168 !ToRefTy->getPointeeType()->isIncompleteType() &&
8169 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8170 BaseToDerivedConversion = 3;
8171 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8172 ToTy.getNonReferenceType().getCanonicalType() ==
8173 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8175 << (unsigned) FnKind << FnDesc
8176 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8177 << (unsigned) isObjectArgument << I + 1;
8178 MaybeEmitInheritedConstructorNote(S, Fn);
8179 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008180 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008181 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008182
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008183 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008184 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008185 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008186 << (unsigned) FnKind << FnDesc
8187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008188 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008189 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008190 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008191 return;
8192 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008193
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008194 if (isa<ObjCObjectPointerType>(CFromTy) &&
8195 isa<PointerType>(CToTy)) {
8196 Qualifiers FromQs = CFromTy.getQualifiers();
8197 Qualifiers ToQs = CToTy.getQualifiers();
8198 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8200 << (unsigned) FnKind << FnDesc
8201 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8202 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8203 MaybeEmitInheritedConstructorNote(S, Fn);
8204 return;
8205 }
8206 }
8207
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008208 // Emit the generic diagnostic and, optionally, add the hints to it.
8209 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8210 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008211 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008212 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8213 << (unsigned) (Cand->Fix.Kind);
8214
8215 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008216 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8217 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008218 FDiag << *HI;
8219 S.Diag(Fn->getLocation(), FDiag);
8220
Sebastian Redlf677ea32011-02-05 19:23:19 +00008221 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008222}
8223
8224void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8225 unsigned NumFormalArgs) {
8226 // TODO: treat calls to a missing default constructor as a special case
8227
8228 FunctionDecl *Fn = Cand->Function;
8229 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8230
8231 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008232
Douglas Gregor439d3c32011-05-05 00:13:13 +00008233 // With invalid overloaded operators, it's possible that we think we
8234 // have an arity mismatch when it fact it looks like we have the
8235 // right number of arguments, because only overloaded operators have
8236 // the weird behavior of overloading member and non-member functions.
8237 // Just don't report anything.
8238 if (Fn->isInvalidDecl() &&
8239 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8240 return;
8241
John McCalladbb8f82010-01-13 09:16:55 +00008242 // at least / at most / exactly
8243 unsigned mode, modeCount;
8244 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008245 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8246 (Cand->FailureKind == ovl_fail_bad_deduction &&
8247 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008248 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008249 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008250 mode = 0; // "at least"
8251 else
8252 mode = 2; // "exactly"
8253 modeCount = MinParams;
8254 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008255 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8256 (Cand->FailureKind == ovl_fail_bad_deduction &&
8257 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008258 if (MinParams != FnTy->getNumArgs())
8259 mode = 1; // "at most"
8260 else
8261 mode = 2; // "exactly"
8262 modeCount = FnTy->getNumArgs();
8263 }
8264
8265 std::string Description;
8266 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8267
Richard Smithf7b80562012-05-11 05:16:41 +00008268 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8270 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8271 << Fn->getParamDecl(0) << NumFormalArgs;
8272 else
8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8274 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8275 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008276 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008277}
8278
John McCall342fec42010-02-01 18:53:26 +00008279/// Diagnose a failed template-argument deduction.
8280void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008281 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008282 FunctionDecl *Fn = Cand->Function; // pattern
8283
Douglas Gregora9333192010-05-08 17:41:32 +00008284 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008285 NamedDecl *ParamD;
8286 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8287 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8288 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008289 switch (Cand->DeductionFailure.Result) {
8290 case Sema::TDK_Success:
8291 llvm_unreachable("TDK_success while diagnosing bad deduction");
8292
8293 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008294 assert(ParamD && "no parameter found for incomplete deduction result");
8295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8296 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008297 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008298 return;
8299 }
8300
John McCall57e97782010-08-05 09:05:08 +00008301 case Sema::TDK_Underqualified: {
8302 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8303 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8304
8305 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8306
8307 // Param will have been canonicalized, but it should just be a
8308 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008309 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008310 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008311 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008312 assert(S.Context.hasSameType(Param, NonCanonParam));
8313
8314 // Arg has also been canonicalized, but there's nothing we can do
8315 // about that. It also doesn't matter as much, because it won't
8316 // have any template parameters in it (because deduction isn't
8317 // done on dependent types).
8318 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8319
8320 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8321 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008322 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008323 return;
8324 }
8325
8326 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008327 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008328 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008329 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008330 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008331 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008332 which = 1;
8333 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008334 which = 2;
8335 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008336
Douglas Gregora9333192010-05-08 17:41:32 +00008337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008338 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008339 << *Cand->DeductionFailure.getFirstArg()
8340 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008341 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008342 return;
8343 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008344
Douglas Gregorf1a84452010-05-08 19:15:54 +00008345 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008346 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008347 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008348 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008349 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8350 << ParamD->getDeclName();
8351 else {
8352 int index = 0;
8353 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8354 index = TTP->getIndex();
8355 else if (NonTypeTemplateParmDecl *NTTP
8356 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8357 index = NTTP->getIndex();
8358 else
8359 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008360 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008361 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8362 << (index + 1);
8363 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008364 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008365 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008366
Douglas Gregora18592e2010-05-08 18:13:28 +00008367 case Sema::TDK_TooManyArguments:
8368 case Sema::TDK_TooFewArguments:
8369 DiagnoseArityMismatch(S, Cand, NumArgs);
8370 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008371
8372 case Sema::TDK_InstantiationDepth:
8373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008374 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008375 return;
8376
8377 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008378 // Format the template argument list into the argument string.
8379 llvm::SmallString<128> TemplateArgString;
8380 if (TemplateArgumentList *Args =
8381 Cand->DeductionFailure.getTemplateArgumentList()) {
8382 TemplateArgString = " ";
8383 TemplateArgString += S.getTemplateArgumentBindingsText(
8384 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8385 }
8386
Richard Smith4493c0a2012-05-09 05:17:00 +00008387 // If this candidate was disabled by enable_if, say so.
8388 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8389 if (PDiag && PDiag->second.getDiagID() ==
8390 diag::err_typename_nested_not_found_enable_if) {
8391 // FIXME: Use the source range of the condition, and the fully-qualified
8392 // name of the enable_if template. These are both present in PDiag.
8393 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8394 << "'enable_if'" << TemplateArgString;
8395 return;
8396 }
8397
Richard Smithb8590f32012-05-07 09:03:25 +00008398 // Format the SFINAE diagnostic into the argument string.
8399 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8400 // formatted message in another diagnostic.
8401 llvm::SmallString<128> SFINAEArgString;
8402 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008403 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008404 SFINAEArgString = ": ";
8405 R = SourceRange(PDiag->first, PDiag->first);
8406 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8407 }
8408
Douglas Gregorec20f462010-05-08 20:07:26 +00008409 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008410 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008411 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008412 return;
8413 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008414
John McCall342fec42010-02-01 18:53:26 +00008415 // TODO: diagnose these individually, then kill off
8416 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008417 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008418 case Sema::TDK_FailedOverloadResolution:
8419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008420 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008421 return;
8422 }
8423}
8424
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008425/// CUDA: diagnose an invalid call across targets.
8426void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8427 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8428 FunctionDecl *Callee = Cand->Function;
8429
8430 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8431 CalleeTarget = S.IdentifyCUDATarget(Callee);
8432
8433 std::string FnDesc;
8434 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8435
8436 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8437 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8438}
8439
John McCall342fec42010-02-01 18:53:26 +00008440/// Generates a 'note' diagnostic for an overload candidate. We've
8441/// already generated a primary error at the call site.
8442///
8443/// It really does need to be a single diagnostic with its caret
8444/// pointed at the candidate declaration. Yes, this creates some
8445/// major challenges of technical writing. Yes, this makes pointing
8446/// out problems with specific arguments quite awkward. It's still
8447/// better than generating twenty screens of text for every failed
8448/// overload.
8449///
8450/// It would be great to be able to express per-candidate problems
8451/// more richly for those diagnostic clients that cared, but we'd
8452/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008453void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008454 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008455 FunctionDecl *Fn = Cand->Function;
8456
John McCall81201622010-01-08 04:41:39 +00008457 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008458 if (Cand->Viable && (Fn->isDeleted() ||
8459 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008460 std::string FnDesc;
8461 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008462
8463 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008464 << FnKind << FnDesc
8465 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008466 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008467 return;
John McCall81201622010-01-08 04:41:39 +00008468 }
8469
John McCall220ccbf2010-01-13 00:25:19 +00008470 // We don't really have anything else to say about viable candidates.
8471 if (Cand->Viable) {
8472 S.NoteOverloadCandidate(Fn);
8473 return;
8474 }
John McCall1d318332010-01-12 00:44:57 +00008475
John McCalladbb8f82010-01-13 09:16:55 +00008476 switch (Cand->FailureKind) {
8477 case ovl_fail_too_many_arguments:
8478 case ovl_fail_too_few_arguments:
8479 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008480
John McCalladbb8f82010-01-13 09:16:55 +00008481 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008482 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008483
John McCall717e8912010-01-23 05:17:32 +00008484 case ovl_fail_trivial_conversion:
8485 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008486 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008487 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008488
John McCallb1bdc622010-02-25 01:37:24 +00008489 case ovl_fail_bad_conversion: {
8490 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008491 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008492 if (Cand->Conversions[I].isBad())
8493 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008494
John McCalladbb8f82010-01-13 09:16:55 +00008495 // FIXME: this currently happens when we're called from SemaInit
8496 // when user-conversion overload fails. Figure out how to handle
8497 // those conditions and diagnose them well.
8498 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008499 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008500
8501 case ovl_fail_bad_target:
8502 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008503 }
John McCalla1d7d622010-01-08 00:58:21 +00008504}
8505
8506void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8507 // Desugar the type of the surrogate down to a function type,
8508 // retaining as many typedefs as possible while still showing
8509 // the function type (and, therefore, its parameter types).
8510 QualType FnType = Cand->Surrogate->getConversionType();
8511 bool isLValueReference = false;
8512 bool isRValueReference = false;
8513 bool isPointer = false;
8514 if (const LValueReferenceType *FnTypeRef =
8515 FnType->getAs<LValueReferenceType>()) {
8516 FnType = FnTypeRef->getPointeeType();
8517 isLValueReference = true;
8518 } else if (const RValueReferenceType *FnTypeRef =
8519 FnType->getAs<RValueReferenceType>()) {
8520 FnType = FnTypeRef->getPointeeType();
8521 isRValueReference = true;
8522 }
8523 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8524 FnType = FnTypePtr->getPointeeType();
8525 isPointer = true;
8526 }
8527 // Desugar down to a function type.
8528 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8529 // Reconstruct the pointer/reference as appropriate.
8530 if (isPointer) FnType = S.Context.getPointerType(FnType);
8531 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8532 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8533
8534 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8535 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008536 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008537}
8538
8539void NoteBuiltinOperatorCandidate(Sema &S,
8540 const char *Opc,
8541 SourceLocation OpLoc,
8542 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008543 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008544 std::string TypeStr("operator");
8545 TypeStr += Opc;
8546 TypeStr += "(";
8547 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008548 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008549 TypeStr += ")";
8550 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8551 } else {
8552 TypeStr += ", ";
8553 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8554 TypeStr += ")";
8555 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8556 }
8557}
8558
8559void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8560 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008561 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008562 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8563 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008564 if (ICS.isBad()) break; // all meaningless after first invalid
8565 if (!ICS.isAmbiguous()) continue;
8566
John McCall120d63c2010-08-24 20:38:10 +00008567 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008568 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008569 }
8570}
8571
John McCall1b77e732010-01-15 23:32:50 +00008572SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8573 if (Cand->Function)
8574 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008575 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008576 return Cand->Surrogate->getLocation();
8577 return SourceLocation();
8578}
8579
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008580static unsigned
8581RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008582 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008583 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008584 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008585
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008586 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008587 case Sema::TDK_Incomplete:
8588 return 1;
8589
8590 case Sema::TDK_Underqualified:
8591 case Sema::TDK_Inconsistent:
8592 return 2;
8593
8594 case Sema::TDK_SubstitutionFailure:
8595 case Sema::TDK_NonDeducedMismatch:
8596 return 3;
8597
8598 case Sema::TDK_InstantiationDepth:
8599 case Sema::TDK_FailedOverloadResolution:
8600 return 4;
8601
8602 case Sema::TDK_InvalidExplicitArguments:
8603 return 5;
8604
8605 case Sema::TDK_TooManyArguments:
8606 case Sema::TDK_TooFewArguments:
8607 return 6;
8608 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008609 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008610}
8611
John McCallbf65c0b2010-01-12 00:48:53 +00008612struct CompareOverloadCandidatesForDisplay {
8613 Sema &S;
8614 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008615
8616 bool operator()(const OverloadCandidate *L,
8617 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008618 // Fast-path this check.
8619 if (L == R) return false;
8620
John McCall81201622010-01-08 04:41:39 +00008621 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008622 if (L->Viable) {
8623 if (!R->Viable) return true;
8624
8625 // TODO: introduce a tri-valued comparison for overload
8626 // candidates. Would be more worthwhile if we had a sort
8627 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008628 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8629 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008630 } else if (R->Viable)
8631 return false;
John McCall81201622010-01-08 04:41:39 +00008632
John McCall1b77e732010-01-15 23:32:50 +00008633 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008634
John McCall1b77e732010-01-15 23:32:50 +00008635 // Criteria by which we can sort non-viable candidates:
8636 if (!L->Viable) {
8637 // 1. Arity mismatches come after other candidates.
8638 if (L->FailureKind == ovl_fail_too_many_arguments ||
8639 L->FailureKind == ovl_fail_too_few_arguments)
8640 return false;
8641 if (R->FailureKind == ovl_fail_too_many_arguments ||
8642 R->FailureKind == ovl_fail_too_few_arguments)
8643 return true;
John McCall81201622010-01-08 04:41:39 +00008644
John McCall717e8912010-01-23 05:17:32 +00008645 // 2. Bad conversions come first and are ordered by the number
8646 // of bad conversions and quality of good conversions.
8647 if (L->FailureKind == ovl_fail_bad_conversion) {
8648 if (R->FailureKind != ovl_fail_bad_conversion)
8649 return true;
8650
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008651 // The conversion that can be fixed with a smaller number of changes,
8652 // comes first.
8653 unsigned numLFixes = L->Fix.NumConversionsFixed;
8654 unsigned numRFixes = R->Fix.NumConversionsFixed;
8655 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8656 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008657 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008658 if (numLFixes < numRFixes)
8659 return true;
8660 else
8661 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008662 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008663
John McCall717e8912010-01-23 05:17:32 +00008664 // If there's any ordering between the defined conversions...
8665 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008666 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008667
8668 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008669 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008670 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008671 switch (CompareImplicitConversionSequences(S,
8672 L->Conversions[I],
8673 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008674 case ImplicitConversionSequence::Better:
8675 leftBetter++;
8676 break;
8677
8678 case ImplicitConversionSequence::Worse:
8679 leftBetter--;
8680 break;
8681
8682 case ImplicitConversionSequence::Indistinguishable:
8683 break;
8684 }
8685 }
8686 if (leftBetter > 0) return true;
8687 if (leftBetter < 0) return false;
8688
8689 } else if (R->FailureKind == ovl_fail_bad_conversion)
8690 return false;
8691
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008692 if (L->FailureKind == ovl_fail_bad_deduction) {
8693 if (R->FailureKind != ovl_fail_bad_deduction)
8694 return true;
8695
8696 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8697 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008698 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008699 } else if (R->FailureKind == ovl_fail_bad_deduction)
8700 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008701
John McCall1b77e732010-01-15 23:32:50 +00008702 // TODO: others?
8703 }
8704
8705 // Sort everything else by location.
8706 SourceLocation LLoc = GetLocationForCandidate(L);
8707 SourceLocation RLoc = GetLocationForCandidate(R);
8708
8709 // Put candidates without locations (e.g. builtins) at the end.
8710 if (LLoc.isInvalid()) return false;
8711 if (RLoc.isInvalid()) return true;
8712
8713 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008714 }
8715};
8716
John McCall717e8912010-01-23 05:17:32 +00008717/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008718/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008719void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008720 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008721 assert(!Cand->Viable);
8722
8723 // Don't do anything on failures other than bad conversion.
8724 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8725
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008726 // We only want the FixIts if all the arguments can be corrected.
8727 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008728 // Use a implicit copy initialization to check conversion fixes.
8729 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008730
John McCall717e8912010-01-23 05:17:32 +00008731 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008732 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008733 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008734 while (true) {
8735 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8736 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008737 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008738 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008739 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008740 }
John McCall717e8912010-01-23 05:17:32 +00008741 }
8742
8743 if (ConvIdx == ConvCount)
8744 return;
8745
John McCallb1bdc622010-02-25 01:37:24 +00008746 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8747 "remaining conversion is initialized?");
8748
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008749 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008750 // operation somehow.
8751 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008752
8753 const FunctionProtoType* Proto;
8754 unsigned ArgIdx = ConvIdx;
8755
8756 if (Cand->IsSurrogate) {
8757 QualType ConvType
8758 = Cand->Surrogate->getConversionType().getNonReferenceType();
8759 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8760 ConvType = ConvPtrType->getPointeeType();
8761 Proto = ConvType->getAs<FunctionProtoType>();
8762 ArgIdx--;
8763 } else if (Cand->Function) {
8764 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8765 if (isa<CXXMethodDecl>(Cand->Function) &&
8766 !isa<CXXConstructorDecl>(Cand->Function))
8767 ArgIdx--;
8768 } else {
8769 // Builtin binary operator with a bad first conversion.
8770 assert(ConvCount <= 3);
8771 for (; ConvIdx != ConvCount; ++ConvIdx)
8772 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008773 = TryCopyInitialization(S, Args[ConvIdx],
8774 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008775 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008776 /*InOverloadResolution*/ true,
8777 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008778 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008779 return;
8780 }
8781
8782 // Fill in the rest of the conversions.
8783 unsigned NumArgsInProto = Proto->getNumArgs();
8784 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008785 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008786 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008787 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008788 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008789 /*InOverloadResolution=*/true,
8790 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008791 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008792 // Store the FixIt in the candidate if it exists.
8793 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008794 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008795 }
John McCall717e8912010-01-23 05:17:32 +00008796 else
8797 Cand->Conversions[ConvIdx].setEllipsis();
8798 }
8799}
8800
John McCalla1d7d622010-01-08 00:58:21 +00008801} // end anonymous namespace
8802
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008803/// PrintOverloadCandidates - When overload resolution fails, prints
8804/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008805/// set.
John McCall120d63c2010-08-24 20:38:10 +00008806void OverloadCandidateSet::NoteCandidates(Sema &S,
8807 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008808 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008809 const char *Opc,
8810 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008811 // Sort the candidates by viability and position. Sorting directly would
8812 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008813 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008814 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8815 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008816 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008817 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008818 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008819 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008820 if (Cand->Function || Cand->IsSurrogate)
8821 Cands.push_back(Cand);
8822 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8823 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008824 }
8825 }
8826
John McCallbf65c0b2010-01-12 00:48:53 +00008827 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008828 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008829
John McCall1d318332010-01-12 00:44:57 +00008830 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008831
Chris Lattner5f9e2722011-07-23 10:55:15 +00008832 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008833 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8834 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008835 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008836 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8837 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008838
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008839 // Set an arbitrary limit on the number of candidate functions we'll spam
8840 // the user with. FIXME: This limit should depend on details of the
8841 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008842 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008843 break;
8844 }
8845 ++CandsShown;
8846
John McCalla1d7d622010-01-08 00:58:21 +00008847 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008848 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008849 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008850 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008851 else {
8852 assert(Cand->Viable &&
8853 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008854 // Generally we only see ambiguities including viable builtin
8855 // operators if overload resolution got screwed up by an
8856 // ambiguous user-defined conversion.
8857 //
8858 // FIXME: It's quite possible for different conversions to see
8859 // different ambiguities, though.
8860 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008861 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008862 ReportedAmbiguousConversions = true;
8863 }
John McCalla1d7d622010-01-08 00:58:21 +00008864
John McCall1d318332010-01-12 00:44:57 +00008865 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008866 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008867 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008868 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008869
8870 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008871 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008872}
8873
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008874// [PossiblyAFunctionType] --> [Return]
8875// NonFunctionType --> NonFunctionType
8876// R (A) --> R(A)
8877// R (*)(A) --> R (A)
8878// R (&)(A) --> R (A)
8879// R (S::*)(A) --> R (A)
8880QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8881 QualType Ret = PossiblyAFunctionType;
8882 if (const PointerType *ToTypePtr =
8883 PossiblyAFunctionType->getAs<PointerType>())
8884 Ret = ToTypePtr->getPointeeType();
8885 else if (const ReferenceType *ToTypeRef =
8886 PossiblyAFunctionType->getAs<ReferenceType>())
8887 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008888 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008889 PossiblyAFunctionType->getAs<MemberPointerType>())
8890 Ret = MemTypePtr->getPointeeType();
8891 Ret =
8892 Context.getCanonicalType(Ret).getUnqualifiedType();
8893 return Ret;
8894}
Douglas Gregor904eed32008-11-10 20:40:00 +00008895
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008896// A helper class to help with address of function resolution
8897// - allows us to avoid passing around all those ugly parameters
8898class AddressOfFunctionResolver
8899{
8900 Sema& S;
8901 Expr* SourceExpr;
8902 const QualType& TargetType;
8903 QualType TargetFunctionType; // Extracted function type from target type
8904
8905 bool Complain;
8906 //DeclAccessPair& ResultFunctionAccessPair;
8907 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008908
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008909 bool TargetTypeIsNonStaticMemberFunction;
8910 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008911
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008912 OverloadExpr::FindResult OvlExprInfo;
8913 OverloadExpr *OvlExpr;
8914 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008915 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008916
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008917public:
8918 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8919 const QualType& TargetType, bool Complain)
8920 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8921 Complain(Complain), Context(S.getASTContext()),
8922 TargetTypeIsNonStaticMemberFunction(
8923 !!TargetType->getAs<MemberPointerType>()),
8924 FoundNonTemplateFunction(false),
8925 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8926 OvlExpr(OvlExprInfo.Expression)
8927 {
8928 ExtractUnqualifiedFunctionTypeFromTargetType();
8929
8930 if (!TargetFunctionType->isFunctionType()) {
8931 if (OvlExpr->hasExplicitTemplateArgs()) {
8932 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008933 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008934 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008935
8936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8937 if (!Method->isStatic()) {
8938 // If the target type is a non-function type and the function
8939 // found is a non-static member function, pretend as if that was
8940 // the target, it's the only possible type to end up with.
8941 TargetTypeIsNonStaticMemberFunction = true;
8942
8943 // And skip adding the function if its not in the proper form.
8944 // We'll diagnose this due to an empty set of functions.
8945 if (!OvlExprInfo.HasFormOfMemberPointer)
8946 return;
8947 }
8948 }
8949
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008950 Matches.push_back(std::make_pair(dap,Fn));
8951 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008952 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008953 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008954 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008955
8956 if (OvlExpr->hasExplicitTemplateArgs())
8957 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008958
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008959 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8960 // C++ [over.over]p4:
8961 // If more than one function is selected, [...]
8962 if (Matches.size() > 1) {
8963 if (FoundNonTemplateFunction)
8964 EliminateAllTemplateMatches();
8965 else
8966 EliminateAllExceptMostSpecializedTemplate();
8967 }
8968 }
8969 }
8970
8971private:
8972 bool isTargetTypeAFunction() const {
8973 return TargetFunctionType->isFunctionType();
8974 }
8975
8976 // [ToType] [Return]
8977
8978 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8979 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8980 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8981 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8982 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8983 }
8984
8985 // return true if any matching specializations were found
8986 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8987 const DeclAccessPair& CurAccessFunPair) {
8988 if (CXXMethodDecl *Method
8989 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8990 // Skip non-static function templates when converting to pointer, and
8991 // static when converting to member pointer.
8992 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8993 return false;
8994 }
8995 else if (TargetTypeIsNonStaticMemberFunction)
8996 return false;
8997
8998 // C++ [over.over]p2:
8999 // If the name is a function template, template argument deduction is
9000 // done (14.8.2.2), and if the argument deduction succeeds, the
9001 // resulting template argument list is used to generate a single
9002 // function template specialization, which is added to the set of
9003 // overloaded functions considered.
9004 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009005 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009006 if (Sema::TemplateDeductionResult Result
9007 = S.DeduceTemplateArguments(FunctionTemplate,
9008 &OvlExplicitTemplateArgs,
9009 TargetFunctionType, Specialization,
9010 Info)) {
9011 // FIXME: make a note of the failed deduction for diagnostics.
9012 (void)Result;
9013 return false;
9014 }
9015
9016 // Template argument deduction ensures that we have an exact match.
9017 // This function template specicalization works.
9018 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9019 assert(TargetFunctionType
9020 == Context.getCanonicalType(Specialization->getType()));
9021 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9022 return true;
9023 }
9024
9025 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9026 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009028 // Skip non-static functions when converting to pointer, and static
9029 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009030 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9031 return false;
9032 }
9033 else if (TargetTypeIsNonStaticMemberFunction)
9034 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009035
Chandler Carruthbd647292009-12-29 06:17:27 +00009036 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009037 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009038 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9039 if (S.CheckCUDATarget(Caller, FunDecl))
9040 return false;
9041
Douglas Gregor43c79c22009-12-09 00:47:37 +00009042 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009043 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9044 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009045 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9046 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009047 Matches.push_back(std::make_pair(CurAccessFunPair,
9048 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009049 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009050 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009051 }
Mike Stump1eb44332009-09-09 15:08:12 +00009052 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009053
9054 return false;
9055 }
9056
9057 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9058 bool Ret = false;
9059
9060 // If the overload expression doesn't have the form of a pointer to
9061 // member, don't try to convert it to a pointer-to-member type.
9062 if (IsInvalidFormOfPointerToMemberFunction())
9063 return false;
9064
9065 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9066 E = OvlExpr->decls_end();
9067 I != E; ++I) {
9068 // Look through any using declarations to find the underlying function.
9069 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9070
9071 // C++ [over.over]p3:
9072 // Non-member functions and static member functions match
9073 // targets of type "pointer-to-function" or "reference-to-function."
9074 // Nonstatic member functions match targets of
9075 // type "pointer-to-member-function."
9076 // Note that according to DR 247, the containing class does not matter.
9077 if (FunctionTemplateDecl *FunctionTemplate
9078 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9079 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9080 Ret = true;
9081 }
9082 // If we have explicit template arguments supplied, skip non-templates.
9083 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9084 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9085 Ret = true;
9086 }
9087 assert(Ret || Matches.empty());
9088 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009089 }
9090
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009091 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009092 // [...] and any given function template specialization F1 is
9093 // eliminated if the set contains a second function template
9094 // specialization whose function template is more specialized
9095 // than the function template of F1 according to the partial
9096 // ordering rules of 14.5.5.2.
9097
9098 // The algorithm specified above is quadratic. We instead use a
9099 // two-pass algorithm (similar to the one used to identify the
9100 // best viable function in an overload set) that identifies the
9101 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009102
9103 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9104 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9105 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009106
John McCallc373d482010-01-27 01:50:18 +00009107 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009108 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9109 TPOC_Other, 0, SourceExpr->getLocStart(),
9110 S.PDiag(),
9111 S.PDiag(diag::err_addr_ovl_ambiguous)
9112 << Matches[0].second->getDeclName(),
9113 S.PDiag(diag::note_ovl_candidate)
9114 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009115 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009116
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009117 if (Result != MatchesCopy.end()) {
9118 // Make it the first and only element
9119 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9120 Matches[0].second = cast<FunctionDecl>(*Result);
9121 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009122 }
9123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009124
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009125 void EliminateAllTemplateMatches() {
9126 // [...] any function template specializations in the set are
9127 // eliminated if the set also contains a non-template function, [...]
9128 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9129 if (Matches[I].second->getPrimaryTemplate() == 0)
9130 ++I;
9131 else {
9132 Matches[I] = Matches[--N];
9133 Matches.set_size(N);
9134 }
9135 }
9136 }
9137
9138public:
9139 void ComplainNoMatchesFound() const {
9140 assert(Matches.empty());
9141 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9142 << OvlExpr->getName() << TargetFunctionType
9143 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009144 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009145 }
9146
9147 bool IsInvalidFormOfPointerToMemberFunction() const {
9148 return TargetTypeIsNonStaticMemberFunction &&
9149 !OvlExprInfo.HasFormOfMemberPointer;
9150 }
9151
9152 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9153 // TODO: Should we condition this on whether any functions might
9154 // have matched, or is it more appropriate to do that in callers?
9155 // TODO: a fixit wouldn't hurt.
9156 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9157 << TargetType << OvlExpr->getSourceRange();
9158 }
9159
9160 void ComplainOfInvalidConversion() const {
9161 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9162 << OvlExpr->getName() << TargetType;
9163 }
9164
9165 void ComplainMultipleMatchesFound() const {
9166 assert(Matches.size() > 1);
9167 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9168 << OvlExpr->getName()
9169 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009170 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009171 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009172
9173 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9174
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009175 int getNumMatches() const { return Matches.size(); }
9176
9177 FunctionDecl* getMatchingFunctionDecl() const {
9178 if (Matches.size() != 1) return 0;
9179 return Matches[0].second;
9180 }
9181
9182 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9183 if (Matches.size() != 1) return 0;
9184 return &Matches[0].first;
9185 }
9186};
9187
9188/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9189/// an overloaded function (C++ [over.over]), where @p From is an
9190/// expression with overloaded function type and @p ToType is the type
9191/// we're trying to resolve to. For example:
9192///
9193/// @code
9194/// int f(double);
9195/// int f(int);
9196///
9197/// int (*pfd)(double) = f; // selects f(double)
9198/// @endcode
9199///
9200/// This routine returns the resulting FunctionDecl if it could be
9201/// resolved, and NULL otherwise. When @p Complain is true, this
9202/// routine will emit diagnostics if there is an error.
9203FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009204Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9205 QualType TargetType,
9206 bool Complain,
9207 DeclAccessPair &FoundResult,
9208 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009209 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009210
9211 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9212 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009213 int NumMatches = Resolver.getNumMatches();
9214 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009215 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009216 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9217 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9218 else
9219 Resolver.ComplainNoMatchesFound();
9220 }
9221 else if (NumMatches > 1 && Complain)
9222 Resolver.ComplainMultipleMatchesFound();
9223 else if (NumMatches == 1) {
9224 Fn = Resolver.getMatchingFunctionDecl();
9225 assert(Fn);
9226 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009227 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009228 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009229 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009230 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009231
9232 if (pHadMultipleCandidates)
9233 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009234 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009235}
9236
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009237/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009238/// resolve that overloaded function expression down to a single function.
9239///
9240/// This routine can only resolve template-ids that refer to a single function
9241/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009242/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009243/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009244FunctionDecl *
9245Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9246 bool Complain,
9247 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009248 // C++ [over.over]p1:
9249 // [...] [Note: any redundant set of parentheses surrounding the
9250 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009251 // C++ [over.over]p1:
9252 // [...] The overloaded function name can be preceded by the &
9253 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009254
Douglas Gregor4b52e252009-12-21 23:17:24 +00009255 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009256 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009257 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009258
9259 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009260 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009261
Douglas Gregor4b52e252009-12-21 23:17:24 +00009262 // Look through all of the overloaded functions, searching for one
9263 // whose type matches exactly.
9264 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009265 for (UnresolvedSetIterator I = ovl->decls_begin(),
9266 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009267 // C++0x [temp.arg.explicit]p3:
9268 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009269 // where deduction is not done, if a template argument list is
9270 // specified and it, along with any default template arguments,
9271 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009272 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009273 FunctionTemplateDecl *FunctionTemplate
9274 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009275
Douglas Gregor4b52e252009-12-21 23:17:24 +00009276 // C++ [over.over]p2:
9277 // If the name is a function template, template argument deduction is
9278 // done (14.8.2.2), and if the argument deduction succeeds, the
9279 // resulting template argument list is used to generate a single
9280 // function template specialization, which is added to the set of
9281 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009282 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009283 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009284 if (TemplateDeductionResult Result
9285 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9286 Specialization, Info)) {
9287 // FIXME: make a note of the failed deduction for diagnostics.
9288 (void)Result;
9289 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009290 }
9291
John McCall864c0412011-04-26 20:42:42 +00009292 assert(Specialization && "no specialization and no error?");
9293
Douglas Gregor4b52e252009-12-21 23:17:24 +00009294 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009295 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009296 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009297 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9298 << ovl->getName();
9299 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009300 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009301 return 0;
John McCall864c0412011-04-26 20:42:42 +00009302 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009303
John McCall864c0412011-04-26 20:42:42 +00009304 Matched = Specialization;
9305 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009307
Douglas Gregor4b52e252009-12-21 23:17:24 +00009308 return Matched;
9309}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009310
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009311
9312
9313
John McCall6dbba4f2011-10-11 23:14:30 +00009314// Resolve and fix an overloaded expression that can be resolved
9315// because it identifies a single function template specialization.
9316//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009317// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009318//
9319// Return true if it was logically possible to so resolve the
9320// expression, regardless of whether or not it succeeded. Always
9321// returns true if 'complain' is set.
9322bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9323 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9324 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009325 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009326 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009327 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009328
John McCall6dbba4f2011-10-11 23:14:30 +00009329 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009330
John McCall864c0412011-04-26 20:42:42 +00009331 DeclAccessPair found;
9332 ExprResult SingleFunctionExpression;
9333 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9334 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009335 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009336 SrcExpr = ExprError();
9337 return true;
9338 }
John McCall864c0412011-04-26 20:42:42 +00009339
9340 // It is only correct to resolve to an instance method if we're
9341 // resolving a form that's permitted to be a pointer to member.
9342 // Otherwise we'll end up making a bound member expression, which
9343 // is illegal in all the contexts we resolve like this.
9344 if (!ovl.HasFormOfMemberPointer &&
9345 isa<CXXMethodDecl>(fn) &&
9346 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009347 if (!complain) return false;
9348
9349 Diag(ovl.Expression->getExprLoc(),
9350 diag::err_bound_member_function)
9351 << 0 << ovl.Expression->getSourceRange();
9352
9353 // TODO: I believe we only end up here if there's a mix of
9354 // static and non-static candidates (otherwise the expression
9355 // would have 'bound member' type, not 'overload' type).
9356 // Ideally we would note which candidate was chosen and why
9357 // the static candidates were rejected.
9358 SrcExpr = ExprError();
9359 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009360 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009361
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009362 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009363 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009364 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009365
9366 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009367 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009368 SingleFunctionExpression =
9369 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009370 if (SingleFunctionExpression.isInvalid()) {
9371 SrcExpr = ExprError();
9372 return true;
9373 }
9374 }
John McCall864c0412011-04-26 20:42:42 +00009375 }
9376
9377 if (!SingleFunctionExpression.isUsable()) {
9378 if (complain) {
9379 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9380 << ovl.Expression->getName()
9381 << DestTypeForComplaining
9382 << OpRangeForComplaining
9383 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009384 NoteAllOverloadCandidates(SrcExpr.get());
9385
9386 SrcExpr = ExprError();
9387 return true;
9388 }
9389
9390 return false;
John McCall864c0412011-04-26 20:42:42 +00009391 }
9392
John McCall6dbba4f2011-10-11 23:14:30 +00009393 SrcExpr = SingleFunctionExpression;
9394 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009395}
9396
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009397/// \brief Add a single candidate to the overload set.
9398static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009399 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009400 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009401 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009402 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009403 bool PartialOverloading,
9404 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009405 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009406 if (isa<UsingShadowDecl>(Callee))
9407 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9408
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009409 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009410 if (ExplicitTemplateArgs) {
9411 assert(!KnownValid && "Explicit template arguments?");
9412 return;
9413 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009414 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9415 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009416 return;
John McCallba135432009-11-21 08:51:07 +00009417 }
9418
9419 if (FunctionTemplateDecl *FuncTemplate
9420 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009421 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009422 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009423 return;
9424 }
9425
Richard Smith2ced0442011-06-26 22:19:54 +00009426 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009427}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009428
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009429/// \brief Add the overload candidates named by callee and/or found by argument
9430/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009431void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009432 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009433 OverloadCandidateSet &CandidateSet,
9434 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009435
9436#ifndef NDEBUG
9437 // Verify that ArgumentDependentLookup is consistent with the rules
9438 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009439 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009440 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9441 // and let Y be the lookup set produced by argument dependent
9442 // lookup (defined as follows). If X contains
9443 //
9444 // -- a declaration of a class member, or
9445 //
9446 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009447 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009448 //
9449 // -- a declaration that is neither a function or a function
9450 // template
9451 //
9452 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009453
John McCall3b4294e2009-12-16 12:17:52 +00009454 if (ULE->requiresADL()) {
9455 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9456 E = ULE->decls_end(); I != E; ++I) {
9457 assert(!(*I)->getDeclContext()->isRecord());
9458 assert(isa<UsingShadowDecl>(*I) ||
9459 !(*I)->getDeclContext()->isFunctionOrMethod());
9460 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009461 }
9462 }
9463#endif
9464
John McCall3b4294e2009-12-16 12:17:52 +00009465 // It would be nice to avoid this copy.
9466 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009467 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009468 if (ULE->hasExplicitTemplateArgs()) {
9469 ULE->copyTemplateArgumentsInto(TABuffer);
9470 ExplicitTemplateArgs = &TABuffer;
9471 }
9472
9473 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9474 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009475 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9476 CandidateSet, PartialOverloading,
9477 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009478
John McCall3b4294e2009-12-16 12:17:52 +00009479 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009480 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009481 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009482 Args, ExplicitTemplateArgs,
9483 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009484 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009485}
John McCall578b69b2009-12-16 08:11:27 +00009486
Richard Smithf50e88a2011-06-05 22:42:48 +00009487/// Attempt to recover from an ill-formed use of a non-dependent name in a
9488/// template, where the non-dependent name was declared after the template
9489/// was defined. This is common in code written for a compilers which do not
9490/// correctly implement two-stage name lookup.
9491///
9492/// Returns true if a viable candidate was found and a diagnostic was issued.
9493static bool
9494DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9495 const CXXScopeSpec &SS, LookupResult &R,
9496 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009497 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009498 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9499 return false;
9500
9501 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009502 if (DC->isTransparentContext())
9503 continue;
9504
Richard Smithf50e88a2011-06-05 22:42:48 +00009505 SemaRef.LookupQualifiedName(R, DC);
9506
9507 if (!R.empty()) {
9508 R.suppressDiagnostics();
9509
9510 if (isa<CXXRecordDecl>(DC)) {
9511 // Don't diagnose names we find in classes; we get much better
9512 // diagnostics for these from DiagnoseEmptyLookup.
9513 R.clear();
9514 return false;
9515 }
9516
9517 OverloadCandidateSet Candidates(FnLoc);
9518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9519 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009520 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009521 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009522
9523 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009524 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009525 // No viable functions. Don't bother the user with notes for functions
9526 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009527 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009528 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009529 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009530
9531 // Find the namespaces where ADL would have looked, and suggest
9532 // declaring the function there instead.
9533 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9534 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009535 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009536 AssociatedNamespaces,
9537 AssociatedClasses);
9538 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009539 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009540 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009541 for (Sema::AssociatedNamespaceSet::iterator
9542 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009543 end = AssociatedNamespaces.end(); it != end; ++it) {
9544 if (!Std->Encloses(*it))
9545 SuggestedNamespaces.insert(*it);
9546 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009547 } else {
9548 // Lacking the 'std::' namespace, use all of the associated namespaces.
9549 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009550 }
9551
9552 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9553 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009554 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009555 SemaRef.Diag(Best->Function->getLocation(),
9556 diag::note_not_found_by_two_phase_lookup)
9557 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009558 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009559 SemaRef.Diag(Best->Function->getLocation(),
9560 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009561 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009562 } else {
9563 // FIXME: It would be useful to list the associated namespaces here,
9564 // but the diagnostics infrastructure doesn't provide a way to produce
9565 // a localized representation of a list of items.
9566 SemaRef.Diag(Best->Function->getLocation(),
9567 diag::note_not_found_by_two_phase_lookup)
9568 << R.getLookupName() << 2;
9569 }
9570
9571 // Try to recover by calling this function.
9572 return true;
9573 }
9574
9575 R.clear();
9576 }
9577
9578 return false;
9579}
9580
9581/// Attempt to recover from ill-formed use of a non-dependent operator in a
9582/// template, where the non-dependent operator was declared after the template
9583/// was defined.
9584///
9585/// Returns true if a viable candidate was found and a diagnostic was issued.
9586static bool
9587DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9588 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009589 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009590 DeclarationName OpName =
9591 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9592 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9593 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009594 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009595}
9596
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009597namespace {
9598// Callback to limit the allowed keywords and to only accept typo corrections
9599// that are keywords or whose decls refer to functions (or template functions)
9600// that accept the given number of arguments.
9601class RecoveryCallCCC : public CorrectionCandidateCallback {
9602 public:
9603 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9604 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009605 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009606 WantRemainingKeywords = false;
9607 }
9608
9609 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9610 if (!candidate.getCorrectionDecl())
9611 return candidate.isKeyword();
9612
9613 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9614 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9615 FunctionDecl *FD = 0;
9616 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9617 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9618 FD = FTD->getTemplatedDecl();
9619 if (!HasExplicitTemplateArgs && !FD) {
9620 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9621 // If the Decl is neither a function nor a template function,
9622 // determine if it is a pointer or reference to a function. If so,
9623 // check against the number of arguments expected for the pointee.
9624 QualType ValType = cast<ValueDecl>(ND)->getType();
9625 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9626 ValType = ValType->getPointeeType();
9627 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9628 if (FPT->getNumArgs() == NumArgs)
9629 return true;
9630 }
9631 }
9632 if (FD && FD->getNumParams() >= NumArgs &&
9633 FD->getMinRequiredArguments() <= NumArgs)
9634 return true;
9635 }
9636 return false;
9637 }
9638
9639 private:
9640 unsigned NumArgs;
9641 bool HasExplicitTemplateArgs;
9642};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009643
9644// Callback that effectively disabled typo correction
9645class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9646 public:
9647 NoTypoCorrectionCCC() {
9648 WantTypeSpecifiers = false;
9649 WantExpressionKeywords = false;
9650 WantCXXNamedCasts = false;
9651 WantRemainingKeywords = false;
9652 }
9653
9654 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9655 return false;
9656 }
9657};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009658}
9659
John McCall578b69b2009-12-16 08:11:27 +00009660/// Attempts to recover from a call where no functions were found.
9661///
9662/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009663static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009664BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009665 UnresolvedLookupExpr *ULE,
9666 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009667 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009668 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009669 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009670
9671 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009672 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009673 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009674
John McCall3b4294e2009-12-16 12:17:52 +00009675 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009676 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009677 if (ULE->hasExplicitTemplateArgs()) {
9678 ULE->copyTemplateArgumentsInto(TABuffer);
9679 ExplicitTemplateArgs = &TABuffer;
9680 }
9681
John McCall578b69b2009-12-16 08:11:27 +00009682 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9683 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009684 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009685 NoTypoCorrectionCCC RejectAll;
9686 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9687 (CorrectionCandidateCallback*)&Validator :
9688 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009689 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009690 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009691 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009692 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009693 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009694 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009695
John McCall3b4294e2009-12-16 12:17:52 +00009696 assert(!R.empty() && "lookup results empty despite recovery");
9697
9698 // Build an implicit member call if appropriate. Just drop the
9699 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009700 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009701 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009702 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9703 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009704 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009705 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009706 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009707 else
9708 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9709
9710 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009711 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009712
9713 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009714 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009715 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009716 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009717 MultiExprArg(Args.data(), Args.size()),
9718 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009719}
Douglas Gregord7a95972010-06-08 17:35:15 +00009720
Sam Panzere1715b62012-08-21 00:52:01 +00009721/// \brief Constructs and populates an OverloadedCandidateSet from
9722/// the given function.
9723/// \returns true when an the ExprResult output parameter has been set.
9724bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9725 UnresolvedLookupExpr *ULE,
9726 Expr **Args, unsigned NumArgs,
9727 SourceLocation RParenLoc,
9728 OverloadCandidateSet *CandidateSet,
9729 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009730#ifndef NDEBUG
9731 if (ULE->requiresADL()) {
9732 // To do ADL, we must have found an unqualified name.
9733 assert(!ULE->getQualifier() && "qualified name with ADL");
9734
9735 // We don't perform ADL for implicit declarations of builtins.
9736 // Verify that this was correctly set up.
9737 FunctionDecl *F;
9738 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9739 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9740 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009741 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009742
John McCall3b4294e2009-12-16 12:17:52 +00009743 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009744 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009745 } else
9746 assert(!ULE->isStdAssociatedNamespace() &&
9747 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009748#endif
9749
John McCall5acb0c92011-10-17 18:40:02 +00009750 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009751 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9752 *Result = ExprError();
9753 return true;
9754 }
Douglas Gregor17330012009-02-04 15:01:18 +00009755
John McCall3b4294e2009-12-16 12:17:52 +00009756 // Add the functions denoted by the callee to the set of candidate
9757 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009758 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009759 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009760
9761 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009762 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9763 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009764 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009765 // In Microsoft mode, if we are inside a template class member function then
9766 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009767 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009768 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009769 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009770 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009771 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9772 llvm::makeArrayRef(Args, NumArgs),
9773 Context.DependentTy, VK_RValue,
9774 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009775 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009776 *Result = Owned(CE);
9777 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009778 }
Sam Panzere1715b62012-08-21 00:52:01 +00009779 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009780 }
John McCall578b69b2009-12-16 08:11:27 +00009781
John McCall5acb0c92011-10-17 18:40:02 +00009782 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009783 return false;
9784}
John McCall5acb0c92011-10-17 18:40:02 +00009785
Sam Panzere1715b62012-08-21 00:52:01 +00009786/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9787/// the completed call expression. If overload resolution fails, emits
9788/// diagnostics and returns ExprError()
9789static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9790 UnresolvedLookupExpr *ULE,
9791 SourceLocation LParenLoc,
9792 Expr **Args, unsigned NumArgs,
9793 SourceLocation RParenLoc,
9794 Expr *ExecConfig,
9795 OverloadCandidateSet *CandidateSet,
9796 OverloadCandidateSet::iterator *Best,
9797 OverloadingResult OverloadResult,
9798 bool AllowTypoCorrection) {
9799 if (CandidateSet->empty())
9800 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9801 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9802 RParenLoc, /*EmptyLookup=*/true,
9803 AllowTypoCorrection);
9804
9805 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009806 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009807 FunctionDecl *FDecl = (*Best)->Function;
9808 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9809 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9810 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9811 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9812 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9813 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009814 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009815
Richard Smithf50e88a2011-06-05 22:42:48 +00009816 case OR_No_Viable_Function: {
9817 // Try to recover by looking for viable functions which the user might
9818 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009819 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009820 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9821 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009822 /*EmptyLookup=*/false,
9823 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009824 if (!Recovery.isInvalid())
9825 return Recovery;
9826
Sam Panzere1715b62012-08-21 00:52:01 +00009827 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009828 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009829 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009830 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9831 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009832 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009833 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009834
9835 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009836 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009837 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009838 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9839 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009840 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009841
Sam Panzere1715b62012-08-21 00:52:01 +00009842 case OR_Deleted: {
9843 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9844 << (*Best)->Function->isDeleted()
9845 << ULE->getName()
9846 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9847 << Fn->getSourceRange();
9848 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9849 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009850
Sam Panzere1715b62012-08-21 00:52:01 +00009851 // We emitted an error for the unvailable/deleted function call but keep
9852 // the call in the AST.
9853 FunctionDecl *FDecl = (*Best)->Function;
9854 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9855 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9856 RParenLoc, ExecConfig);
9857 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009858 }
9859
Douglas Gregorff331c12010-07-25 18:17:45 +00009860 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009861 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009862}
9863
Sam Panzere1715b62012-08-21 00:52:01 +00009864/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9865/// (which eventually refers to the declaration Func) and the call
9866/// arguments Args/NumArgs, attempt to resolve the function call down
9867/// to a specific function. If overload resolution succeeds, returns
9868/// the call expression produced by overload resolution.
9869/// Otherwise, emits diagnostics and returns ExprError.
9870ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9871 UnresolvedLookupExpr *ULE,
9872 SourceLocation LParenLoc,
9873 Expr **Args, unsigned NumArgs,
9874 SourceLocation RParenLoc,
9875 Expr *ExecConfig,
9876 bool AllowTypoCorrection) {
9877 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9878 ExprResult result;
9879
9880 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9881 &CandidateSet, &result))
9882 return result;
9883
9884 OverloadCandidateSet::iterator Best;
9885 OverloadingResult OverloadResult =
9886 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9887
9888 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9889 RParenLoc, ExecConfig, &CandidateSet,
9890 &Best, OverloadResult,
9891 AllowTypoCorrection);
9892}
9893
John McCall6e266892010-01-26 03:27:55 +00009894static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009895 return Functions.size() > 1 ||
9896 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9897}
9898
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009899/// \brief Create a unary operation that may resolve to an overloaded
9900/// operator.
9901///
9902/// \param OpLoc The location of the operator itself (e.g., '*').
9903///
9904/// \param OpcIn The UnaryOperator::Opcode that describes this
9905/// operator.
9906///
James Dennett40ae6662012-06-22 08:52:37 +00009907/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009908/// considered by overload resolution. The caller needs to build this
9909/// set based on the context using, e.g.,
9910/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9911/// set should not contain any member functions; those will be added
9912/// by CreateOverloadedUnaryOp().
9913///
James Dennett8da16872012-06-22 10:32:46 +00009914/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009915ExprResult
John McCall6e266892010-01-26 03:27:55 +00009916Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9917 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009918 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009919 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009920
9921 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9922 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9923 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009924 // TODO: provide better source location info.
9925 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009926
John McCall5acb0c92011-10-17 18:40:02 +00009927 if (checkPlaceholderForOverload(*this, Input))
9928 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009929
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009930 Expr *Args[2] = { Input, 0 };
9931 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009932
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009933 // For post-increment and post-decrement, add the implicit '0' as
9934 // the second argument, so that we know this is a post-increment or
9935 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009936 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009937 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009938 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9939 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009940 NumArgs = 2;
9941 }
9942
9943 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009944 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009945 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009946 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009947 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009948 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009949 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009950
John McCallc373d482010-01-27 01:50:18 +00009951 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009952 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009953 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009954 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009955 /*ADL*/ true, IsOverloaded(Fns),
9956 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009957 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009958 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009959 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009960 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009961 OpLoc));
9962 }
9963
9964 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009965 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009966
9967 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009968 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9969 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009970
9971 // Add operator candidates that are member functions.
9972 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9973
John McCall6e266892010-01-26 03:27:55 +00009974 // Add candidates from ADL.
9975 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009976 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009977 /*ExplicitTemplateArgs*/ 0,
9978 CandidateSet);
9979
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009980 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009981 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009982
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9984
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009985 // Perform overload resolution.
9986 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009987 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009988 case OR_Success: {
9989 // We found a built-in operator or an overloaded operator.
9990 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009991
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009992 if (FnDecl) {
9993 // We matched an overloaded operator. Build a call to that
9994 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009995
Eli Friedman5f2987c2012-02-02 03:46:19 +00009996 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009997
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009998 // Convert the arguments.
9999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010000 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010001
John Wiegley429bb272011-04-08 18:41:53 +000010002 ExprResult InputRes =
10003 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10004 Best->FoundDecl, Method);
10005 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010006 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010007 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010008 } else {
10009 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010010 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010011 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010012 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010013 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010014 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010015 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010016 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010017 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010018 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010019 }
10020
John McCallb697e082010-05-06 18:15:07 +000010021 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10022
John McCallf89e55a2010-11-18 06:31:45 +000010023 // Determine the result type.
10024 QualType ResultTy = FnDecl->getResultType();
10025 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10026 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010027
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010028 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010029 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010030 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010031 if (FnExpr.isInvalid())
10032 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010033
Eli Friedman4c3b8962009-11-18 03:58:17 +000010034 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010035 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010036 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010037 llvm::makeArrayRef(Args, NumArgs),
10038 ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +000010039
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010040 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010041 FnDecl))
10042 return ExprError();
10043
John McCall9ae2f072010-08-23 23:25:46 +000010044 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010045 } else {
10046 // We matched a built-in operator. Convert the arguments, then
10047 // break out so that we will build the appropriate built-in
10048 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010049 ExprResult InputRes =
10050 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10051 Best->Conversions[0], AA_Passing);
10052 if (InputRes.isInvalid())
10053 return ExprError();
10054 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010055 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010056 }
John Wiegley429bb272011-04-08 18:41:53 +000010057 }
10058
10059 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010060 // This is an erroneous use of an operator which can be overloaded by
10061 // a non-member function. Check for non-member operators which were
10062 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010063 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10064 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010065 // FIXME: Recover by calling the found function.
10066 return ExprError();
10067
John Wiegley429bb272011-04-08 18:41:53 +000010068 // No viable function; fall through to handling this as a
10069 // built-in operator, which will produce an error message for us.
10070 break;
10071
10072 case OR_Ambiguous:
10073 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10074 << UnaryOperator::getOpcodeStr(Opc)
10075 << Input->getType()
10076 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010077 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10078 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010079 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10080 return ExprError();
10081
10082 case OR_Deleted:
10083 Diag(OpLoc, diag::err_ovl_deleted_oper)
10084 << Best->Function->isDeleted()
10085 << UnaryOperator::getOpcodeStr(Opc)
10086 << getDeletedOrUnavailableSuffix(Best->Function)
10087 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010088 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10089 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010090 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010091 return ExprError();
10092 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010093
10094 // Either we found no viable overloaded operator or we matched a
10095 // built-in operator. In either case, fall through to trying to
10096 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010097 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010098}
10099
Douglas Gregor063daf62009-03-13 18:40:31 +000010100/// \brief Create a binary operation that may resolve to an overloaded
10101/// operator.
10102///
10103/// \param OpLoc The location of the operator itself (e.g., '+').
10104///
10105/// \param OpcIn The BinaryOperator::Opcode that describes this
10106/// operator.
10107///
James Dennett40ae6662012-06-22 08:52:37 +000010108/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010109/// considered by overload resolution. The caller needs to build this
10110/// set based on the context using, e.g.,
10111/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10112/// set should not contain any member functions; those will be added
10113/// by CreateOverloadedBinOp().
10114///
10115/// \param LHS Left-hand argument.
10116/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010117ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010118Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010119 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010120 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010121 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010122 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010123 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010124
10125 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10126 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10127 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10128
10129 // If either side is type-dependent, create an appropriate dependent
10130 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010131 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010132 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010133 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010134 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010135 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010136 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010137 Context.DependentTy,
10138 VK_RValue, OK_Ordinary,
10139 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010140
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010141 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10142 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010143 VK_LValue,
10144 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010145 Context.DependentTy,
10146 Context.DependentTy,
10147 OpLoc));
10148 }
John McCall6e266892010-01-26 03:27:55 +000010149
10150 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010151 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010152 // TODO: provide better source location info in DNLoc component.
10153 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010154 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010155 = UnresolvedLookupExpr::Create(Context, NamingClass,
10156 NestedNameSpecifierLoc(), OpNameInfo,
10157 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010158 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +000010159 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010160 Args,
Douglas Gregor063daf62009-03-13 18:40:31 +000010161 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010162 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +000010163 OpLoc));
10164 }
10165
John McCall5acb0c92011-10-17 18:40:02 +000010166 // Always do placeholder-like conversions on the RHS.
10167 if (checkPlaceholderForOverload(*this, Args[1]))
10168 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010169
John McCall3c3b7f92011-10-25 17:37:35 +000010170 // Do placeholder-like conversion on the LHS; note that we should
10171 // not get here with a PseudoObject LHS.
10172 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010173 if (checkPlaceholderForOverload(*this, Args[0]))
10174 return ExprError();
10175
Sebastian Redl275c2b42009-11-18 23:10:33 +000010176 // If this is the assignment operator, we only perform overload resolution
10177 // if the left-hand side is a class or enumeration type. This is actually
10178 // a hack. The standard requires that we do overload resolution between the
10179 // various built-in candidates, but as DR507 points out, this can lead to
10180 // problems. So we do it this way, which pretty much follows what GCC does.
10181 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010182 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010183 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010184
John McCall0e800c92010-12-04 08:14:53 +000010185 // If this is the .* operator, which is not overloadable, just
10186 // create a built-in binary operator.
10187 if (Opc == BO_PtrMemD)
10188 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10189
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010190 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010191 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010192
10193 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010194 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010195
10196 // Add operator candidates that are member functions.
10197 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10198
John McCall6e266892010-01-26 03:27:55 +000010199 // Add candidates from ADL.
10200 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010201 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010202 /*ExplicitTemplateArgs*/ 0,
10203 CandidateSet);
10204
Douglas Gregor063daf62009-03-13 18:40:31 +000010205 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010206 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010207
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010208 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10209
Douglas Gregor063daf62009-03-13 18:40:31 +000010210 // Perform overload resolution.
10211 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010212 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010213 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010214 // We found a built-in operator or an overloaded operator.
10215 FunctionDecl *FnDecl = Best->Function;
10216
10217 if (FnDecl) {
10218 // We matched an overloaded operator. Build a call to that
10219 // operator.
10220
Eli Friedman5f2987c2012-02-02 03:46:19 +000010221 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010222
Douglas Gregor063daf62009-03-13 18:40:31 +000010223 // Convert the arguments.
10224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010225 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010226 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010227
Chandler Carruth6df868e2010-12-12 08:17:55 +000010228 ExprResult Arg1 =
10229 PerformCopyInitialization(
10230 InitializedEntity::InitializeParameter(Context,
10231 FnDecl->getParamDecl(0)),
10232 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010233 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010234 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010235
John Wiegley429bb272011-04-08 18:41:53 +000010236 ExprResult Arg0 =
10237 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10238 Best->FoundDecl, Method);
10239 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010240 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010241 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010242 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010243 } else {
10244 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010245 ExprResult Arg0 = PerformCopyInitialization(
10246 InitializedEntity::InitializeParameter(Context,
10247 FnDecl->getParamDecl(0)),
10248 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010249 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010250 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010251
Chandler Carruth6df868e2010-12-12 08:17:55 +000010252 ExprResult Arg1 =
10253 PerformCopyInitialization(
10254 InitializedEntity::InitializeParameter(Context,
10255 FnDecl->getParamDecl(1)),
10256 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010257 if (Arg1.isInvalid())
10258 return ExprError();
10259 Args[0] = LHS = Arg0.takeAs<Expr>();
10260 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010261 }
10262
John McCallb697e082010-05-06 18:15:07 +000010263 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10264
John McCallf89e55a2010-11-18 06:31:45 +000010265 // Determine the result type.
10266 QualType ResultTy = FnDecl->getResultType();
10267 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10268 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010269
10270 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010271 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10272 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010273 if (FnExpr.isInvalid())
10274 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010275
John McCall9ae2f072010-08-23 23:25:46 +000010276 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010277 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010278 Args, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010279
10280 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010281 FnDecl))
10282 return ExprError();
10283
John McCall9ae2f072010-08-23 23:25:46 +000010284 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010285 } else {
10286 // We matched a built-in operator. Convert the arguments, then
10287 // break out so that we will build the appropriate built-in
10288 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010289 ExprResult ArgsRes0 =
10290 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10291 Best->Conversions[0], AA_Passing);
10292 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010293 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010294 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010295
John Wiegley429bb272011-04-08 18:41:53 +000010296 ExprResult ArgsRes1 =
10297 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10298 Best->Conversions[1], AA_Passing);
10299 if (ArgsRes1.isInvalid())
10300 return ExprError();
10301 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010302 break;
10303 }
10304 }
10305
Douglas Gregor33074752009-09-30 21:46:01 +000010306 case OR_No_Viable_Function: {
10307 // C++ [over.match.oper]p9:
10308 // If the operator is the operator , [...] and there are no
10309 // viable functions, then the operator is assumed to be the
10310 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010311 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010312 break;
10313
Chandler Carruth6df868e2010-12-12 08:17:55 +000010314 // For class as left operand for assignment or compound assigment
10315 // operator do not fall through to handling in built-in, but report that
10316 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010317 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010318 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010319 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010320 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10321 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010322 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010323 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010324 // This is an erroneous use of an operator which can be overloaded by
10325 // a non-member function. Check for non-member operators which were
10326 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010327 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010328 // FIXME: Recover by calling the found function.
10329 return ExprError();
10330
Douglas Gregor33074752009-09-30 21:46:01 +000010331 // No viable function; try to create a built-in operation, which will
10332 // produce an error. Then, show the non-viable candidates.
10333 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010334 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010335 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010336 "C++ binary operator overloading is missing candidates!");
10337 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010338 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010339 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010340 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010341 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010342
10343 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010344 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010345 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010346 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010347 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010348 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010349 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010350 return ExprError();
10351
10352 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010353 if (isImplicitlyDeleted(Best->Function)) {
10354 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10355 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10356 << getSpecialMember(Method)
10357 << BinaryOperator::getOpcodeStr(Opc)
10358 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010359
10360 if (getSpecialMember(Method) != CXXInvalid) {
10361 // The user probably meant to call this special member. Just
10362 // explain why it's deleted.
10363 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010364 return ExprError();
10365 }
10366 } else {
10367 Diag(OpLoc, diag::err_ovl_deleted_oper)
10368 << Best->Function->isDeleted()
10369 << BinaryOperator::getOpcodeStr(Opc)
10370 << getDeletedOrUnavailableSuffix(Best->Function)
10371 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10372 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010373 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010374 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010375 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010376 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010377
Douglas Gregor33074752009-09-30 21:46:01 +000010378 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010379 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010380}
10381
John McCall60d7b3a2010-08-24 06:29:42 +000010382ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010383Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10384 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010385 Expr *Base, Expr *Idx) {
10386 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010387 DeclarationName OpName =
10388 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10389
10390 // If either side is type-dependent, create an appropriate dependent
10391 // expression.
10392 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10393
John McCallc373d482010-01-27 01:50:18 +000010394 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010395 // CHECKME: no 'operator' keyword?
10396 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10397 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010398 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010399 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010400 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010401 /*ADL*/ true, /*Overloaded*/ false,
10402 UnresolvedSetIterator(),
10403 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010404 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010405
Sebastian Redlf322ed62009-10-29 20:17:01 +000010406 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010407 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010408 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010409 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010410 RLoc));
10411 }
10412
John McCall5acb0c92011-10-17 18:40:02 +000010413 // Handle placeholders on both operands.
10414 if (checkPlaceholderForOverload(*this, Args[0]))
10415 return ExprError();
10416 if (checkPlaceholderForOverload(*this, Args[1]))
10417 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010418
Sebastian Redlf322ed62009-10-29 20:17:01 +000010419 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010420 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010421
10422 // Subscript can only be overloaded as a member function.
10423
10424 // Add operator candidates that are member functions.
10425 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10426
10427 // Add builtin operator candidates.
10428 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10429
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010430 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10431
Sebastian Redlf322ed62009-10-29 20:17:01 +000010432 // Perform overload resolution.
10433 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010434 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010435 case OR_Success: {
10436 // We found a built-in operator or an overloaded operator.
10437 FunctionDecl *FnDecl = Best->Function;
10438
10439 if (FnDecl) {
10440 // We matched an overloaded operator. Build a call to that
10441 // operator.
10442
Eli Friedman5f2987c2012-02-02 03:46:19 +000010443 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010444
John McCall9aa472c2010-03-19 07:35:19 +000010445 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010446 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010447
Sebastian Redlf322ed62009-10-29 20:17:01 +000010448 // Convert the arguments.
10449 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010450 ExprResult Arg0 =
10451 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10452 Best->FoundDecl, Method);
10453 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010454 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010455 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010456
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010457 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010458 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010459 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010460 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010461 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010462 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010463 Owned(Args[1]));
10464 if (InputInit.isInvalid())
10465 return ExprError();
10466
10467 Args[1] = InputInit.takeAs<Expr>();
10468
Sebastian Redlf322ed62009-10-29 20:17:01 +000010469 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010470 QualType ResultTy = FnDecl->getResultType();
10471 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10472 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010473
10474 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010475 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10476 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010477 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10478 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010479 OpLocInfo.getLoc(),
10480 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010481 if (FnExpr.isInvalid())
10482 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010483
John McCall9ae2f072010-08-23 23:25:46 +000010484 CXXOperatorCallExpr *TheCall =
10485 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010486 FnExpr.take(), Args,
John McCallf89e55a2010-11-18 06:31:45 +000010487 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010488
John McCall9ae2f072010-08-23 23:25:46 +000010489 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010490 FnDecl))
10491 return ExprError();
10492
John McCall9ae2f072010-08-23 23:25:46 +000010493 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010494 } else {
10495 // We matched a built-in operator. Convert the arguments, then
10496 // break out so that we will build the appropriate built-in
10497 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010498 ExprResult ArgsRes0 =
10499 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10500 Best->Conversions[0], AA_Passing);
10501 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010502 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010503 Args[0] = ArgsRes0.take();
10504
10505 ExprResult ArgsRes1 =
10506 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10507 Best->Conversions[1], AA_Passing);
10508 if (ArgsRes1.isInvalid())
10509 return ExprError();
10510 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010511
10512 break;
10513 }
10514 }
10515
10516 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010517 if (CandidateSet.empty())
10518 Diag(LLoc, diag::err_ovl_no_oper)
10519 << Args[0]->getType() << /*subscript*/ 0
10520 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10521 else
10522 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10523 << Args[0]->getType()
10524 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010525 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010526 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010527 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010528 }
10529
10530 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010531 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010532 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010533 << Args[0]->getType() << Args[1]->getType()
10534 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010535 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010536 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010537 return ExprError();
10538
10539 case OR_Deleted:
10540 Diag(LLoc, diag::err_ovl_deleted_oper)
10541 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010542 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010543 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010544 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010545 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010546 return ExprError();
10547 }
10548
10549 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010550 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010551}
10552
Douglas Gregor88a35142008-12-22 05:46:06 +000010553/// BuildCallToMemberFunction - Build a call to a member
10554/// function. MemExpr is the expression that refers to the member
10555/// function (and includes the object parameter), Args/NumArgs are the
10556/// arguments to the function call (not including the object
10557/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010558/// expression refers to a non-static member function or an overloaded
10559/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010560ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010561Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10562 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010563 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010564 assert(MemExprE->getType() == Context.BoundMemberTy ||
10565 MemExprE->getType() == Context.OverloadTy);
10566
Douglas Gregor88a35142008-12-22 05:46:06 +000010567 // Dig out the member expression. This holds both the object
10568 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010569 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010570
John McCall864c0412011-04-26 20:42:42 +000010571 // Determine whether this is a call to a pointer-to-member function.
10572 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10573 assert(op->getType() == Context.BoundMemberTy);
10574 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10575
10576 QualType fnType =
10577 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10578
10579 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10580 QualType resultType = proto->getCallResultType(Context);
10581 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10582
10583 // Check that the object type isn't more qualified than the
10584 // member function we're calling.
10585 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10586
10587 QualType objectType = op->getLHS()->getType();
10588 if (op->getOpcode() == BO_PtrMemI)
10589 objectType = objectType->castAs<PointerType>()->getPointeeType();
10590 Qualifiers objectQuals = objectType.getQualifiers();
10591
10592 Qualifiers difference = objectQuals - funcQuals;
10593 difference.removeObjCGCAttr();
10594 difference.removeAddressSpace();
10595 if (difference) {
10596 std::string qualsString = difference.getAsString();
10597 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10598 << fnType.getUnqualifiedType()
10599 << qualsString
10600 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10601 }
10602
10603 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010604 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10605 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010606 resultType, valueKind, RParenLoc);
10607
10608 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010609 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010610 call, 0))
10611 return ExprError();
10612
10613 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10614 return ExprError();
10615
10616 return MaybeBindToTemporary(call);
10617 }
10618
John McCall5acb0c92011-10-17 18:40:02 +000010619 UnbridgedCastsSet UnbridgedCasts;
10620 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10621 return ExprError();
10622
John McCall129e2df2009-11-30 22:42:35 +000010623 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010624 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010625 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010626 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010627 if (isa<MemberExpr>(NakedMemExpr)) {
10628 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010629 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010630 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010631 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010632 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010633 } else {
10634 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010635 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010636
John McCall701c89e2009-12-03 04:06:58 +000010637 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010638 Expr::Classification ObjectClassification
10639 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10640 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010641
Douglas Gregor88a35142008-12-22 05:46:06 +000010642 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010643 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010644
John McCallaa81e162009-12-01 22:10:20 +000010645 // FIXME: avoid copy.
10646 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10647 if (UnresExpr->hasExplicitTemplateArgs()) {
10648 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10649 TemplateArgs = &TemplateArgsBuffer;
10650 }
10651
John McCall129e2df2009-11-30 22:42:35 +000010652 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10653 E = UnresExpr->decls_end(); I != E; ++I) {
10654
John McCall701c89e2009-12-03 04:06:58 +000010655 NamedDecl *Func = *I;
10656 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10657 if (isa<UsingShadowDecl>(Func))
10658 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10659
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010660
Francois Pichetdbee3412011-01-18 05:04:39 +000010661 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010662 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010663 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10664 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010665 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010666 // If explicit template arguments were provided, we can't call a
10667 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010668 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010669 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010670
John McCall9aa472c2010-03-19 07:35:19 +000010671 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010672 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010673 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010674 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010675 } else {
John McCall129e2df2009-11-30 22:42:35 +000010676 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010677 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010678 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010679 llvm::makeArrayRef(Args, NumArgs),
10680 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010681 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010682 }
Douglas Gregordec06662009-08-21 18:42:58 +000010683 }
Mike Stump1eb44332009-09-09 15:08:12 +000010684
John McCall129e2df2009-11-30 22:42:35 +000010685 DeclarationName DeclName = UnresExpr->getMemberName();
10686
John McCall5acb0c92011-10-17 18:40:02 +000010687 UnbridgedCasts.restore();
10688
Douglas Gregor88a35142008-12-22 05:46:06 +000010689 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010690 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010691 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010692 case OR_Success:
10693 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010694 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010695 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010696 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010697 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010698 break;
10699
10700 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010701 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010702 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010703 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010704 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10705 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010706 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010707 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010708
10709 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010710 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010711 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010712 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10713 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010714 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010715 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010716
10717 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010718 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010719 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010720 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010721 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010722 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010723 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10724 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010725 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010726 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010727 }
10728
John McCall6bb80172010-03-30 21:47:33 +000010729 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010730
John McCallaa81e162009-12-01 22:10:20 +000010731 // If overload resolution picked a static member, build a
10732 // non-member call based on that function.
10733 if (Method->isStatic()) {
10734 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10735 Args, NumArgs, RParenLoc);
10736 }
10737
John McCall129e2df2009-11-30 22:42:35 +000010738 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010739 }
10740
John McCallf89e55a2010-11-18 06:31:45 +000010741 QualType ResultType = Method->getResultType();
10742 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10743 ResultType = ResultType.getNonLValueExprType(Context);
10744
Douglas Gregor88a35142008-12-22 05:46:06 +000010745 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010746 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010747 new (Context) CXXMemberCallExpr(Context, MemExprE,
10748 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010749 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010750
Anders Carlssoneed3e692009-10-10 00:06:20 +000010751 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010752 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010753 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010754 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010755
Douglas Gregor88a35142008-12-22 05:46:06 +000010756 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010757 // We only need to do this if there was actually an overload; otherwise
10758 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010759 if (!Method->isStatic()) {
10760 ExprResult ObjectArg =
10761 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10762 FoundDecl, Method);
10763 if (ObjectArg.isInvalid())
10764 return ExprError();
10765 MemExpr->setBase(ObjectArg.take());
10766 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010767
10768 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010769 const FunctionProtoType *Proto =
10770 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010771 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010772 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010773 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010774
Eli Friedmane61eb042012-02-18 04:48:30 +000010775 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10776
Richard Smith831421f2012-06-25 20:30:08 +000010777 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010778 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010779
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010780 if ((isa<CXXConstructorDecl>(CurContext) ||
10781 isa<CXXDestructorDecl>(CurContext)) &&
10782 TheCall->getMethodDecl()->isPure()) {
10783 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10784
Chandler Carruthae198062011-06-27 08:31:58 +000010785 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010786 Diag(MemExpr->getLocStart(),
10787 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10788 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10789 << MD->getParent()->getDeclName();
10790
10791 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010792 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010793 }
John McCall9ae2f072010-08-23 23:25:46 +000010794 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010795}
10796
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010797/// BuildCallToObjectOfClassType - Build a call to an object of class
10798/// type (C++ [over.call.object]), which can end up invoking an
10799/// overloaded function call operator (@c operator()) or performing a
10800/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010801ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010802Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010803 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010804 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010805 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010806 if (checkPlaceholderForOverload(*this, Obj))
10807 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010808 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010809
10810 UnbridgedCastsSet UnbridgedCasts;
10811 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10812 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010813
John Wiegley429bb272011-04-08 18:41:53 +000010814 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10815 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010816
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010817 // C++ [over.call.object]p1:
10818 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010819 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010820 // candidate functions includes at least the function call
10821 // operators of T. The function call operators of T are obtained by
10822 // ordinary lookup of the name operator() in the context of
10823 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010824 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010825 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010826
John Wiegley429bb272011-04-08 18:41:53 +000010827 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010828 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010829 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010830
John McCalla24dc2e2009-11-17 02:14:36 +000010831 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10832 LookupQualifiedName(R, Record->getDecl());
10833 R.suppressDiagnostics();
10834
Douglas Gregor593564b2009-11-15 07:48:03 +000010835 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010836 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010837 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10838 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010839 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010840 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010841
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010842 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010843 // In addition, for each (non-explicit in C++0x) conversion function
10844 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010845 //
10846 // operator conversion-type-id () cv-qualifier;
10847 //
10848 // where cv-qualifier is the same cv-qualification as, or a
10849 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010850 // denotes the type "pointer to function of (P1,...,Pn) returning
10851 // R", or the type "reference to pointer to function of
10852 // (P1,...,Pn) returning R", or the type "reference to function
10853 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010854 // is also considered as a candidate function. Similarly,
10855 // surrogate call functions are added to the set of candidate
10856 // functions for each conversion function declared in an
10857 // accessible base class provided the function is not hidden
10858 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010859 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010860 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010861 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010862 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010863 NamedDecl *D = *I;
10864 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10865 if (isa<UsingShadowDecl>(D))
10866 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010867
Douglas Gregor4a27d702009-10-21 06:18:39 +000010868 // Skip over templated conversion functions; they aren't
10869 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010870 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010871 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010872
John McCall701c89e2009-12-03 04:06:58 +000010873 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010874 if (!Conv->isExplicit()) {
10875 // Strip the reference type (if any) and then the pointer type (if
10876 // any) to get down to what might be a function type.
10877 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10878 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10879 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010880
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010881 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10882 {
10883 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010884 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10885 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010886 }
10887 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010888 }
Mike Stump1eb44332009-09-09 15:08:12 +000010889
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010890 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10891
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010892 // Perform overload resolution.
10893 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010894 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010895 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010896 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010897 // Overload resolution succeeded; we'll build the appropriate call
10898 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010899 break;
10900
10901 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010902 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010903 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010904 << Object.get()->getType() << /*call*/ 1
10905 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010906 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010907 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010908 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010909 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10911 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010912 break;
10913
10914 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010915 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010916 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010917 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010918 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10919 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010920 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010921
10922 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010923 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010924 diag::err_ovl_deleted_object_call)
10925 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010926 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010927 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010928 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010929 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10930 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010931 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010932 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010933
Douglas Gregorff331c12010-07-25 18:17:45 +000010934 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010935 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010936
John McCall5acb0c92011-10-17 18:40:02 +000010937 UnbridgedCasts.restore();
10938
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010939 if (Best->Function == 0) {
10940 // Since there is no function declaration, this is one of the
10941 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010942 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010943 = cast<CXXConversionDecl>(
10944 Best->Conversions[0].UserDefined.ConversionFunction);
10945
John Wiegley429bb272011-04-08 18:41:53 +000010946 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010947 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010948
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010949 // We selected one of the surrogate functions that converts the
10950 // object parameter to a function pointer. Perform the conversion
10951 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010952
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010953 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010954 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010955 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10956 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010957 if (Call.isInvalid())
10958 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010959 // Record usage of conversion in an implicit cast.
10960 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10961 CK_UserDefinedConversion,
10962 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010963
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010964 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010965 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010966 }
10967
Eli Friedman5f2987c2012-02-02 03:46:19 +000010968 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010969 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010970 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010971
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010972 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10973 // that calls this method, using Object for the implicit object
10974 // parameter and passing along the remaining arguments.
10975 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010976 const FunctionProtoType *Proto =
10977 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010978
10979 unsigned NumArgsInProto = Proto->getNumArgs();
10980 unsigned NumArgsToCheck = NumArgs;
10981
10982 // Build the full argument list for the method call (the
10983 // implicit object parameter is placed at the beginning of the
10984 // list).
10985 Expr **MethodArgs;
10986 if (NumArgs < NumArgsInProto) {
10987 NumArgsToCheck = NumArgsInProto;
10988 MethodArgs = new Expr*[NumArgsInProto + 1];
10989 } else {
10990 MethodArgs = new Expr*[NumArgs + 1];
10991 }
John Wiegley429bb272011-04-08 18:41:53 +000010992 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010993 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10994 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010995
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010996 DeclarationNameInfo OpLocInfo(
10997 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10998 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010999 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011000 HadMultipleCandidates,
11001 OpLocInfo.getLoc(),
11002 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011003 if (NewFn.isInvalid())
11004 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011005
11006 // Once we've built TheCall, all of the expressions are properly
11007 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011008 QualType ResultTy = Method->getResultType();
11009 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11010 ResultTy = ResultTy.getNonLValueExprType(Context);
11011
John McCall9ae2f072010-08-23 23:25:46 +000011012 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011013 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011014 llvm::makeArrayRef(MethodArgs, NumArgs+1),
John McCallf89e55a2010-11-18 06:31:45 +000011015 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011016 delete [] MethodArgs;
11017
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011018 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011019 Method))
11020 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011021
Douglas Gregor518fda12009-01-13 05:10:00 +000011022 // We may have default arguments. If so, we need to allocate more
11023 // slots in the call for them.
11024 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011025 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011026 else if (NumArgs > NumArgsInProto)
11027 NumArgsToCheck = NumArgsInProto;
11028
Chris Lattner312531a2009-04-12 08:11:20 +000011029 bool IsError = false;
11030
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011031 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011032 ExprResult ObjRes =
11033 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11034 Best->FoundDecl, Method);
11035 if (ObjRes.isInvalid())
11036 IsError = true;
11037 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011038 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011039 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011040
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011041 // Check the argument types.
11042 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011043 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011044 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011045 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011046
Douglas Gregor518fda12009-01-13 05:10:00 +000011047 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011048
John McCall60d7b3a2010-08-24 06:29:42 +000011049 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011050 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011051 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011052 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011053 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011054
Anders Carlsson3faa4862010-01-29 18:43:53 +000011055 IsError |= InputInit.isInvalid();
11056 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011057 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011058 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011059 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11060 if (DefArg.isInvalid()) {
11061 IsError = true;
11062 break;
11063 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011064
Douglas Gregord47c47d2009-11-09 19:27:57 +000011065 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011066 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011067
11068 TheCall->setArg(i + 1, Arg);
11069 }
11070
11071 // If this is a variadic call, handle args passed through "...".
11072 if (Proto->isVariadic()) {
11073 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011074 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011075 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11076 IsError |= Arg.isInvalid();
11077 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011078 }
11079 }
11080
Chris Lattner312531a2009-04-12 08:11:20 +000011081 if (IsError) return true;
11082
Eli Friedmane61eb042012-02-18 04:48:30 +000011083 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11084
Richard Smith831421f2012-06-25 20:30:08 +000011085 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011086 return true;
11087
John McCall182f7092010-08-24 06:09:16 +000011088 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011089}
11090
Douglas Gregor8ba10742008-11-20 16:27:02 +000011091/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011092/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011093/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011094ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011095Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011096 assert(Base->getType()->isRecordType() &&
11097 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011098
John McCall5acb0c92011-10-17 18:40:02 +000011099 if (checkPlaceholderForOverload(*this, Base))
11100 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011101
John McCall5769d612010-02-08 23:07:23 +000011102 SourceLocation Loc = Base->getExprLoc();
11103
Douglas Gregor8ba10742008-11-20 16:27:02 +000011104 // C++ [over.ref]p1:
11105 //
11106 // [...] An expression x->m is interpreted as (x.operator->())->m
11107 // for a class object x of type T if T::operator->() exists and if
11108 // the operator is selected as the best match function by the
11109 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011110 DeclarationName OpName =
11111 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011112 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011113 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011114
John McCall5769d612010-02-08 23:07:23 +000011115 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011116 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011117 return ExprError();
11118
John McCalla24dc2e2009-11-17 02:14:36 +000011119 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11120 LookupQualifiedName(R, BaseRecord->getDecl());
11121 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011122
11123 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011124 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011125 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11126 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011127 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011128
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011129 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11130
Douglas Gregor8ba10742008-11-20 16:27:02 +000011131 // Perform overload resolution.
11132 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011133 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011134 case OR_Success:
11135 // Overload resolution succeeded; we'll build the call below.
11136 break;
11137
11138 case OR_No_Viable_Function:
11139 if (CandidateSet.empty())
11140 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011141 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011142 else
11143 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011144 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011145 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011146 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011147
11148 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011149 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11150 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011151 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011152 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011153
11154 case OR_Deleted:
11155 Diag(OpLoc, diag::err_ovl_deleted_oper)
11156 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011157 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011158 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011159 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011160 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011161 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011162 }
11163
Eli Friedman5f2987c2012-02-02 03:46:19 +000011164 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011165 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011166 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011167
Douglas Gregor8ba10742008-11-20 16:27:02 +000011168 // Convert the object parameter.
11169 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011170 ExprResult BaseResult =
11171 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11172 Best->FoundDecl, Method);
11173 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011174 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011175 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011176
Douglas Gregor8ba10742008-11-20 16:27:02 +000011177 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011178 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011179 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011180 if (FnExpr.isInvalid())
11181 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011182
John McCallf89e55a2010-11-18 06:31:45 +000011183 QualType ResultTy = Method->getResultType();
11184 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11185 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011186 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011187 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011188 Base, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011189
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011190 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011191 Method))
11192 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011193
11194 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011195}
11196
Richard Smith36f5cfe2012-03-09 08:00:36 +000011197/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11198/// a literal operator described by the provided lookup results.
11199ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11200 DeclarationNameInfo &SuffixInfo,
11201 ArrayRef<Expr*> Args,
11202 SourceLocation LitEndLoc,
11203 TemplateArgumentListInfo *TemplateArgs) {
11204 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011205
Richard Smith36f5cfe2012-03-09 08:00:36 +000011206 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11207 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11208 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011209
Richard Smith36f5cfe2012-03-09 08:00:36 +000011210 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11211
Richard Smith36f5cfe2012-03-09 08:00:36 +000011212 // Perform overload resolution. This will usually be trivial, but might need
11213 // to perform substitutions for a literal operator template.
11214 OverloadCandidateSet::iterator Best;
11215 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11216 case OR_Success:
11217 case OR_Deleted:
11218 break;
11219
11220 case OR_No_Viable_Function:
11221 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11222 << R.getLookupName();
11223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11224 return ExprError();
11225
11226 case OR_Ambiguous:
11227 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11228 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11229 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011230 }
11231
Richard Smith36f5cfe2012-03-09 08:00:36 +000011232 FunctionDecl *FD = Best->Function;
11233 MarkFunctionReferenced(UDSuffixLoc, FD);
11234 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011235
Richard Smith36f5cfe2012-03-09 08:00:36 +000011236 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11237 SuffixInfo.getLoc(),
11238 SuffixInfo.getInfo());
11239 if (Fn.isInvalid())
11240 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011241
11242 // Check the argument types. This should almost always be a no-op, except
11243 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011244 Expr *ConvArgs[2];
11245 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11246 ExprResult InputInit = PerformCopyInitialization(
11247 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11248 SourceLocation(), Args[ArgIdx]);
11249 if (InputInit.isInvalid())
11250 return true;
11251 ConvArgs[ArgIdx] = InputInit.take();
11252 }
11253
Richard Smith9fcce652012-03-07 08:35:16 +000011254 QualType ResultTy = FD->getResultType();
11255 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11256 ResultTy = ResultTy.getNonLValueExprType(Context);
11257
Richard Smith9fcce652012-03-07 08:35:16 +000011258 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011259 new (Context) UserDefinedLiteral(Context, Fn.take(),
11260 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011261 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11262
11263 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11264 return ExprError();
11265
Richard Smith831421f2012-06-25 20:30:08 +000011266 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011267 return ExprError();
11268
11269 return MaybeBindToTemporary(UDL);
11270}
11271
Sam Panzere1715b62012-08-21 00:52:01 +000011272/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11273/// given LookupResult is non-empty, it is assumed to describe a member which
11274/// will be invoked. Otherwise, the function will be found via argument
11275/// dependent lookup.
11276/// CallExpr is set to a valid expression and FRS_Success returned on success,
11277/// otherwise CallExpr is set to ExprError() and some non-success value
11278/// is returned.
11279Sema::ForRangeStatus
11280Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11281 SourceLocation RangeLoc, VarDecl *Decl,
11282 BeginEndFunction BEF,
11283 const DeclarationNameInfo &NameInfo,
11284 LookupResult &MemberLookup,
11285 OverloadCandidateSet *CandidateSet,
11286 Expr *Range, ExprResult *CallExpr) {
11287 CandidateSet->clear();
11288 if (!MemberLookup.empty()) {
11289 ExprResult MemberRef =
11290 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11291 /*IsPtr=*/false, CXXScopeSpec(),
11292 /*TemplateKWLoc=*/SourceLocation(),
11293 /*FirstQualifierInScope=*/0,
11294 MemberLookup,
11295 /*TemplateArgs=*/0);
11296 if (MemberRef.isInvalid()) {
11297 *CallExpr = ExprError();
11298 Diag(Range->getLocStart(), diag::note_in_for_range)
11299 << RangeLoc << BEF << Range->getType();
11300 return FRS_DiagnosticIssued;
11301 }
11302 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11303 if (CallExpr->isInvalid()) {
11304 *CallExpr = ExprError();
11305 Diag(Range->getLocStart(), diag::note_in_for_range)
11306 << RangeLoc << BEF << Range->getType();
11307 return FRS_DiagnosticIssued;
11308 }
11309 } else {
11310 UnresolvedSet<0> FoundNames;
11311 // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace
11312 // std is an associated namespace.
11313 UnresolvedLookupExpr *Fn =
11314 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11315 NestedNameSpecifierLoc(), NameInfo,
11316 /*NeedsADL=*/true, /*Overloaded=*/false,
11317 FoundNames.begin(), FoundNames.end(),
11318 /*LookInStdNamespace=*/true);
11319
11320 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11321 CandidateSet, CallExpr);
11322 if (CandidateSet->empty() || CandidateSetError) {
11323 *CallExpr = ExprError();
11324 return FRS_NoViableFunction;
11325 }
11326 OverloadCandidateSet::iterator Best;
11327 OverloadingResult OverloadResult =
11328 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11329
11330 if (OverloadResult == OR_No_Viable_Function) {
11331 *CallExpr = ExprError();
11332 return FRS_NoViableFunction;
11333 }
11334 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11335 Loc, 0, CandidateSet, &Best,
11336 OverloadResult,
11337 /*AllowTypoCorrection=*/false);
11338 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11339 *CallExpr = ExprError();
11340 Diag(Range->getLocStart(), diag::note_in_for_range)
11341 << RangeLoc << BEF << Range->getType();
11342 return FRS_DiagnosticIssued;
11343 }
11344 }
11345 return FRS_Success;
11346}
11347
11348
Douglas Gregor904eed32008-11-10 20:40:00 +000011349/// FixOverloadedFunctionReference - E is an expression that refers to
11350/// a C++ overloaded function (possibly with some parentheses and
11351/// perhaps a '&' around it). We have resolved the overloaded function
11352/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011353/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011354Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011355 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011356 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011357 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11358 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011359 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011360 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011361
Douglas Gregor699ee522009-11-20 19:42:02 +000011362 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011363 }
11364
Douglas Gregor699ee522009-11-20 19:42:02 +000011365 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011366 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11367 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011368 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011369 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011370 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011371 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011372 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011373 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011374
11375 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011376 ICE->getCastKind(),
11377 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011378 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011379 }
11380
Douglas Gregor699ee522009-11-20 19:42:02 +000011381 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011382 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011383 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011384 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11385 if (Method->isStatic()) {
11386 // Do nothing: static member functions aren't any different
11387 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011388 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011389 // Fix the sub expression, which really has to be an
11390 // UnresolvedLookupExpr holding an overloaded member function
11391 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011392 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11393 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011394 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011395 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011396
John McCallba135432009-11-21 08:51:07 +000011397 assert(isa<DeclRefExpr>(SubExpr)
11398 && "fixed to something other than a decl ref");
11399 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11400 && "fixed to a member ref with no nested name qualifier");
11401
11402 // We have taken the address of a pointer to member
11403 // function. Perform the computation here so that we get the
11404 // appropriate pointer to member type.
11405 QualType ClassType
11406 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11407 QualType MemPtrType
11408 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11409
John McCallf89e55a2010-11-18 06:31:45 +000011410 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11411 VK_RValue, OK_Ordinary,
11412 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011413 }
11414 }
John McCall6bb80172010-03-30 21:47:33 +000011415 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11416 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011417 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011418 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011419
John McCall2de56d12010-08-25 11:45:40 +000011420 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011421 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011422 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011423 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011424 }
John McCallba135432009-11-21 08:51:07 +000011425
11426 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011427 // FIXME: avoid copy.
11428 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011429 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011430 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11431 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011432 }
11433
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011434 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11435 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011436 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011437 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011438 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011439 ULE->getNameLoc(),
11440 Fn->getType(),
11441 VK_LValue,
11442 Found.getDecl(),
11443 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011444 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011445 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11446 return DRE;
John McCallba135432009-11-21 08:51:07 +000011447 }
11448
John McCall129e2df2009-11-30 22:42:35 +000011449 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011450 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011451 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11452 if (MemExpr->hasExplicitTemplateArgs()) {
11453 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11454 TemplateArgs = &TemplateArgsBuffer;
11455 }
John McCalld5532b62009-11-23 01:53:49 +000011456
John McCallaa81e162009-12-01 22:10:20 +000011457 Expr *Base;
11458
John McCallf89e55a2010-11-18 06:31:45 +000011459 // If we're filling in a static method where we used to have an
11460 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011461 if (MemExpr->isImplicitAccess()) {
11462 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011463 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11464 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011465 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011466 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011467 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011468 MemExpr->getMemberLoc(),
11469 Fn->getType(),
11470 VK_LValue,
11471 Found.getDecl(),
11472 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011473 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011474 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11475 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011476 } else {
11477 SourceLocation Loc = MemExpr->getMemberLoc();
11478 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011479 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011480 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011481 Base = new (Context) CXXThisExpr(Loc,
11482 MemExpr->getBaseType(),
11483 /*isImplicit=*/true);
11484 }
John McCallaa81e162009-12-01 22:10:20 +000011485 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011486 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011487
John McCallf5307512011-04-27 00:36:17 +000011488 ExprValueKind valueKind;
11489 QualType type;
11490 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11491 valueKind = VK_LValue;
11492 type = Fn->getType();
11493 } else {
11494 valueKind = VK_RValue;
11495 type = Context.BoundMemberTy;
11496 }
11497
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011498 MemberExpr *ME = MemberExpr::Create(Context, Base,
11499 MemExpr->isArrow(),
11500 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011501 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011502 Fn,
11503 Found,
11504 MemExpr->getMemberNameInfo(),
11505 TemplateArgs,
11506 type, valueKind, OK_Ordinary);
11507 ME->setHadMultipleCandidates(true);
11508 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011509 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011510
John McCall3fa5cae2010-10-26 07:05:15 +000011511 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011512}
11513
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011514ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011515 DeclAccessPair Found,
11516 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011517 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011518}
11519
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011520} // end namespace clang