blob: 284c8dec1c62701b14fba8db694e9dc352b01109 [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"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000044 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000052}
53
John McCall120d63c2010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor60d62c22008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202}
203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000242bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregorf9af5242011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265 switch (ICE->getCastKind()) {
266 case CK_NoOp:
267 case CK_IntegralCast:
268 case CK_IntegralToBoolean:
269 case CK_IntegralToFloating:
270 case CK_FloatingToIntegral:
271 case CK_FloatingToBoolean:
272 case CK_FloatingCast:
273 Converted = ICE->getSubExpr();
274 continue;
275
276 default:
277 return Converted;
278 }
279 }
280
281 return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx The AST context.
288/// \param Converted The result of applying this standard conversion sequence.
289/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
290/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000291/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
292/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000293NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000294StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
295 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000296 APValue &ConstantValue,
297 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000298 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000299
300 // C++11 [dcl.init.list]p7:
301 // A narrowing conversion is an implicit conversion ...
302 QualType FromType = getToType(0);
303 QualType ToType = getToType(1);
304 switch (Second) {
305 // -- from a floating-point type to an integer type, or
306 //
307 // -- from an integer type or unscoped enumeration type to a floating-point
308 // type, except where the source is a constant expression and the actual
309 // value after conversion will fit into the target type and will produce
310 // the original value when converted back to the original type, or
311 case ICK_Floating_Integral:
312 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
313 return NK_Type_Narrowing;
314 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
315 llvm::APSInt IntConstantValue;
316 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
317 if (Initializer &&
318 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
319 // Convert the integer to the floating type.
320 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
321 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
322 llvm::APFloat::rmNearestTiesToEven);
323 // And back.
324 llvm::APSInt ConvertedValue = IntConstantValue;
325 bool ignored;
326 Result.convertToInteger(ConvertedValue,
327 llvm::APFloat::rmTowardZero, &ignored);
328 // If the resulting value is different, this was a narrowing conversion.
329 if (IntConstantValue != ConvertedValue) {
330 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000331 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000332 return NK_Constant_Narrowing;
333 }
334 } else {
335 // Variables are always narrowings.
336 return NK_Variable_Narrowing;
337 }
338 }
339 return NK_Not_Narrowing;
340
341 // -- from long double to double or float, or from double to float, except
342 // where the source is a constant expression and the actual value after
343 // conversion is within the range of values that can be represented (even
344 // if it cannot be represented exactly), or
345 case ICK_Floating_Conversion:
346 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
347 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
348 // FromType is larger than ToType.
349 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
350 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
351 // Constant!
352 assert(ConstantValue.isFloat());
353 llvm::APFloat FloatVal = ConstantValue.getFloat();
354 // Convert the source value into the target type.
355 bool ignored;
356 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
357 Ctx.getFloatTypeSemantics(ToType),
358 llvm::APFloat::rmNearestTiesToEven, &ignored);
359 // If there was no overflow, the source value is within the range of
360 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000361 if (ConvertStatus & llvm::APFloat::opOverflow) {
362 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000363 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000364 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000365 } else {
366 return NK_Variable_Narrowing;
367 }
368 }
369 return NK_Not_Narrowing;
370
371 // -- from an integer type or unscoped enumeration type to an integer type
372 // that cannot represent all the values of the original type, except where
373 // the source is a constant expression and the actual value after
374 // conversion will fit into the target type and will produce the original
375 // value when converted back to the original type.
376 case ICK_Boolean_Conversion: // Bools are integers too.
377 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
378 // Boolean conversions can be from pointers and pointers to members
379 // [conv.bool], and those aren't considered narrowing conversions.
380 return NK_Not_Narrowing;
381 } // Otherwise, fall through to the integral case.
382 case ICK_Integral_Conversion: {
383 assert(FromType->isIntegralOrUnscopedEnumerationType());
384 assert(ToType->isIntegralOrUnscopedEnumerationType());
385 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
386 const unsigned FromWidth = Ctx.getIntWidth(FromType);
387 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
388 const unsigned ToWidth = Ctx.getIntWidth(ToType);
389
390 if (FromWidth > ToWidth ||
391 (FromWidth == ToWidth && FromSigned != ToSigned)) {
392 // Not all values of FromType can be represented in ToType.
393 llvm::APSInt InitializerValue;
394 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
395 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
396 ConstantValue = APValue(InitializerValue);
397
398 // Add a bit to the InitializerValue so we don't have to worry about
399 // signed vs. unsigned comparisons.
400 InitializerValue = InitializerValue.extend(
401 InitializerValue.getBitWidth() + 1);
402 // Convert the initializer to and from the target width and signed-ness.
403 llvm::APSInt ConvertedValue = InitializerValue;
404 ConvertedValue = ConvertedValue.trunc(ToWidth);
405 ConvertedValue.setIsSigned(ToSigned);
406 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
407 ConvertedValue.setIsSigned(InitializerValue.isSigned());
408 // If the result is different, this was a narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000409 if (ConvertedValue != InitializerValue) {
410 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000411 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000412 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000413 } else {
414 // Variables are always narrowings.
415 return NK_Variable_Narrowing;
416 }
417 }
418 return NK_Not_Narrowing;
419 }
420
421 default:
422 // Other kinds of conversions are not narrowings.
423 return NK_Not_Narrowing;
424 }
425}
426
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000427/// DebugPrint - Print this standard conversion sequence to standard
428/// error. Useful for debugging overloading issues.
429void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000431 bool PrintedSomething = false;
432 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000434 PrintedSomething = true;
435 }
436
437 if (Second != ICK_Identity) {
438 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000439 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000440 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000441 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000442
443 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000444 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000445 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000446 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000447 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000448 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000449 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (Third != ICK_Identity) {
454 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000455 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000456 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000462 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000463 }
464}
465
466/// DebugPrint - Print this user-defined conversion sequence to standard
467/// error. Useful for debugging overloading issues.
468void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000469 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470 if (Before.First || Before.Second || Before.Third) {
471 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000474 if (ConversionFunction)
475 OS << '\'' << *ConversionFunction << '\'';
476 else
477 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000478 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 After.DebugPrint();
481 }
482}
483
484/// DebugPrint - Print this implicit conversion sequence to standard
485/// error. Useful for debugging overloading issues.
486void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000487 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 switch (ConversionKind) {
489 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 Standard.DebugPrint();
492 break;
493 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000494 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 UserDefined.DebugPrint();
496 break;
497 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000498 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 break;
John McCall1d318332010-01-12 00:44:57 +0000500 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000501 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000502 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000504 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 break;
506 }
507
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000508 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509}
510
John McCall1d318332010-01-12 00:44:57 +0000511void AmbiguousConversionSequence::construct() {
512 new (&conversions()) ConversionSet();
513}
514
515void AmbiguousConversionSequence::destruct() {
516 conversions().~ConversionSet();
517}
518
519void
520AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
521 FromTypePtr = O.FromTypePtr;
522 ToTypePtr = O.ToTypePtr;
523 new (&conversions()) ConversionSet(O.conversions());
524}
525
Douglas Gregora9333192010-05-08 17:41:32 +0000526namespace {
527 // Structure used by OverloadCandidate::DeductionFailureInfo to store
528 // template parameter and template argument information.
529 struct DFIParamWithArguments {
530 TemplateParameter Param;
531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
534}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000535
Douglas Gregora9333192010-05-08 17:41:32 +0000536/// \brief Convert from Sema's representation of template deduction information
537/// to the form used in overload-candidate information.
538OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000539static MakeDeductionFailureInfo(ASTContext &Context,
540 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000541 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000542 OverloadCandidate::DeductionFailureInfo Result;
543 Result.Result = static_cast<unsigned>(TDK);
544 Result.Data = 0;
545 switch (TDK) {
546 case Sema::TDK_Success:
547 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000548 case Sema::TDK_TooManyArguments:
549 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000550 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551
Douglas Gregora9333192010-05-08 17:41:32 +0000552 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000553 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000554 Result.Data = Info.Param.getOpaqueValue();
555 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556
Douglas Gregora9333192010-05-08 17:41:32 +0000557 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000558 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000559 // FIXME: Should allocate from normal heap so that we can free this later.
560 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000561 Saved->Param = Info.Param;
562 Saved->FirstArg = Info.FirstArg;
563 Saved->SecondArg = Info.SecondArg;
564 Result.Data = Saved;
565 break;
566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567
Douglas Gregora9333192010-05-08 17:41:32 +0000568 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000569 Result.Data = Info.take();
570 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000571
Douglas Gregora9333192010-05-08 17:41:32 +0000572 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000573 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000575 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000576
Douglas Gregora9333192010-05-08 17:41:32 +0000577 return Result;
578}
John McCall1d318332010-01-12 00:44:57 +0000579
Douglas Gregora9333192010-05-08 17:41:32 +0000580void OverloadCandidate::DeductionFailureInfo::Destroy() {
581 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
582 case Sema::TDK_Success:
583 case Sema::TDK_InstantiationDepth:
584 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000585 case Sema::TDK_TooManyArguments:
586 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000587 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589
Douglas Gregora9333192010-05-08 17:41:32 +0000590 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000591 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000592 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000593 Data = 0;
594 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000595
596 case Sema::TDK_SubstitutionFailure:
597 // FIXME: Destroy the template arugment list?
598 Data = 0;
599 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000600
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000601 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000602 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000603 case Sema::TDK_FailedOverloadResolution:
604 break;
605 }
606}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
608TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000609OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
610 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
611 case Sema::TDK_Success:
612 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000613 case Sema::TDK_TooManyArguments:
614 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000615 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000616 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora9333192010-05-08 17:41:32 +0000618 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000619 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000620 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000621
622 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000623 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000624 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000625
Douglas Gregora9333192010-05-08 17:41:32 +0000626 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000627 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000628 case Sema::TDK_FailedOverloadResolution:
629 break;
630 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000631
Douglas Gregora9333192010-05-08 17:41:32 +0000632 return TemplateParameter();
633}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000634
Douglas Gregorec20f462010-05-08 20:07:26 +0000635TemplateArgumentList *
636OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
637 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
638 case Sema::TDK_Success:
639 case Sema::TDK_InstantiationDepth:
640 case Sema::TDK_TooManyArguments:
641 case Sema::TDK_TooFewArguments:
642 case Sema::TDK_Incomplete:
643 case Sema::TDK_InvalidExplicitArguments:
644 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000645 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000646 return 0;
647
648 case Sema::TDK_SubstitutionFailure:
649 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000650
Douglas Gregorec20f462010-05-08 20:07:26 +0000651 // Unhandled
652 case Sema::TDK_NonDeducedMismatch:
653 case Sema::TDK_FailedOverloadResolution:
654 break;
655 }
656
657 return 0;
658}
659
Douglas Gregora9333192010-05-08 17:41:32 +0000660const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
661 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
662 case Sema::TDK_Success:
663 case Sema::TDK_InstantiationDepth:
664 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000665 case Sema::TDK_TooManyArguments:
666 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000667 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000668 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000669 return 0;
670
Douglas Gregora9333192010-05-08 17:41:32 +0000671 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000672 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000674
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000675 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000676 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000677 case Sema::TDK_FailedOverloadResolution:
678 break;
679 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000680
Douglas Gregora9333192010-05-08 17:41:32 +0000681 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682}
Douglas Gregora9333192010-05-08 17:41:32 +0000683
684const TemplateArgument *
685OverloadCandidate::DeductionFailureInfo::getSecondArg() {
686 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
687 case Sema::TDK_Success:
688 case Sema::TDK_InstantiationDepth:
689 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000690 case Sema::TDK_TooManyArguments:
691 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000692 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000693 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000694 return 0;
695
Douglas Gregora9333192010-05-08 17:41:32 +0000696 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000697 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000698 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
699
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000700 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000701 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000702 case Sema::TDK_FailedOverloadResolution:
703 break;
704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000705
Douglas Gregora9333192010-05-08 17:41:32 +0000706 return 0;
707}
708
709void OverloadCandidateSet::clear() {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000710 for (iterator i = begin(), e = end(); i != e; ++i)
711 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
712 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000713 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000714 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000715 Functions.clear();
716}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000717
John McCall5acb0c92011-10-17 18:40:02 +0000718namespace {
719 class UnbridgedCastsSet {
720 struct Entry {
721 Expr **Addr;
722 Expr *Saved;
723 };
724 SmallVector<Entry, 2> Entries;
725
726 public:
727 void save(Sema &S, Expr *&E) {
728 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
729 Entry entry = { &E, E };
730 Entries.push_back(entry);
731 E = S.stripARCUnbridgedCast(E);
732 }
733
734 void restore() {
735 for (SmallVectorImpl<Entry>::iterator
736 i = Entries.begin(), e = Entries.end(); i != e; ++i)
737 *i->Addr = i->Saved;
738 }
739 };
740}
741
742/// checkPlaceholderForOverload - Do any interesting placeholder-like
743/// preprocessing on the given expression.
744///
745/// \param unbridgedCasts a collection to which to add unbridged casts;
746/// without this, they will be immediately diagnosed as errors
747///
748/// Return true on unrecoverable error.
749static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
750 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000751 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
752 // We can't handle overloaded expressions here because overload
753 // resolution might reasonably tweak them.
754 if (placeholder->getKind() == BuiltinType::Overload) return false;
755
756 // If the context potentially accepts unbridged ARC casts, strip
757 // the unbridged cast and add it to the collection for later restoration.
758 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
759 unbridgedCasts) {
760 unbridgedCasts->save(S, E);
761 return false;
762 }
763
764 // Go ahead and check everything else.
765 ExprResult result = S.CheckPlaceholderExpr(E);
766 if (result.isInvalid())
767 return true;
768
769 E = result.take();
770 return false;
771 }
772
773 // Nothing to do.
774 return false;
775}
776
777/// checkArgPlaceholdersForOverload - Check a set of call operands for
778/// placeholders.
779static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
780 unsigned numArgs,
781 UnbridgedCastsSet &unbridged) {
782 for (unsigned i = 0; i != numArgs; ++i)
783 if (checkPlaceholderForOverload(S, args[i], &unbridged))
784 return true;
785
786 return false;
787}
788
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000790// overload of the declarations in Old. This routine returns false if
791// New and Old cannot be overloaded, e.g., if New has the same
792// signature as some function in Old (C++ 1.3.10) or if the Old
793// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000794// it does return false, MatchedDecl will point to the decl that New
795// cannot be overloaded with. This decl may be a UsingShadowDecl on
796// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797//
798// Example: Given the following input:
799//
800// void f(int, float); // #1
801// void f(int, int); // #2
802// int f(int, int); // #3
803//
804// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000805// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000806//
John McCall51fa86f2009-12-02 08:47:38 +0000807// When we process #2, Old contains only the FunctionDecl for #1. By
808// comparing the parameter types, we see that #1 and #2 are overloaded
809// (since they have different signatures), so this routine returns
810// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000811//
John McCall51fa86f2009-12-02 08:47:38 +0000812// When we process #3, Old is an overload set containing #1 and #2. We
813// compare the signatures of #3 to #1 (they're overloaded, so we do
814// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
815// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816// signature), IsOverload returns false and MatchedDecl will be set to
817// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000818//
819// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
820// into a class by a using declaration. The rules for whether to hide
821// shadow declarations ignore some properties which otherwise figure
822// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000823Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000824Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
825 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000826 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000827 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000828 NamedDecl *OldD = *I;
829
830 bool OldIsUsingDecl = false;
831 if (isa<UsingShadowDecl>(OldD)) {
832 OldIsUsingDecl = true;
833
834 // We can always introduce two using declarations into the same
835 // context, even if they have identical signatures.
836 if (NewIsUsingDecl) continue;
837
838 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
839 }
840
841 // If either declaration was introduced by a using declaration,
842 // we'll need to use slightly different rules for matching.
843 // Essentially, these rules are the normal rules, except that
844 // function templates hide function templates with different
845 // return types or template parameter lists.
846 bool UseMemberUsingDeclRules =
847 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
848
John McCall51fa86f2009-12-02 08:47:38 +0000849 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000850 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
851 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
852 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
853 continue;
854 }
855
John McCall871b2e72009-12-09 03:35:25 +0000856 Match = *I;
857 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000858 }
John McCall51fa86f2009-12-02 08:47:38 +0000859 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000860 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
861 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
862 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
863 continue;
864 }
865
John McCall871b2e72009-12-09 03:35:25 +0000866 Match = *I;
867 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000868 }
John McCalld7945c62010-11-10 03:01:53 +0000869 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000870 // We can overload with these, which can show up when doing
871 // redeclaration checks for UsingDecls.
872 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000873 } else if (isa<TagDecl>(OldD)) {
874 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000875 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
876 // Optimistically assume that an unresolved using decl will
877 // overload; if it doesn't, we'll have to diagnose during
878 // template instantiation.
879 } else {
John McCall68263142009-11-18 22:49:29 +0000880 // (C++ 13p1):
881 // Only function declarations can be overloaded; object and type
882 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000883 Match = *I;
884 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000885 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000886 }
John McCall68263142009-11-18 22:49:29 +0000887
John McCall871b2e72009-12-09 03:35:25 +0000888 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000889}
890
John McCallad00b772010-06-16 08:42:20 +0000891bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
892 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000893 // If both of the functions are extern "C", then they are not
894 // overloads.
895 if (Old->isExternC() && New->isExternC())
896 return false;
897
John McCall68263142009-11-18 22:49:29 +0000898 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
899 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
900
901 // C++ [temp.fct]p2:
902 // A function template can be overloaded with other function templates
903 // and with normal (non-template) functions.
904 if ((OldTemplate == 0) != (NewTemplate == 0))
905 return true;
906
907 // Is the function New an overload of the function Old?
908 QualType OldQType = Context.getCanonicalType(Old->getType());
909 QualType NewQType = Context.getCanonicalType(New->getType());
910
911 // Compare the signatures (C++ 1.3.10) of the two functions to
912 // determine whether they are overloads. If we find any mismatch
913 // in the signature, they are overloads.
914
915 // If either of these functions is a K&R-style function (no
916 // prototype), then we consider them to have matching signatures.
917 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
918 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
919 return false;
920
John McCallf4c73712011-01-19 06:33:43 +0000921 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
922 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000923
924 // The signature of a function includes the types of its
925 // parameters (C++ 1.3.10), which includes the presence or absence
926 // of the ellipsis; see C++ DR 357).
927 if (OldQType != NewQType &&
928 (OldType->getNumArgs() != NewType->getNumArgs() ||
929 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000930 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000931 return true;
932
933 // C++ [temp.over.link]p4:
934 // The signature of a function template consists of its function
935 // signature, its return type and its template parameter list. The names
936 // of the template parameters are significant only for establishing the
937 // relationship between the template parameters and the rest of the
938 // signature.
939 //
940 // We check the return type and template parameter lists for function
941 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000942 //
943 // However, we don't consider either of these when deciding whether
944 // a member introduced by a shadow declaration is hidden.
945 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000946 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
947 OldTemplate->getTemplateParameters(),
948 false, TPL_TemplateMatch) ||
949 OldType->getResultType() != NewType->getResultType()))
950 return true;
951
952 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000953 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000954 //
955 // As part of this, also check whether one of the member functions
956 // is static, in which case they are not overloads (C++
957 // 13.1p2). While not part of the definition of the signature,
958 // this check is important to determine whether these functions
959 // can be overloaded.
960 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
961 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
962 if (OldMethod && NewMethod &&
963 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000964 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000965 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
966 if (!UseUsingDeclRules &&
967 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
968 (OldMethod->getRefQualifier() == RQ_None ||
969 NewMethod->getRefQualifier() == RQ_None)) {
970 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971 // - Member function declarations with the same name and the same
972 // parameter-type-list as well as member function template
973 // declarations with the same name, the same parameter-type-list, and
974 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000975 // them, but not all, have a ref-qualifier (8.3.5).
976 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
977 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
978 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
979 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000980
John McCall68263142009-11-18 22:49:29 +0000981 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000982 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983
John McCall68263142009-11-18 22:49:29 +0000984 // The signatures match; this is not an overload.
985 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000986}
987
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000988/// \brief Checks availability of the function depending on the current
989/// function context. Inside an unavailable function, unavailability is ignored.
990///
991/// \returns true if \arg FD is unavailable and current context is inside
992/// an available function, false otherwise.
993bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
994 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
995}
996
Sebastian Redlcf15cef2011-12-22 18:58:38 +0000997/// \brief Tries a user-defined conversion from From to ToType.
998///
999/// Produces an implicit conversion sequence for when a standard conversion
1000/// is not an option. See TryImplicitConversion for more information.
1001static ImplicitConversionSequence
1002TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1003 bool SuppressUserConversions,
1004 bool AllowExplicit,
1005 bool InOverloadResolution,
1006 bool CStyle,
1007 bool AllowObjCWritebackConversion) {
1008 ImplicitConversionSequence ICS;
1009
1010 if (SuppressUserConversions) {
1011 // We're not in the case above, so there is no conversion that
1012 // we can perform.
1013 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1014 return ICS;
1015 }
1016
1017 // Attempt user-defined conversion.
1018 OverloadCandidateSet Conversions(From->getExprLoc());
1019 OverloadingResult UserDefResult
1020 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1021 AllowExplicit);
1022
1023 if (UserDefResult == OR_Success) {
1024 ICS.setUserDefined();
1025 // C++ [over.ics.user]p4:
1026 // A conversion of an expression of class type to the same class
1027 // type is given Exact Match rank, and a conversion of an
1028 // expression of class type to a base class of that type is
1029 // given Conversion rank, in spite of the fact that a copy
1030 // constructor (i.e., a user-defined conversion function) is
1031 // called for those cases.
1032 if (CXXConstructorDecl *Constructor
1033 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1034 QualType FromCanon
1035 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1036 QualType ToCanon
1037 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1038 if (Constructor->isCopyConstructor() &&
1039 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1040 // Turn this into a "standard" conversion sequence, so that it
1041 // gets ranked with standard conversion sequences.
1042 ICS.setStandard();
1043 ICS.Standard.setAsIdentityConversion();
1044 ICS.Standard.setFromType(From->getType());
1045 ICS.Standard.setAllToTypes(ToType);
1046 ICS.Standard.CopyConstructor = Constructor;
1047 if (ToCanon != FromCanon)
1048 ICS.Standard.Second = ICK_Derived_To_Base;
1049 }
1050 }
1051
1052 // C++ [over.best.ics]p4:
1053 // However, when considering the argument of a user-defined
1054 // conversion function that is a candidate by 13.3.1.3 when
1055 // invoked for the copying of the temporary in the second step
1056 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1057 // 13.3.1.6 in all cases, only standard conversion sequences and
1058 // ellipsis conversion sequences are allowed.
1059 if (SuppressUserConversions && ICS.isUserDefined()) {
1060 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1061 }
1062 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1063 ICS.setAmbiguous();
1064 ICS.Ambiguous.setFromType(From->getType());
1065 ICS.Ambiguous.setToType(ToType);
1066 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1067 Cand != Conversions.end(); ++Cand)
1068 if (Cand->Viable)
1069 ICS.Ambiguous.addConversion(Cand->Function);
1070 } else {
1071 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1072 }
1073
1074 return ICS;
1075}
1076
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001077/// TryImplicitConversion - Attempt to perform an implicit conversion
1078/// from the given expression (Expr) to the given type (ToType). This
1079/// function returns an implicit conversion sequence that can be used
1080/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001081///
1082/// void f(float f);
1083/// void g(int i) { f(i); }
1084///
1085/// this routine would produce an implicit conversion sequence to
1086/// describe the initialization of f from i, which will be a standard
1087/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1088/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1089//
1090/// Note that this routine only determines how the conversion can be
1091/// performed; it does not actually perform the conversion. As such,
1092/// it will not produce any diagnostics if no conversion is available,
1093/// but will instead return an implicit conversion sequence of kind
1094/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001095///
1096/// If @p SuppressUserConversions, then user-defined conversions are
1097/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001098/// If @p AllowExplicit, then explicit user-defined conversions are
1099/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001100///
1101/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1102/// writeback conversion, which allows __autoreleasing id* parameters to
1103/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001104static ImplicitConversionSequence
1105TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1106 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001107 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001108 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001109 bool CStyle,
1110 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001111 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001112 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001113 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001114 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001115 return ICS;
1116 }
1117
David Blaikie4e4d0842012-03-11 07:00:24 +00001118 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001119 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001120 return ICS;
1121 }
1122
Douglas Gregor604eb652010-08-11 02:15:33 +00001123 // C++ [over.ics.user]p4:
1124 // A conversion of an expression of class type to the same class
1125 // type is given Exact Match rank, and a conversion of an
1126 // expression of class type to a base class of that type is
1127 // given Conversion rank, in spite of the fact that a copy/move
1128 // constructor (i.e., a user-defined conversion function) is
1129 // called for those cases.
1130 QualType FromType = From->getType();
1131 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001132 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1133 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001134 ICS.setStandard();
1135 ICS.Standard.setAsIdentityConversion();
1136 ICS.Standard.setFromType(FromType);
1137 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001138
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001139 // We don't actually check at this point whether there is a valid
1140 // copy/move constructor, since overloading just assumes that it
1141 // exists. When we actually perform initialization, we'll find the
1142 // appropriate constructor to copy the returned object, if needed.
1143 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001144
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001145 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001146 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001147 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001148
Douglas Gregor604eb652010-08-11 02:15:33 +00001149 return ICS;
1150 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001151
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001152 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1153 AllowExplicit, InOverloadResolution, CStyle,
1154 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001155}
1156
John McCallf85e1932011-06-15 23:02:42 +00001157ImplicitConversionSequence
1158Sema::TryImplicitConversion(Expr *From, QualType ToType,
1159 bool SuppressUserConversions,
1160 bool AllowExplicit,
1161 bool InOverloadResolution,
1162 bool CStyle,
1163 bool AllowObjCWritebackConversion) {
1164 return clang::TryImplicitConversion(*this, From, ToType,
1165 SuppressUserConversions, AllowExplicit,
1166 InOverloadResolution, CStyle,
1167 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001168}
1169
Douglas Gregor575c63a2010-04-16 22:27:05 +00001170/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001171/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001172/// converted expression. Flavor is the kind of conversion we're
1173/// performing, used in the error message. If @p AllowExplicit,
1174/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001175ExprResult
1176Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001177 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001178 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001179 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001180}
1181
John Wiegley429bb272011-04-08 18:41:53 +00001182ExprResult
1183Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001184 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001185 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001186 if (checkPlaceholderForOverload(*this, From))
1187 return ExprError();
1188
John McCallf85e1932011-06-15 23:02:42 +00001189 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1190 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001191 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001192 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001193
John McCall120d63c2010-08-24 20:38:10 +00001194 ICS = clang::TryImplicitConversion(*this, From, ToType,
1195 /*SuppressUserConversions=*/false,
1196 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001197 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001198 /*CStyle=*/false,
1199 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001200 return PerformImplicitConversion(From, ToType, ICS, Action);
1201}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001202
1203/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001204/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001205bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1206 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001207 if (Context.hasSameUnqualifiedType(FromType, ToType))
1208 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001209
John McCall00ccbef2010-12-21 00:44:39 +00001210 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1211 // where F adds one of the following at most once:
1212 // - a pointer
1213 // - a member pointer
1214 // - a block pointer
1215 CanQualType CanTo = Context.getCanonicalType(ToType);
1216 CanQualType CanFrom = Context.getCanonicalType(FromType);
1217 Type::TypeClass TyClass = CanTo->getTypeClass();
1218 if (TyClass != CanFrom->getTypeClass()) return false;
1219 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1220 if (TyClass == Type::Pointer) {
1221 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1222 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1223 } else if (TyClass == Type::BlockPointer) {
1224 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1225 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1226 } else if (TyClass == Type::MemberPointer) {
1227 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1228 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1229 } else {
1230 return false;
1231 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001232
John McCall00ccbef2010-12-21 00:44:39 +00001233 TyClass = CanTo->getTypeClass();
1234 if (TyClass != CanFrom->getTypeClass()) return false;
1235 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1236 return false;
1237 }
1238
1239 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1240 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1241 if (!EInfo.getNoReturn()) return false;
1242
1243 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1244 assert(QualType(FromFn, 0).isCanonical());
1245 if (QualType(FromFn, 0) != CanTo) return false;
1246
1247 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001248 return true;
1249}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001251/// \brief Determine whether the conversion from FromType to ToType is a valid
1252/// vector conversion.
1253///
1254/// \param ICK Will be set to the vector conversion kind, if this is a vector
1255/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001256static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1257 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001258 // We need at least one of these types to be a vector type to have a vector
1259 // conversion.
1260 if (!ToType->isVectorType() && !FromType->isVectorType())
1261 return false;
1262
1263 // Identical types require no conversions.
1264 if (Context.hasSameUnqualifiedType(FromType, ToType))
1265 return false;
1266
1267 // There are no conversions between extended vector types, only identity.
1268 if (ToType->isExtVectorType()) {
1269 // There are no conversions between extended vector types other than the
1270 // identity conversion.
1271 if (FromType->isExtVectorType())
1272 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001273
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001274 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001275 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001276 ICK = ICK_Vector_Splat;
1277 return true;
1278 }
1279 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001280
1281 // We can perform the conversion between vector types in the following cases:
1282 // 1)vector types are equivalent AltiVec and GCC vector types
1283 // 2)lax vector conversions are permitted and the vector types are of the
1284 // same size
1285 if (ToType->isVectorType() && FromType->isVectorType()) {
1286 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001287 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001288 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001289 ICK = ICK_Vector_Conversion;
1290 return true;
1291 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001292 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001293
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001294 return false;
1295}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001296
Douglas Gregor7d000652012-04-12 20:48:09 +00001297static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1298 bool InOverloadResolution,
1299 StandardConversionSequence &SCS,
1300 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001301
Douglas Gregor60d62c22008-10-31 16:23:19 +00001302/// IsStandardConversion - Determines whether there is a standard
1303/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1304/// expression From to the type ToType. Standard conversion sequences
1305/// only consider non-class types; for conversions that involve class
1306/// types, use TryImplicitConversion. If a conversion exists, SCS will
1307/// contain the standard conversion sequence required to perform this
1308/// conversion and this routine will return true. Otherwise, this
1309/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001310static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1311 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001312 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001313 bool CStyle,
1314 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001315 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001316
Douglas Gregor60d62c22008-10-31 16:23:19 +00001317 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001318 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001319 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001320 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001321 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001322 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001323
Douglas Gregorf9201e02009-02-11 23:02:49 +00001324 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001325 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001326 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001327 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001328 return false;
1329
Mike Stump1eb44332009-09-09 15:08:12 +00001330 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001331 }
1332
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001333 // The first conversion can be an lvalue-to-rvalue conversion,
1334 // array-to-pointer conversion, or function-to-pointer conversion
1335 // (C++ 4p1).
1336
John McCall120d63c2010-08-24 20:38:10 +00001337 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001338 DeclAccessPair AccessPair;
1339 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001340 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001341 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001342 // We were able to resolve the address of the overloaded function,
1343 // so we can convert to the type of that function.
1344 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001345
1346 // we can sometimes resolve &foo<int> regardless of ToType, so check
1347 // if the type matches (identity) or we are converting to bool
1348 if (!S.Context.hasSameUnqualifiedType(
1349 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1350 QualType resultTy;
1351 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001352 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001353 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1354 // otherwise, only a boolean conversion is standard
1355 if (!ToType->isBooleanType())
1356 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001358
Chandler Carruth90434232011-03-29 08:08:18 +00001359 // Check if the "from" expression is taking the address of an overloaded
1360 // function and recompute the FromType accordingly. Take advantage of the
1361 // fact that non-static member functions *must* have such an address-of
1362 // expression.
1363 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1364 if (Method && !Method->isStatic()) {
1365 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1366 "Non-unary operator on non-static member address");
1367 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1368 == UO_AddrOf &&
1369 "Non-address-of operator on non-static member address");
1370 const Type *ClassType
1371 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1372 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001373 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1374 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1375 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001376 "Non-address-of operator for overloaded function expression");
1377 FromType = S.Context.getPointerType(FromType);
1378 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001379
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001380 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001381 assert(S.Context.hasSameType(
1382 FromType,
1383 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001384 } else {
1385 return false;
1386 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001387 }
John McCall21480112011-08-30 00:57:29 +00001388 // Lvalue-to-rvalue conversion (C++11 4.1):
1389 // A glvalue (3.10) of a non-function, non-array type T can
1390 // be converted to a prvalue.
1391 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001392 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001393 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001394 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001395 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001396
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001397 // C11 6.3.2.1p2:
1398 // ... if the lvalue has atomic type, the value has the non-atomic version
1399 // of the type of the lvalue ...
1400 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1401 FromType = Atomic->getValueType();
1402
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001403 // If T is a non-class type, the type of the rvalue is the
1404 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001405 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1406 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001407 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001408 } else if (FromType->isArrayType()) {
1409 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001410 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001411
1412 // An lvalue or rvalue of type "array of N T" or "array of unknown
1413 // bound of T" can be converted to an rvalue of type "pointer to
1414 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001415 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001416
John McCall120d63c2010-08-24 20:38:10 +00001417 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001418 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001419 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001420
1421 // For the purpose of ranking in overload resolution
1422 // (13.3.3.1.1), this conversion is considered an
1423 // array-to-pointer conversion followed by a qualification
1424 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001425 SCS.Second = ICK_Identity;
1426 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001427 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001428 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001429 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001431 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001432 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001433 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001434
1435 // An lvalue of function type T can be converted to an rvalue of
1436 // type "pointer to T." The result is a pointer to the
1437 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001438 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001439 } else {
1440 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001441 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001443 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001444
1445 // The second conversion can be an integral promotion, floating
1446 // point promotion, integral conversion, floating point conversion,
1447 // floating-integral conversion, pointer conversion,
1448 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001449 // For overloading in C, this can also be a "compatible-type"
1450 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001451 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001452 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001453 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001454 // The unqualified versions of the types are the same: there's no
1455 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001456 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001457 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001458 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001459 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001460 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001461 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001462 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001463 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001464 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001465 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001466 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001467 SCS.Second = ICK_Complex_Promotion;
1468 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001469 } else if (ToType->isBooleanType() &&
1470 (FromType->isArithmeticType() ||
1471 FromType->isAnyPointerType() ||
1472 FromType->isBlockPointerType() ||
1473 FromType->isMemberPointerType() ||
1474 FromType->isNullPtrType())) {
1475 // Boolean conversions (C++ 4.12).
1476 SCS.Second = ICK_Boolean_Conversion;
1477 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001478 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001479 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001480 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001481 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001482 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001483 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001484 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001485 SCS.Second = ICK_Complex_Conversion;
1486 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001487 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1488 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001489 // Complex-real conversions (C99 6.3.1.7)
1490 SCS.Second = ICK_Complex_Real;
1491 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001492 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001493 // Floating point conversions (C++ 4.8).
1494 SCS.Second = ICK_Floating_Conversion;
1495 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001496 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001497 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001498 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001499 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001500 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001501 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001502 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001503 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001504 SCS.Second = ICK_Block_Pointer_Conversion;
1505 } else if (AllowObjCWritebackConversion &&
1506 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1507 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001508 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1509 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001510 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001511 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001512 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001513 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001515 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001516 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001517 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001518 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001519 SCS.Second = SecondICK;
1520 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001521 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001522 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001523 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001524 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001525 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001526 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001527 // Treat a conversion that strips "noreturn" as an identity conversion.
1528 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001529 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1530 InOverloadResolution,
1531 SCS, CStyle)) {
1532 SCS.Second = ICK_TransparentUnionConversion;
1533 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001534 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1535 CStyle)) {
1536 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001537 // appropriately.
1538 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539 } else {
1540 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001541 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001542 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001543 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001544
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001545 QualType CanonFrom;
1546 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001547 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001548 bool ObjCLifetimeConversion;
1549 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1550 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001551 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001552 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001554 CanonFrom = S.Context.getCanonicalType(FromType);
1555 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001556 } else {
1557 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001558 SCS.Third = ICK_Identity;
1559
Mike Stump1eb44332009-09-09 15:08:12 +00001560 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001561 // [...] Any difference in top-level cv-qualification is
1562 // subsumed by the initialization itself and does not constitute
1563 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001564 CanonFrom = S.Context.getCanonicalType(FromType);
1565 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001566 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001567 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001568 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001569 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1570 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001571 FromType = ToType;
1572 CanonFrom = CanonTo;
1573 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001574 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001575 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001576
1577 // If we have not converted the argument type to the parameter type,
1578 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001579 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001580 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001581
Douglas Gregor60d62c22008-10-31 16:23:19 +00001582 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001583}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001584
1585static bool
1586IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1587 QualType &ToType,
1588 bool InOverloadResolution,
1589 StandardConversionSequence &SCS,
1590 bool CStyle) {
1591
1592 const RecordType *UT = ToType->getAsUnionType();
1593 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1594 return false;
1595 // The field to initialize within the transparent union.
1596 RecordDecl *UD = UT->getDecl();
1597 // It's compatible if the expression matches any of the fields.
1598 for (RecordDecl::field_iterator it = UD->field_begin(),
1599 itend = UD->field_end();
1600 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001601 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1602 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001603 ToType = it->getType();
1604 return true;
1605 }
1606 }
1607 return false;
1608}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001609
1610/// IsIntegralPromotion - Determines whether the conversion from the
1611/// expression From (whose potentially-adjusted type is FromType) to
1612/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1613/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001614bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001615 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001616 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001617 if (!To) {
1618 return false;
1619 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001620
1621 // An rvalue of type char, signed char, unsigned char, short int, or
1622 // unsigned short int can be converted to an rvalue of type int if
1623 // int can represent all the values of the source type; otherwise,
1624 // the source rvalue can be converted to an rvalue of type unsigned
1625 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001626 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1627 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001628 if (// We can promote any signed, promotable integer type to an int
1629 (FromType->isSignedIntegerType() ||
1630 // We can promote any unsigned integer type whose size is
1631 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001632 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001633 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001634 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001635 }
1636
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001637 return To->getKind() == BuiltinType::UInt;
1638 }
1639
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001640 // C++0x [conv.prom]p3:
1641 // A prvalue of an unscoped enumeration type whose underlying type is not
1642 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1643 // following types that can represent all the values of the enumeration
1644 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1645 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001646 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001647 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001648 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001649 // with lowest integer conversion rank (4.13) greater than the rank of long
1650 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001651 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001652 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1653 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1654 // provided for a scoped enumeration.
1655 if (FromEnumType->getDecl()->isScoped())
1656 return false;
1657
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001658 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001659 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001660 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001661 return Context.hasSameUnqualifiedType(ToType,
1662 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001663 }
John McCall842aef82009-12-09 09:09:27 +00001664
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001665 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001666 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1667 // to an rvalue a prvalue of the first of the following types that can
1668 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001669 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001671 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001672 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001673 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001674 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001675 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676 // Determine whether the type we're converting from is signed or
1677 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001678 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001679 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001681 // The types we'll try to promote to, in the appropriate
1682 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001683 QualType PromoteTypes[6] = {
1684 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001685 Context.LongTy, Context.UnsignedLongTy ,
1686 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001687 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001688 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001689 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1690 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001691 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001692 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1693 // We found the type that we can promote to. If this is the
1694 // type we wanted, we have a promotion. Otherwise, no
1695 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001696 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001697 }
1698 }
1699 }
1700
1701 // An rvalue for an integral bit-field (9.6) can be converted to an
1702 // rvalue of type int if int can represent all the values of the
1703 // bit-field; otherwise, it can be converted to unsigned int if
1704 // unsigned int can represent all the values of the bit-field. If
1705 // the bit-field is larger yet, no integral promotion applies to
1706 // it. If the bit-field has an enumerated type, it is treated as any
1707 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001708 // FIXME: We should delay checking of bit-fields until we actually perform the
1709 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001710 using llvm::APSInt;
1711 if (From)
1712 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001713 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001714 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001715 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1716 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1717 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Douglas Gregor86f19402008-12-20 23:49:58 +00001719 // Are we promoting to an int from a bitfield that fits in an int?
1720 if (BitWidth < ToSize ||
1721 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1722 return To->getKind() == BuiltinType::Int;
1723 }
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Douglas Gregor86f19402008-12-20 23:49:58 +00001725 // Are we promoting to an unsigned int from an unsigned bitfield
1726 // that fits into an unsigned int?
1727 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1728 return To->getKind() == BuiltinType::UInt;
1729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Douglas Gregor86f19402008-12-20 23:49:58 +00001731 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001732 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001733 }
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001735 // An rvalue of type bool can be converted to an rvalue of type int,
1736 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001737 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001738 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001739 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001740
1741 return false;
1742}
1743
1744/// IsFloatingPointPromotion - Determines whether the conversion from
1745/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1746/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001747bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001748 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1749 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001750 /// An rvalue of type float can be converted to an rvalue of type
1751 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001752 if (FromBuiltin->getKind() == BuiltinType::Float &&
1753 ToBuiltin->getKind() == BuiltinType::Double)
1754 return true;
1755
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001756 // C99 6.3.1.5p1:
1757 // When a float is promoted to double or long double, or a
1758 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001759 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001760 (FromBuiltin->getKind() == BuiltinType::Float ||
1761 FromBuiltin->getKind() == BuiltinType::Double) &&
1762 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1763 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001764
1765 // Half can be promoted to float.
1766 if (FromBuiltin->getKind() == BuiltinType::Half &&
1767 ToBuiltin->getKind() == BuiltinType::Float)
1768 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001769 }
1770
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001771 return false;
1772}
1773
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001774/// \brief Determine if a conversion is a complex promotion.
1775///
1776/// A complex promotion is defined as a complex -> complex conversion
1777/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001778/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001779bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001780 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001781 if (!FromComplex)
1782 return false;
1783
John McCall183700f2009-09-21 23:43:11 +00001784 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001785 if (!ToComplex)
1786 return false;
1787
1788 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001789 ToComplex->getElementType()) ||
1790 IsIntegralPromotion(0, FromComplex->getElementType(),
1791 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001792}
1793
Douglas Gregorcb7de522008-11-26 23:31:11 +00001794/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1795/// the pointer type FromPtr to a pointer to type ToPointee, with the
1796/// same type qualifiers as FromPtr has on its pointee type. ToType,
1797/// if non-empty, will be a pointer to ToType that may or may not have
1798/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001799///
Mike Stump1eb44332009-09-09 15:08:12 +00001800static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001801BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001802 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001803 ASTContext &Context,
1804 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001805 assert((FromPtr->getTypeClass() == Type::Pointer ||
1806 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1807 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001808
John McCallf85e1932011-06-15 23:02:42 +00001809 /// Conversions to 'id' subsume cv-qualifier conversions.
1810 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001811 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001812
1813 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001814 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001815 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001816 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001817
John McCallf85e1932011-06-15 23:02:42 +00001818 if (StripObjCLifetime)
1819 Quals.removeObjCLifetime();
1820
Mike Stump1eb44332009-09-09 15:08:12 +00001821 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001822 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001823 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001824 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001825 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001826
1827 // Build a pointer to ToPointee. It has the right qualifiers
1828 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001829 if (isa<ObjCObjectPointerType>(ToType))
1830 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001831 return Context.getPointerType(ToPointee);
1832 }
1833
1834 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001835 QualType QualifiedCanonToPointee
1836 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001837
Douglas Gregorda80f742010-12-01 21:43:58 +00001838 if (isa<ObjCObjectPointerType>(ToType))
1839 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1840 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001841}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001842
Mike Stump1eb44332009-09-09 15:08:12 +00001843static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001844 bool InOverloadResolution,
1845 ASTContext &Context) {
1846 // Handle value-dependent integral null pointer constants correctly.
1847 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1848 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001849 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001850 return !InOverloadResolution;
1851
Douglas Gregorce940492009-09-25 04:25:58 +00001852 return Expr->isNullPointerConstant(Context,
1853 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1854 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001855}
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001857/// IsPointerConversion - Determines whether the conversion of the
1858/// expression From, which has the (possibly adjusted) type FromType,
1859/// can be converted to the type ToType via a pointer conversion (C++
1860/// 4.10). If so, returns true and places the converted type (that
1861/// might differ from ToType in its cv-qualifiers at some level) into
1862/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001863///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001864/// This routine also supports conversions to and from block pointers
1865/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1866/// pointers to interfaces. FIXME: Once we've determined the
1867/// appropriate overloading rules for Objective-C, we may want to
1868/// split the Objective-C checks into a different routine; however,
1869/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001870/// conversions, so for now they live here. IncompatibleObjC will be
1871/// set if the conversion is an allowed Objective-C conversion that
1872/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001873bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001874 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001875 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001876 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001877 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001878 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1879 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001880 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001881
Mike Stump1eb44332009-09-09 15:08:12 +00001882 // Conversion from a null pointer constant to any Objective-C pointer type.
1883 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001884 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001885 ConvertedType = ToType;
1886 return true;
1887 }
1888
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001889 // Blocks: Block pointers can be converted to void*.
1890 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001891 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001892 ConvertedType = ToType;
1893 return true;
1894 }
1895 // Blocks: A null pointer constant can be converted to a block
1896 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001897 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001898 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001899 ConvertedType = ToType;
1900 return true;
1901 }
1902
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001903 // If the left-hand-side is nullptr_t, the right side can be a null
1904 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001905 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001906 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001907 ConvertedType = ToType;
1908 return true;
1909 }
1910
Ted Kremenek6217b802009-07-29 21:53:49 +00001911 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001912 if (!ToTypePtr)
1913 return false;
1914
1915 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001916 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001917 ConvertedType = ToType;
1918 return true;
1919 }
Sebastian Redl07779722008-10-31 14:43:28 +00001920
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001922 // , including objective-c pointers.
1923 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001924 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001925 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001926 ConvertedType = BuildSimilarlyQualifiedPointerType(
1927 FromType->getAs<ObjCObjectPointerType>(),
1928 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001929 ToType, Context);
1930 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001931 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001932 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001933 if (!FromTypePtr)
1934 return false;
1935
1936 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001937
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001938 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001939 // pointer conversion, so don't do all of the work below.
1940 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1941 return false;
1942
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001943 // An rvalue of type "pointer to cv T," where T is an object type,
1944 // can be converted to an rvalue of type "pointer to cv void" (C++
1945 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001946 if (FromPointeeType->isIncompleteOrObjectType() &&
1947 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001948 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001949 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001950 ToType, Context,
1951 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001952 return true;
1953 }
1954
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001955 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001956 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001957 ToPointeeType->isVoidType()) {
1958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1959 ToPointeeType,
1960 ToType, Context);
1961 return true;
1962 }
1963
Douglas Gregorf9201e02009-02-11 23:02:49 +00001964 // When we're overloading in C, we allow a special kind of pointer
1965 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00001966 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001969 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001970 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001971 return true;
1972 }
1973
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001974 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001975 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001976 // An rvalue of type "pointer to cv D," where D is a class type,
1977 // can be converted to an rvalue of type "pointer to cv B," where
1978 // B is a base class (clause 10) of D. If B is an inaccessible
1979 // (clause 11) or ambiguous (10.2) base class of D, a program that
1980 // necessitates this conversion is ill-formed. The result of the
1981 // conversion is a pointer to the base class sub-object of the
1982 // derived class object. The null pointer value is converted to
1983 // the null pointer value of the destination type.
1984 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001985 // Note that we do not check for ambiguity or inaccessibility
1986 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001987 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001989 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001990 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001991 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001992 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001993 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001994 ToType, Context);
1995 return true;
1996 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001997
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001998 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1999 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2000 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2001 ToPointeeType,
2002 ToType, Context);
2003 return true;
2004 }
2005
Douglas Gregorc7887512008-12-19 19:13:09 +00002006 return false;
2007}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002008
2009/// \brief Adopt the given qualifiers for the given type.
2010static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2011 Qualifiers TQs = T.getQualifiers();
2012
2013 // Check whether qualifiers already match.
2014 if (TQs == Qs)
2015 return T;
2016
2017 if (Qs.compatiblyIncludes(TQs))
2018 return Context.getQualifiedType(T, Qs);
2019
2020 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2021}
Douglas Gregorc7887512008-12-19 19:13:09 +00002022
2023/// isObjCPointerConversion - Determines whether this is an
2024/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2025/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002026bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002027 QualType& ConvertedType,
2028 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002029 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002030 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002031
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002032 // The set of qualifiers on the type we're converting from.
2033 Qualifiers FromQualifiers = FromType.getQualifiers();
2034
Steve Naroff14108da2009-07-10 23:34:53 +00002035 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002036 const ObjCObjectPointerType* ToObjCPtr =
2037 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002038 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002039 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002040
Steve Naroff14108da2009-07-10 23:34:53 +00002041 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002042 // If the pointee types are the same (ignoring qualifications),
2043 // then this is not a pointer conversion.
2044 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2045 FromObjCPtr->getPointeeType()))
2046 return false;
2047
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002048 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002049 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002050 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002051 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002052 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002053 return true;
2054 }
2055 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002056 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002057 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002058 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002059 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002060 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002061 return true;
2062 }
2063 // Objective C++: We're able to convert from a pointer to an
2064 // interface to a pointer to a different interface.
2065 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002066 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2067 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002068 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002069 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2070 FromObjCPtr->getPointeeType()))
2071 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002072 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002073 ToObjCPtr->getPointeeType(),
2074 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002075 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002076 return true;
2077 }
2078
2079 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2080 // Okay: this is some kind of implicit downcast of Objective-C
2081 // interfaces, which is permitted. However, we're going to
2082 // complain about it.
2083 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002085 ToObjCPtr->getPointeeType(),
2086 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002087 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002088 return true;
2089 }
Mike Stump1eb44332009-09-09 15:08:12 +00002090 }
Steve Naroff14108da2009-07-10 23:34:53 +00002091 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002092 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002093 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002094 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002096 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002097 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002098 // to a block pointer type.
2099 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002100 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002101 return true;
2102 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002103 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002105 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002106 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002107 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002108 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002109 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002110 return true;
2111 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002112 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002113 return false;
2114
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002115 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002116 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002117 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002118 else if (const BlockPointerType *FromBlockPtr =
2119 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002120 FromPointeeType = FromBlockPtr->getPointeeType();
2121 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002122 return false;
2123
Douglas Gregorc7887512008-12-19 19:13:09 +00002124 // If we have pointers to pointers, recursively check whether this
2125 // is an Objective-C conversion.
2126 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2127 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2128 IncompatibleObjC)) {
2129 // We always complain about this conversion.
2130 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002131 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002132 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002133 return true;
2134 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002135 // Allow conversion of pointee being objective-c pointer to another one;
2136 // as in I* to id.
2137 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2138 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2139 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2140 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002141
Douglas Gregorda80f742010-12-01 21:43:58 +00002142 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002143 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002144 return true;
2145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002147 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002148 // differences in the argument and result types are in Objective-C
2149 // pointer conversions. If so, we permit the conversion (but
2150 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002151 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002152 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002153 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002154 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002155 if (FromFunctionType && ToFunctionType) {
2156 // If the function types are exactly the same, this isn't an
2157 // Objective-C pointer conversion.
2158 if (Context.getCanonicalType(FromPointeeType)
2159 == Context.getCanonicalType(ToPointeeType))
2160 return false;
2161
2162 // Perform the quick checks that will tell us whether these
2163 // function types are obviously different.
2164 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2165 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2166 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2167 return false;
2168
2169 bool HasObjCConversion = false;
2170 if (Context.getCanonicalType(FromFunctionType->getResultType())
2171 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2172 // Okay, the types match exactly. Nothing to do.
2173 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2174 ToFunctionType->getResultType(),
2175 ConvertedType, IncompatibleObjC)) {
2176 // Okay, we have an Objective-C pointer conversion.
2177 HasObjCConversion = true;
2178 } else {
2179 // Function types are too different. Abort.
2180 return false;
2181 }
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Douglas Gregorc7887512008-12-19 19:13:09 +00002183 // Check argument types.
2184 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2185 ArgIdx != NumArgs; ++ArgIdx) {
2186 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2187 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2188 if (Context.getCanonicalType(FromArgType)
2189 == Context.getCanonicalType(ToArgType)) {
2190 // Okay, the types match exactly. Nothing to do.
2191 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2192 ConvertedType, IncompatibleObjC)) {
2193 // Okay, we have an Objective-C pointer conversion.
2194 HasObjCConversion = true;
2195 } else {
2196 // Argument types are too different. Abort.
2197 return false;
2198 }
2199 }
2200
2201 if (HasObjCConversion) {
2202 // We had an Objective-C conversion. Allow this pointer
2203 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002204 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002205 IncompatibleObjC = true;
2206 return true;
2207 }
2208 }
2209
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002210 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002211}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212
John McCallf85e1932011-06-15 23:02:42 +00002213/// \brief Determine whether this is an Objective-C writeback conversion,
2214/// used for parameter passing when performing automatic reference counting.
2215///
2216/// \param FromType The type we're converting form.
2217///
2218/// \param ToType The type we're converting to.
2219///
2220/// \param ConvertedType The type that will be produced after applying
2221/// this conversion.
2222bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2223 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002224 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002225 Context.hasSameUnqualifiedType(FromType, ToType))
2226 return false;
2227
2228 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2229 QualType ToPointee;
2230 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2231 ToPointee = ToPointer->getPointeeType();
2232 else
2233 return false;
2234
2235 Qualifiers ToQuals = ToPointee.getQualifiers();
2236 if (!ToPointee->isObjCLifetimeType() ||
2237 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002238 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002239 return false;
2240
2241 // Argument must be a pointer to __strong to __weak.
2242 QualType FromPointee;
2243 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2244 FromPointee = FromPointer->getPointeeType();
2245 else
2246 return false;
2247
2248 Qualifiers FromQuals = FromPointee.getQualifiers();
2249 if (!FromPointee->isObjCLifetimeType() ||
2250 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2251 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2252 return false;
2253
2254 // Make sure that we have compatible qualifiers.
2255 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2256 if (!ToQuals.compatiblyIncludes(FromQuals))
2257 return false;
2258
2259 // Remove qualifiers from the pointee type we're converting from; they
2260 // aren't used in the compatibility check belong, and we'll be adding back
2261 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2262 FromPointee = FromPointee.getUnqualifiedType();
2263
2264 // The unqualified form of the pointee types must be compatible.
2265 ToPointee = ToPointee.getUnqualifiedType();
2266 bool IncompatibleObjC;
2267 if (Context.typesAreCompatible(FromPointee, ToPointee))
2268 FromPointee = ToPointee;
2269 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2270 IncompatibleObjC))
2271 return false;
2272
2273 /// \brief Construct the type we're converting to, which is a pointer to
2274 /// __autoreleasing pointee.
2275 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2276 ConvertedType = Context.getPointerType(FromPointee);
2277 return true;
2278}
2279
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002280bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2281 QualType& ConvertedType) {
2282 QualType ToPointeeType;
2283 if (const BlockPointerType *ToBlockPtr =
2284 ToType->getAs<BlockPointerType>())
2285 ToPointeeType = ToBlockPtr->getPointeeType();
2286 else
2287 return false;
2288
2289 QualType FromPointeeType;
2290 if (const BlockPointerType *FromBlockPtr =
2291 FromType->getAs<BlockPointerType>())
2292 FromPointeeType = FromBlockPtr->getPointeeType();
2293 else
2294 return false;
2295 // We have pointer to blocks, check whether the only
2296 // differences in the argument and result types are in Objective-C
2297 // pointer conversions. If so, we permit the conversion.
2298
2299 const FunctionProtoType *FromFunctionType
2300 = FromPointeeType->getAs<FunctionProtoType>();
2301 const FunctionProtoType *ToFunctionType
2302 = ToPointeeType->getAs<FunctionProtoType>();
2303
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002304 if (!FromFunctionType || !ToFunctionType)
2305 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002306
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002307 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002308 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002309
2310 // Perform the quick checks that will tell us whether these
2311 // function types are obviously different.
2312 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2313 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2314 return false;
2315
2316 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2317 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2318 if (FromEInfo != ToEInfo)
2319 return false;
2320
2321 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002322 if (Context.hasSameType(FromFunctionType->getResultType(),
2323 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002324 // Okay, the types match exactly. Nothing to do.
2325 } else {
2326 QualType RHS = FromFunctionType->getResultType();
2327 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002328 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002329 !RHS.hasQualifiers() && LHS.hasQualifiers())
2330 LHS = LHS.getUnqualifiedType();
2331
2332 if (Context.hasSameType(RHS,LHS)) {
2333 // OK exact match.
2334 } else if (isObjCPointerConversion(RHS, LHS,
2335 ConvertedType, IncompatibleObjC)) {
2336 if (IncompatibleObjC)
2337 return false;
2338 // Okay, we have an Objective-C pointer conversion.
2339 }
2340 else
2341 return false;
2342 }
2343
2344 // Check argument types.
2345 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2346 ArgIdx != NumArgs; ++ArgIdx) {
2347 IncompatibleObjC = false;
2348 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2349 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2350 if (Context.hasSameType(FromArgType, ToArgType)) {
2351 // Okay, the types match exactly. Nothing to do.
2352 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2353 ConvertedType, IncompatibleObjC)) {
2354 if (IncompatibleObjC)
2355 return false;
2356 // Okay, we have an Objective-C pointer conversion.
2357 } else
2358 // Argument types are too different. Abort.
2359 return false;
2360 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002361 if (LangOpts.ObjCAutoRefCount &&
2362 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2363 ToFunctionType))
2364 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002365
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002366 ConvertedType = ToType;
2367 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002368}
2369
Richard Trieu6efd4c52011-11-23 22:32:32 +00002370enum {
2371 ft_default,
2372 ft_different_class,
2373 ft_parameter_arity,
2374 ft_parameter_mismatch,
2375 ft_return_type,
2376 ft_qualifer_mismatch
2377};
2378
2379/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2380/// function types. Catches different number of parameter, mismatch in
2381/// parameter types, and different return types.
2382void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2383 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002384 // If either type is not valid, include no extra info.
2385 if (FromType.isNull() || ToType.isNull()) {
2386 PDiag << ft_default;
2387 return;
2388 }
2389
Richard Trieu6efd4c52011-11-23 22:32:32 +00002390 // Get the function type from the pointers.
2391 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2392 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2393 *ToMember = ToType->getAs<MemberPointerType>();
2394 if (FromMember->getClass() != ToMember->getClass()) {
2395 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2396 << QualType(FromMember->getClass(), 0);
2397 return;
2398 }
2399 FromType = FromMember->getPointeeType();
2400 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002401 }
2402
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002403 if (FromType->isPointerType())
2404 FromType = FromType->getPointeeType();
2405 if (ToType->isPointerType())
2406 ToType = ToType->getPointeeType();
2407
2408 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002409 FromType = FromType.getNonReferenceType();
2410 ToType = ToType.getNonReferenceType();
2411
Richard Trieu6efd4c52011-11-23 22:32:32 +00002412 // Don't print extra info for non-specialized template functions.
2413 if (FromType->isInstantiationDependentType() &&
2414 !FromType->getAs<TemplateSpecializationType>()) {
2415 PDiag << ft_default;
2416 return;
2417 }
2418
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002419 // No extra info for same types.
2420 if (Context.hasSameType(FromType, ToType)) {
2421 PDiag << ft_default;
2422 return;
2423 }
2424
Richard Trieu6efd4c52011-11-23 22:32:32 +00002425 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2426 *ToFunction = ToType->getAs<FunctionProtoType>();
2427
2428 // Both types need to be function types.
2429 if (!FromFunction || !ToFunction) {
2430 PDiag << ft_default;
2431 return;
2432 }
2433
2434 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2435 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2436 << FromFunction->getNumArgs();
2437 return;
2438 }
2439
2440 // Handle different parameter types.
2441 unsigned ArgPos;
2442 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2443 PDiag << ft_parameter_mismatch << ArgPos + 1
2444 << ToFunction->getArgType(ArgPos)
2445 << FromFunction->getArgType(ArgPos);
2446 return;
2447 }
2448
2449 // Handle different return type.
2450 if (!Context.hasSameType(FromFunction->getResultType(),
2451 ToFunction->getResultType())) {
2452 PDiag << ft_return_type << ToFunction->getResultType()
2453 << FromFunction->getResultType();
2454 return;
2455 }
2456
2457 unsigned FromQuals = FromFunction->getTypeQuals(),
2458 ToQuals = ToFunction->getTypeQuals();
2459 if (FromQuals != ToQuals) {
2460 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2461 return;
2462 }
2463
2464 // Unable to find a difference, so add no extra info.
2465 PDiag << ft_default;
2466}
2467
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002468/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002469/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002470/// they have same number of arguments. This routine assumes that Objective-C
2471/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002472/// If the parameters are different, ArgPos will have the the parameter index
2473/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002475 const FunctionProtoType *NewType,
2476 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002477 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002478 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2479 N = NewType->arg_type_begin(),
2480 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2481 if (!Context.hasSameType(*O, *N)) {
2482 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2483 return false;
2484 }
2485 }
2486 return true;
2487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002488
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002489 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2490 N = NewType->arg_type_begin(),
2491 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2492 QualType ToType = (*O);
2493 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002494 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002495 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2496 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002497 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2498 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2499 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2500 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002501 continue;
2502 }
John McCallc12c5bb2010-05-15 11:32:37 +00002503 else if (const ObjCObjectPointerType *PTTo =
2504 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002505 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002506 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002507 if (Context.hasSameUnqualifiedType(
2508 PTTo->getObjectType()->getBaseType(),
2509 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002510 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002511 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002512 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002513 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002514 }
2515 }
2516 return true;
2517}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002518
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002519/// CheckPointerConversion - Check the pointer conversion from the
2520/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002521/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002522/// conversions for which IsPointerConversion has already returned
2523/// true. It returns true and produces a diagnostic if there was an
2524/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002525bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002526 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002527 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002528 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002529 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002530 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002531
John McCalldaa8e4e2010-11-15 09:13:47 +00002532 Kind = CK_BitCast;
2533
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002534 if (!IsCStyleOrFunctionalCast &&
2535 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2536 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2537 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002538 PDiag(diag::warn_impcast_bool_to_null_pointer)
2539 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002540
John McCall1d9b3b22011-09-09 05:25:32 +00002541 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2542 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002543 QualType FromPointeeType = FromPtrType->getPointeeType(),
2544 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002545
Douglas Gregor5fccd362010-03-03 23:55:11 +00002546 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2547 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002548 // We must have a derived-to-base conversion. Check an
2549 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002550 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2551 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002552 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002553 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002554 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002555
Anders Carlsson61faec12009-09-12 04:46:44 +00002556 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002557 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002558 }
2559 }
John McCall1d9b3b22011-09-09 05:25:32 +00002560 } else if (const ObjCObjectPointerType *ToPtrType =
2561 ToType->getAs<ObjCObjectPointerType>()) {
2562 if (const ObjCObjectPointerType *FromPtrType =
2563 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002564 // Objective-C++ conversions are always okay.
2565 // FIXME: We should have a different class of conversions for the
2566 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002567 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002568 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002569 } else if (FromType->isBlockPointerType()) {
2570 Kind = CK_BlockPointerToObjCPointerCast;
2571 } else {
2572 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002573 }
John McCall1d9b3b22011-09-09 05:25:32 +00002574 } else if (ToType->isBlockPointerType()) {
2575 if (!FromType->isBlockPointerType())
2576 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002577 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002578
2579 // We shouldn't fall into this case unless it's valid for other
2580 // reasons.
2581 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2582 Kind = CK_NullToPointer;
2583
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002584 return false;
2585}
2586
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002587/// IsMemberPointerConversion - Determines whether the conversion of the
2588/// expression From, which has the (possibly adjusted) type FromType, can be
2589/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2590/// If so, returns true and places the converted type (that might differ from
2591/// ToType in its cv-qualifiers at some level) into ConvertedType.
2592bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002593 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002594 bool InOverloadResolution,
2595 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002596 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002597 if (!ToTypePtr)
2598 return false;
2599
2600 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002601 if (From->isNullPointerConstant(Context,
2602 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2603 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002604 ConvertedType = ToType;
2605 return true;
2606 }
2607
2608 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002609 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002610 if (!FromTypePtr)
2611 return false;
2612
2613 // A pointer to member of B can be converted to a pointer to member of D,
2614 // where D is derived from B (C++ 4.11p2).
2615 QualType FromClass(FromTypePtr->getClass(), 0);
2616 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002617
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002618 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2619 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2620 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002621 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2622 ToClass.getTypePtr());
2623 return true;
2624 }
2625
2626 return false;
2627}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002628
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002629/// CheckMemberPointerConversion - Check the member pointer conversion from the
2630/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002631/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002632/// for which IsMemberPointerConversion has already returned true. It returns
2633/// true and produces a diagnostic if there was an error, or returns false
2634/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002635bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002636 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002637 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002638 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002639 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002640 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002641 if (!FromPtrType) {
2642 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002644 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002645 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002646 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002647 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002648 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002649
Ted Kremenek6217b802009-07-29 21:53:49 +00002650 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002651 assert(ToPtrType && "No member pointer cast has a target type "
2652 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002653
Sebastian Redl21593ac2009-01-28 18:33:18 +00002654 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2655 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002656
Sebastian Redl21593ac2009-01-28 18:33:18 +00002657 // FIXME: What about dependent types?
2658 assert(FromClass->isRecordType() && "Pointer into non-class.");
2659 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002660
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002661 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002662 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002663 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2664 assert(DerivationOkay &&
2665 "Should not have been called if derivation isn't OK.");
2666 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002667
Sebastian Redl21593ac2009-01-28 18:33:18 +00002668 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2669 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002670 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2671 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2672 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2673 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002674 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002675
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002676 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002677 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2678 << FromClass << ToClass << QualType(VBase, 0)
2679 << From->getSourceRange();
2680 return true;
2681 }
2682
John McCall6b2accb2010-02-10 09:31:12 +00002683 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002684 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2685 Paths.front(),
2686 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002687
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002688 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002689 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002690 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002691 return false;
2692}
2693
Douglas Gregor98cd5992008-10-21 23:43:52 +00002694/// IsQualificationConversion - Determines whether the conversion from
2695/// an rvalue of type FromType to ToType is a qualification conversion
2696/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002697///
2698/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2699/// when the qualification conversion involves a change in the Objective-C
2700/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002701bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002703 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002704 FromType = Context.getCanonicalType(FromType);
2705 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002706 ObjCLifetimeConversion = false;
2707
Douglas Gregor98cd5992008-10-21 23:43:52 +00002708 // If FromType and ToType are the same type, this is not a
2709 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002710 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002711 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002712
Douglas Gregor98cd5992008-10-21 23:43:52 +00002713 // (C++ 4.4p4):
2714 // A conversion can add cv-qualifiers at levels other than the first
2715 // in multi-level pointers, subject to the following rules: [...]
2716 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002717 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002718 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002719 // Within each iteration of the loop, we check the qualifiers to
2720 // determine if this still looks like a qualification
2721 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002722 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002723 // until there are no more pointers or pointers-to-members left to
2724 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002725 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002726
Douglas Gregor621c92a2011-04-25 18:40:17 +00002727 Qualifiers FromQuals = FromType.getQualifiers();
2728 Qualifiers ToQuals = ToType.getQualifiers();
2729
John McCallf85e1932011-06-15 23:02:42 +00002730 // Objective-C ARC:
2731 // Check Objective-C lifetime conversions.
2732 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2733 UnwrappedAnyPointer) {
2734 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2735 ObjCLifetimeConversion = true;
2736 FromQuals.removeObjCLifetime();
2737 ToQuals.removeObjCLifetime();
2738 } else {
2739 // Qualification conversions cannot cast between different
2740 // Objective-C lifetime qualifiers.
2741 return false;
2742 }
2743 }
2744
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002745 // Allow addition/removal of GC attributes but not changing GC attributes.
2746 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2747 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2748 FromQuals.removeObjCGCAttr();
2749 ToQuals.removeObjCGCAttr();
2750 }
2751
Douglas Gregor98cd5992008-10-21 23:43:52 +00002752 // -- for every j > 0, if const is in cv 1,j then const is in cv
2753 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002754 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002755 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Douglas Gregor98cd5992008-10-21 23:43:52 +00002757 // -- if the cv 1,j and cv 2,j are different, then const is in
2758 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002759 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002760 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002761 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Douglas Gregor98cd5992008-10-21 23:43:52 +00002763 // Keep track of whether all prior cv-qualifiers in the "to" type
2764 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002765 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002766 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002767 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002768
2769 // We are left with FromType and ToType being the pointee types
2770 // after unwrapping the original FromType and ToType the same number
2771 // of types. If we unwrapped any pointers, and if FromType and
2772 // ToType have the same unqualified type (since we checked
2773 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002774 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002775}
2776
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002777/// \brief - Determine whether this is a conversion from a scalar type to an
2778/// atomic type.
2779///
2780/// If successful, updates \c SCS's second and third steps in the conversion
2781/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002782static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2783 bool InOverloadResolution,
2784 StandardConversionSequence &SCS,
2785 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002786 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2787 if (!ToAtomic)
2788 return false;
2789
2790 StandardConversionSequence InnerSCS;
2791 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2792 InOverloadResolution, InnerSCS,
2793 CStyle, /*AllowObjCWritebackConversion=*/false))
2794 return false;
2795
2796 SCS.Second = InnerSCS.Second;
2797 SCS.setToType(1, InnerSCS.getToType(1));
2798 SCS.Third = InnerSCS.Third;
2799 SCS.QualificationIncludesObjCLifetime
2800 = InnerSCS.QualificationIncludesObjCLifetime;
2801 SCS.setToType(2, InnerSCS.getToType(2));
2802 return true;
2803}
2804
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002805static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2806 CXXConstructorDecl *Constructor,
2807 QualType Type) {
2808 const FunctionProtoType *CtorType =
2809 Constructor->getType()->getAs<FunctionProtoType>();
2810 if (CtorType->getNumArgs() > 0) {
2811 QualType FirstArg = CtorType->getArgType(0);
2812 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2813 return true;
2814 }
2815 return false;
2816}
2817
Sebastian Redl56a04282012-02-11 23:51:08 +00002818static OverloadingResult
2819IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2820 CXXRecordDecl *To,
2821 UserDefinedConversionSequence &User,
2822 OverloadCandidateSet &CandidateSet,
2823 bool AllowExplicit) {
2824 DeclContext::lookup_iterator Con, ConEnd;
2825 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2826 Con != ConEnd; ++Con) {
2827 NamedDecl *D = *Con;
2828 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2829
2830 // Find the constructor (which may be a template).
2831 CXXConstructorDecl *Constructor = 0;
2832 FunctionTemplateDecl *ConstructorTmpl
2833 = dyn_cast<FunctionTemplateDecl>(D);
2834 if (ConstructorTmpl)
2835 Constructor
2836 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2837 else
2838 Constructor = cast<CXXConstructorDecl>(D);
2839
2840 bool Usable = !Constructor->isInvalidDecl() &&
2841 S.isInitListConstructor(Constructor) &&
2842 (AllowExplicit || !Constructor->isExplicit());
2843 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002844 // If the first argument is (a reference to) the target type,
2845 // suppress conversions.
2846 bool SuppressUserConversions =
2847 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002848 if (ConstructorTmpl)
2849 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2850 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002851 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002852 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002853 else
2854 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002855 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002856 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002857 }
2858 }
2859
2860 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2861
2862 OverloadCandidateSet::iterator Best;
2863 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2864 case OR_Success: {
2865 // Record the standard conversion we used and the conversion function.
2866 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2867 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2868
2869 QualType ThisType = Constructor->getThisType(S.Context);
2870 // Initializer lists don't have conversions as such.
2871 User.Before.setAsIdentityConversion();
2872 User.HadMultipleCandidates = HadMultipleCandidates;
2873 User.ConversionFunction = Constructor;
2874 User.FoundConversionFunction = Best->FoundDecl;
2875 User.After.setAsIdentityConversion();
2876 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2877 User.After.setAllToTypes(ToType);
2878 return OR_Success;
2879 }
2880
2881 case OR_No_Viable_Function:
2882 return OR_No_Viable_Function;
2883 case OR_Deleted:
2884 return OR_Deleted;
2885 case OR_Ambiguous:
2886 return OR_Ambiguous;
2887 }
2888
2889 llvm_unreachable("Invalid OverloadResult!");
2890}
2891
Douglas Gregor734d9862009-01-30 23:27:23 +00002892/// Determines whether there is a user-defined conversion sequence
2893/// (C++ [over.ics.user]) that converts expression From to the type
2894/// ToType. If such a conversion exists, User will contain the
2895/// user-defined conversion sequence that performs such a conversion
2896/// and this routine will return true. Otherwise, this routine returns
2897/// false and User is unspecified.
2898///
Douglas Gregor734d9862009-01-30 23:27:23 +00002899/// \param AllowExplicit true if the conversion should consider C++0x
2900/// "explicit" conversion functions as well as non-explicit conversion
2901/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002902static OverloadingResult
2903IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002904 UserDefinedConversionSequence &User,
2905 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002906 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002907 // Whether we will only visit constructors.
2908 bool ConstructorsOnly = false;
2909
2910 // If the type we are conversion to is a class type, enumerate its
2911 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002912 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002913 // C++ [over.match.ctor]p1:
2914 // When objects of class type are direct-initialized (8.5), or
2915 // copy-initialized from an expression of the same or a
2916 // derived class type (8.5), overload resolution selects the
2917 // constructor. [...] For copy-initialization, the candidate
2918 // functions are all the converting constructors (12.3.1) of
2919 // that class. The argument list is the expression-list within
2920 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002921 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002922 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002923 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002924 ConstructorsOnly = true;
2925
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002926 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2927 // RequireCompleteType may have returned true due to some invalid decl
2928 // during template instantiation, but ToType may be complete enough now
2929 // to try to recover.
2930 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002931 // We're not going to find any constructors.
2932 } else if (CXXRecordDecl *ToRecordDecl
2933 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002934
2935 Expr **Args = &From;
2936 unsigned NumArgs = 1;
2937 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002938 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002939 // But first, see if there is an init-list-contructor that will work.
2940 OverloadingResult Result = IsInitializerListConstructorConversion(
2941 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2942 if (Result != OR_No_Viable_Function)
2943 return Result;
2944 // Never mind.
2945 CandidateSet.clear();
2946
2947 // If we're list-initializing, we pass the individual elements as
2948 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002949 Args = InitList->getInits();
2950 NumArgs = InitList->getNumInits();
2951 ListInitializing = true;
2952 }
2953
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002954 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002955 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002956 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002957 NamedDecl *D = *Con;
2958 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2959
Douglas Gregordec06662009-08-21 18:42:58 +00002960 // Find the constructor (which may be a template).
2961 CXXConstructorDecl *Constructor = 0;
2962 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002963 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002964 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002965 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002966 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2967 else
John McCall9aa472c2010-03-19 07:35:19 +00002968 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002969
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002970 bool Usable = !Constructor->isInvalidDecl();
2971 if (ListInitializing)
2972 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2973 else
2974 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2975 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002976 bool SuppressUserConversions = !ConstructorsOnly;
2977 if (SuppressUserConversions && ListInitializing) {
2978 SuppressUserConversions = false;
2979 if (NumArgs == 1) {
2980 // If the first argument is (a reference to) the target type,
2981 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002982 SuppressUserConversions = isFirstArgumentCompatibleWithType(
2983 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002984 }
2985 }
Douglas Gregordec06662009-08-21 18:42:58 +00002986 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002987 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2988 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002989 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002990 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00002991 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002992 // Allow one user-defined conversion when user specifies a
2993 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002994 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002995 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002996 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00002997 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002998 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002999 }
3000 }
3001
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003002 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003003 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall120d63c2010-08-24 20:38:10 +00003004 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
3005 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003006 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003007 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003008 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003009 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003010 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3011 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003012 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003013 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003014 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003015 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003016 DeclAccessPair FoundDecl = I.getPair();
3017 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003018 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3019 if (isa<UsingShadowDecl>(D))
3020 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3021
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003022 CXXConversionDecl *Conv;
3023 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003024 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3025 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003026 else
John McCall32daa422010-03-31 01:36:47 +00003027 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003028
3029 if (AllowExplicit || !Conv->isExplicit()) {
3030 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003031 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3032 ActingContext, From, ToType,
3033 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003034 else
John McCall120d63c2010-08-24 20:38:10 +00003035 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3036 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003037 }
3038 }
3039 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003040 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003041
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003042 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3043
Douglas Gregor60d62c22008-10-31 16:23:19 +00003044 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003045 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003046 case OR_Success:
3047 // Record the standard conversion we used and the conversion function.
3048 if (CXXConstructorDecl *Constructor
3049 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003050 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003051
John McCall120d63c2010-08-24 20:38:10 +00003052 // C++ [over.ics.user]p1:
3053 // If the user-defined conversion is specified by a
3054 // constructor (12.3.1), the initial standard conversion
3055 // sequence converts the source type to the type required by
3056 // the argument of the constructor.
3057 //
3058 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003059 if (isa<InitListExpr>(From)) {
3060 // Initializer lists don't have conversions as such.
3061 User.Before.setAsIdentityConversion();
3062 } else {
3063 if (Best->Conversions[0].isEllipsis())
3064 User.EllipsisConversion = true;
3065 else {
3066 User.Before = Best->Conversions[0].Standard;
3067 User.EllipsisConversion = false;
3068 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003069 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003070 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003071 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003072 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003073 User.After.setAsIdentityConversion();
3074 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3075 User.After.setAllToTypes(ToType);
3076 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003077 }
3078 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003079 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003080 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003081
John McCall120d63c2010-08-24 20:38:10 +00003082 // C++ [over.ics.user]p1:
3083 //
3084 // [...] If the user-defined conversion is specified by a
3085 // conversion function (12.3.2), the initial standard
3086 // conversion sequence converts the source type to the
3087 // implicit object parameter of the conversion function.
3088 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003089 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003090 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003091 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003092 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003093
John McCall120d63c2010-08-24 20:38:10 +00003094 // C++ [over.ics.user]p2:
3095 // The second standard conversion sequence converts the
3096 // result of the user-defined conversion to the target type
3097 // for the sequence. Since an implicit conversion sequence
3098 // is an initialization, the special rules for
3099 // initialization by user-defined conversion apply when
3100 // selecting the best user-defined conversion for a
3101 // user-defined conversion sequence (see 13.3.3 and
3102 // 13.3.3.1).
3103 User.After = Best->FinalConversion;
3104 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003105 }
David Blaikie7530c032012-01-17 06:56:22 +00003106 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003107
John McCall120d63c2010-08-24 20:38:10 +00003108 case OR_No_Viable_Function:
3109 return OR_No_Viable_Function;
3110 case OR_Deleted:
3111 // No conversion here! We're done.
3112 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003113
John McCall120d63c2010-08-24 20:38:10 +00003114 case OR_Ambiguous:
3115 return OR_Ambiguous;
3116 }
3117
David Blaikie7530c032012-01-17 06:56:22 +00003118 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003119}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003121bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003122Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003123 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003124 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003125 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003126 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003127 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003128 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003129 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003130 diag::err_typecheck_ambiguous_condition)
3131 << From->getType() << ToType << From->getSourceRange();
3132 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003133 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003134 diag::err_typecheck_nonviable_condition)
3135 << From->getType() << ToType << From->getSourceRange();
3136 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003137 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003138 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003139 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003140}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003141
Douglas Gregorb734e242012-02-22 17:32:19 +00003142/// \brief Compare the user-defined conversion functions or constructors
3143/// of two user-defined conversion sequences to determine whether any ordering
3144/// is possible.
3145static ImplicitConversionSequence::CompareKind
3146compareConversionFunctions(Sema &S,
3147 FunctionDecl *Function1,
3148 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003149 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003150 return ImplicitConversionSequence::Indistinguishable;
3151
3152 // Objective-C++:
3153 // If both conversion functions are implicitly-declared conversions from
3154 // a lambda closure type to a function pointer and a block pointer,
3155 // respectively, always prefer the conversion to a function pointer,
3156 // because the function pointer is more lightweight and is more likely
3157 // to keep code working.
3158 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3159 if (!Conv1)
3160 return ImplicitConversionSequence::Indistinguishable;
3161
3162 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3163 if (!Conv2)
3164 return ImplicitConversionSequence::Indistinguishable;
3165
3166 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3167 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3168 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3169 if (Block1 != Block2)
3170 return Block1? ImplicitConversionSequence::Worse
3171 : ImplicitConversionSequence::Better;
3172 }
3173
3174 return ImplicitConversionSequence::Indistinguishable;
3175}
3176
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003177/// CompareImplicitConversionSequences - Compare two implicit
3178/// conversion sequences to determine whether one is better than the
3179/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003180static ImplicitConversionSequence::CompareKind
3181CompareImplicitConversionSequences(Sema &S,
3182 const ImplicitConversionSequence& ICS1,
3183 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003184{
3185 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3186 // conversion sequences (as defined in 13.3.3.1)
3187 // -- a standard conversion sequence (13.3.3.1.1) is a better
3188 // conversion sequence than a user-defined conversion sequence or
3189 // an ellipsis conversion sequence, and
3190 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3191 // conversion sequence than an ellipsis conversion sequence
3192 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003193 //
John McCall1d318332010-01-12 00:44:57 +00003194 // C++0x [over.best.ics]p10:
3195 // For the purpose of ranking implicit conversion sequences as
3196 // described in 13.3.3.2, the ambiguous conversion sequence is
3197 // treated as a user-defined sequence that is indistinguishable
3198 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003199 if (ICS1.getKindRank() < ICS2.getKindRank())
3200 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003201 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003202 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003203
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003204 // The following checks require both conversion sequences to be of
3205 // the same kind.
3206 if (ICS1.getKind() != ICS2.getKind())
3207 return ImplicitConversionSequence::Indistinguishable;
3208
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003209 ImplicitConversionSequence::CompareKind Result =
3210 ImplicitConversionSequence::Indistinguishable;
3211
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003212 // Two implicit conversion sequences of the same form are
3213 // indistinguishable conversion sequences unless one of the
3214 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003215 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003216 Result = CompareStandardConversionSequences(S,
3217 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003218 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003219 // User-defined conversion sequence U1 is a better conversion
3220 // sequence than another user-defined conversion sequence U2 if
3221 // they contain the same user-defined conversion function or
3222 // constructor and if the second standard conversion sequence of
3223 // U1 is better than the second standard conversion sequence of
3224 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003225 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003226 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003227 Result = CompareStandardConversionSequences(S,
3228 ICS1.UserDefined.After,
3229 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003230 else
3231 Result = compareConversionFunctions(S,
3232 ICS1.UserDefined.ConversionFunction,
3233 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003234 }
3235
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003236 // List-initialization sequence L1 is a better conversion sequence than
3237 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3238 // for some X and L2 does not.
3239 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003240 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003241 ICS1.isListInitializationSequence() &&
3242 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003243 if (ICS1.isStdInitializerListElement() &&
3244 !ICS2.isStdInitializerListElement())
3245 return ImplicitConversionSequence::Better;
3246 if (!ICS1.isStdInitializerListElement() &&
3247 ICS2.isStdInitializerListElement())
3248 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003249 }
3250
3251 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003252}
3253
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003254static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3255 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3256 Qualifiers Quals;
3257 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003259 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003261 return Context.hasSameUnqualifiedType(T1, T2);
3262}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263
Douglas Gregorad323a82010-01-27 03:51:04 +00003264// Per 13.3.3.2p3, compare the given standard conversion sequences to
3265// determine if one is a proper subset of the other.
3266static ImplicitConversionSequence::CompareKind
3267compareStandardConversionSubsets(ASTContext &Context,
3268 const StandardConversionSequence& SCS1,
3269 const StandardConversionSequence& SCS2) {
3270 ImplicitConversionSequence::CompareKind Result
3271 = ImplicitConversionSequence::Indistinguishable;
3272
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003273 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003274 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003275 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3276 return ImplicitConversionSequence::Better;
3277 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3278 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279
Douglas Gregorad323a82010-01-27 03:51:04 +00003280 if (SCS1.Second != SCS2.Second) {
3281 if (SCS1.Second == ICK_Identity)
3282 Result = ImplicitConversionSequence::Better;
3283 else if (SCS2.Second == ICK_Identity)
3284 Result = ImplicitConversionSequence::Worse;
3285 else
3286 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003287 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003288 return ImplicitConversionSequence::Indistinguishable;
3289
3290 if (SCS1.Third == SCS2.Third) {
3291 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3292 : ImplicitConversionSequence::Indistinguishable;
3293 }
3294
3295 if (SCS1.Third == ICK_Identity)
3296 return Result == ImplicitConversionSequence::Worse
3297 ? ImplicitConversionSequence::Indistinguishable
3298 : ImplicitConversionSequence::Better;
3299
3300 if (SCS2.Third == ICK_Identity)
3301 return Result == ImplicitConversionSequence::Better
3302 ? ImplicitConversionSequence::Indistinguishable
3303 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304
Douglas Gregorad323a82010-01-27 03:51:04 +00003305 return ImplicitConversionSequence::Indistinguishable;
3306}
3307
Douglas Gregor440a4832011-01-26 14:52:12 +00003308/// \brief Determine whether one of the given reference bindings is better
3309/// than the other based on what kind of bindings they are.
3310static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3311 const StandardConversionSequence &SCS2) {
3312 // C++0x [over.ics.rank]p3b4:
3313 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3314 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003315 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003316 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003317 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003318 // reference*.
3319 //
3320 // FIXME: Rvalue references. We're going rogue with the above edits,
3321 // because the semantics in the current C++0x working paper (N3225 at the
3322 // time of this writing) break the standard definition of std::forward
3323 // and std::reference_wrapper when dealing with references to functions.
3324 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003325 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3326 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3327 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003328
Douglas Gregor440a4832011-01-26 14:52:12 +00003329 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3330 SCS2.IsLvalueReference) ||
3331 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3332 !SCS2.IsLvalueReference);
3333}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003334
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003335/// CompareStandardConversionSequences - Compare two standard
3336/// conversion sequences to determine whether one is better than the
3337/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003338static ImplicitConversionSequence::CompareKind
3339CompareStandardConversionSequences(Sema &S,
3340 const StandardConversionSequence& SCS1,
3341 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003342{
3343 // Standard conversion sequence S1 is a better conversion sequence
3344 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3345
3346 // -- S1 is a proper subsequence of S2 (comparing the conversion
3347 // sequences in the canonical form defined by 13.3.3.1.1,
3348 // excluding any Lvalue Transformation; the identity conversion
3349 // sequence is considered to be a subsequence of any
3350 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003351 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003352 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003353 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003354
3355 // -- the rank of S1 is better than the rank of S2 (by the rules
3356 // defined below), or, if not that,
3357 ImplicitConversionRank Rank1 = SCS1.getRank();
3358 ImplicitConversionRank Rank2 = SCS2.getRank();
3359 if (Rank1 < Rank2)
3360 return ImplicitConversionSequence::Better;
3361 else if (Rank2 < Rank1)
3362 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003363
Douglas Gregor57373262008-10-22 14:17:15 +00003364 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3365 // are indistinguishable unless one of the following rules
3366 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Douglas Gregor57373262008-10-22 14:17:15 +00003368 // A conversion that is not a conversion of a pointer, or
3369 // pointer to member, to bool is better than another conversion
3370 // that is such a conversion.
3371 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3372 return SCS2.isPointerConversionToBool()
3373 ? ImplicitConversionSequence::Better
3374 : ImplicitConversionSequence::Worse;
3375
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003376 // C++ [over.ics.rank]p4b2:
3377 //
3378 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003379 // conversion of B* to A* is better than conversion of B* to
3380 // void*, and conversion of A* to void* is better than conversion
3381 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003382 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003383 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003384 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003385 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003386 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3387 // Exactly one of the conversion sequences is a conversion to
3388 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003389 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3390 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003391 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3392 // Neither conversion sequence converts to a void pointer; compare
3393 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003394 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003395 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003396 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003397 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3398 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003399 // Both conversion sequences are conversions to void
3400 // pointers. Compare the source types to determine if there's an
3401 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003402 QualType FromType1 = SCS1.getFromType();
3403 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003404
3405 // Adjust the types we're converting from via the array-to-pointer
3406 // conversion, if we need to.
3407 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003408 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003409 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003410 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003411
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003412 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3413 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003414
John McCall120d63c2010-08-24 20:38:10 +00003415 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003416 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003417 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003418 return ImplicitConversionSequence::Worse;
3419
3420 // Objective-C++: If one interface is more specific than the
3421 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003422 const ObjCObjectPointerType* FromObjCPtr1
3423 = FromType1->getAs<ObjCObjectPointerType>();
3424 const ObjCObjectPointerType* FromObjCPtr2
3425 = FromType2->getAs<ObjCObjectPointerType>();
3426 if (FromObjCPtr1 && FromObjCPtr2) {
3427 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3428 FromObjCPtr2);
3429 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3430 FromObjCPtr1);
3431 if (AssignLeft != AssignRight) {
3432 return AssignLeft? ImplicitConversionSequence::Better
3433 : ImplicitConversionSequence::Worse;
3434 }
Douglas Gregor01919692009-12-13 21:37:05 +00003435 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003436 }
Douglas Gregor57373262008-10-22 14:17:15 +00003437
3438 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3439 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003440 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003441 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003442 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003443
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003444 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003445 // Check for a better reference binding based on the kind of bindings.
3446 if (isBetterReferenceBindingKind(SCS1, SCS2))
3447 return ImplicitConversionSequence::Better;
3448 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3449 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003450
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003451 // C++ [over.ics.rank]p3b4:
3452 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3453 // which the references refer are the same type except for
3454 // top-level cv-qualifiers, and the type to which the reference
3455 // initialized by S2 refers is more cv-qualified than the type
3456 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003457 QualType T1 = SCS1.getToType(2);
3458 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003459 T1 = S.Context.getCanonicalType(T1);
3460 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003461 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003462 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3463 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003464 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003465 // Objective-C++ ARC: If the references refer to objects with different
3466 // lifetimes, prefer bindings that don't change lifetime.
3467 if (SCS1.ObjCLifetimeConversionBinding !=
3468 SCS2.ObjCLifetimeConversionBinding) {
3469 return SCS1.ObjCLifetimeConversionBinding
3470 ? ImplicitConversionSequence::Worse
3471 : ImplicitConversionSequence::Better;
3472 }
3473
Chandler Carruth6df868e2010-12-12 08:17:55 +00003474 // If the type is an array type, promote the element qualifiers to the
3475 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003476 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003477 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003478 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003479 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003480 if (T2.isMoreQualifiedThan(T1))
3481 return ImplicitConversionSequence::Better;
3482 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003483 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003484 }
3485 }
Douglas Gregor57373262008-10-22 14:17:15 +00003486
Francois Pichet1c98d622011-09-18 21:37:37 +00003487 // In Microsoft mode, prefer an integral conversion to a
3488 // floating-to-integral conversion if the integral conversion
3489 // is between types of the same size.
3490 // For example:
3491 // void f(float);
3492 // void f(int);
3493 // int main {
3494 // long a;
3495 // f(a);
3496 // }
3497 // Here, MSVC will call f(int) instead of generating a compile error
3498 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003499 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003500 SCS1.Second == ICK_Integral_Conversion &&
3501 SCS2.Second == ICK_Floating_Integral &&
3502 S.Context.getTypeSize(SCS1.getFromType()) ==
3503 S.Context.getTypeSize(SCS1.getToType(2)))
3504 return ImplicitConversionSequence::Better;
3505
Douglas Gregor57373262008-10-22 14:17:15 +00003506 return ImplicitConversionSequence::Indistinguishable;
3507}
3508
3509/// CompareQualificationConversions - Compares two standard conversion
3510/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003511/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3512ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003513CompareQualificationConversions(Sema &S,
3514 const StandardConversionSequence& SCS1,
3515 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003516 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003517 // -- S1 and S2 differ only in their qualification conversion and
3518 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3519 // cv-qualification signature of type T1 is a proper subset of
3520 // the cv-qualification signature of type T2, and S1 is not the
3521 // deprecated string literal array-to-pointer conversion (4.2).
3522 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3523 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3524 return ImplicitConversionSequence::Indistinguishable;
3525
3526 // FIXME: the example in the standard doesn't use a qualification
3527 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003528 QualType T1 = SCS1.getToType(2);
3529 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003530 T1 = S.Context.getCanonicalType(T1);
3531 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003532 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003533 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3534 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003535
3536 // If the types are the same, we won't learn anything by unwrapped
3537 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003538 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003539 return ImplicitConversionSequence::Indistinguishable;
3540
Chandler Carruth28e318c2009-12-29 07:16:59 +00003541 // If the type is an array type, promote the element qualifiers to the type
3542 // for comparison.
3543 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003544 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003545 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003546 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003547
Mike Stump1eb44332009-09-09 15:08:12 +00003548 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003549 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003550
3551 // Objective-C++ ARC:
3552 // Prefer qualification conversions not involving a change in lifetime
3553 // to qualification conversions that do not change lifetime.
3554 if (SCS1.QualificationIncludesObjCLifetime !=
3555 SCS2.QualificationIncludesObjCLifetime) {
3556 Result = SCS1.QualificationIncludesObjCLifetime
3557 ? ImplicitConversionSequence::Worse
3558 : ImplicitConversionSequence::Better;
3559 }
3560
John McCall120d63c2010-08-24 20:38:10 +00003561 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003562 // Within each iteration of the loop, we check the qualifiers to
3563 // determine if this still looks like a qualification
3564 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003565 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003566 // until there are no more pointers or pointers-to-members left
3567 // to unwrap. This essentially mimics what
3568 // IsQualificationConversion does, but here we're checking for a
3569 // strict subset of qualifiers.
3570 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3571 // The qualifiers are the same, so this doesn't tell us anything
3572 // about how the sequences rank.
3573 ;
3574 else if (T2.isMoreQualifiedThan(T1)) {
3575 // T1 has fewer qualifiers, so it could be the better sequence.
3576 if (Result == ImplicitConversionSequence::Worse)
3577 // Neither has qualifiers that are a subset of the other's
3578 // qualifiers.
3579 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003580
Douglas Gregor57373262008-10-22 14:17:15 +00003581 Result = ImplicitConversionSequence::Better;
3582 } else if (T1.isMoreQualifiedThan(T2)) {
3583 // T2 has fewer qualifiers, so it could be the better sequence.
3584 if (Result == ImplicitConversionSequence::Better)
3585 // Neither has qualifiers that are a subset of the other's
3586 // qualifiers.
3587 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Douglas Gregor57373262008-10-22 14:17:15 +00003589 Result = ImplicitConversionSequence::Worse;
3590 } else {
3591 // Qualifiers are disjoint.
3592 return ImplicitConversionSequence::Indistinguishable;
3593 }
3594
3595 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003596 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003597 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003598 }
3599
Douglas Gregor57373262008-10-22 14:17:15 +00003600 // Check that the winning standard conversion sequence isn't using
3601 // the deprecated string literal array to pointer conversion.
3602 switch (Result) {
3603 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003604 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003605 Result = ImplicitConversionSequence::Indistinguishable;
3606 break;
3607
3608 case ImplicitConversionSequence::Indistinguishable:
3609 break;
3610
3611 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003612 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003613 Result = ImplicitConversionSequence::Indistinguishable;
3614 break;
3615 }
3616
3617 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003618}
3619
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003620/// CompareDerivedToBaseConversions - Compares two standard conversion
3621/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003622/// various kinds of derived-to-base conversions (C++
3623/// [over.ics.rank]p4b3). As part of these checks, we also look at
3624/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003625ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003626CompareDerivedToBaseConversions(Sema &S,
3627 const StandardConversionSequence& SCS1,
3628 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003629 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003630 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003631 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003632 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003633
3634 // Adjust the types we're converting from via the array-to-pointer
3635 // conversion, if we need to.
3636 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003637 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003638 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003639 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003640
3641 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003642 FromType1 = S.Context.getCanonicalType(FromType1);
3643 ToType1 = S.Context.getCanonicalType(ToType1);
3644 FromType2 = S.Context.getCanonicalType(FromType2);
3645 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003646
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003647 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003648 //
3649 // If class B is derived directly or indirectly from class A and
3650 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003651 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003652 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003653 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003654 SCS2.Second == ICK_Pointer_Conversion &&
3655 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3656 FromType1->isPointerType() && FromType2->isPointerType() &&
3657 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003658 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003659 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003660 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003661 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003662 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003663 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003664 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003665 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003666
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003667 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003668 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003669 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003670 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003671 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003672 return ImplicitConversionSequence::Worse;
3673 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003674
3675 // -- conversion of B* to A* is better than conversion of C* to A*,
3676 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003677 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003678 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003679 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003680 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003681 }
3682 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3683 SCS2.Second == ICK_Pointer_Conversion) {
3684 const ObjCObjectPointerType *FromPtr1
3685 = FromType1->getAs<ObjCObjectPointerType>();
3686 const ObjCObjectPointerType *FromPtr2
3687 = FromType2->getAs<ObjCObjectPointerType>();
3688 const ObjCObjectPointerType *ToPtr1
3689 = ToType1->getAs<ObjCObjectPointerType>();
3690 const ObjCObjectPointerType *ToPtr2
3691 = ToType2->getAs<ObjCObjectPointerType>();
3692
3693 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3694 // Apply the same conversion ranking rules for Objective-C pointer types
3695 // that we do for C++ pointers to class types. However, we employ the
3696 // Objective-C pseudo-subtyping relationship used for assignment of
3697 // Objective-C pointer types.
3698 bool FromAssignLeft
3699 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3700 bool FromAssignRight
3701 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3702 bool ToAssignLeft
3703 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3704 bool ToAssignRight
3705 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3706
3707 // A conversion to an a non-id object pointer type or qualified 'id'
3708 // type is better than a conversion to 'id'.
3709 if (ToPtr1->isObjCIdType() &&
3710 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3711 return ImplicitConversionSequence::Worse;
3712 if (ToPtr2->isObjCIdType() &&
3713 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3714 return ImplicitConversionSequence::Better;
3715
3716 // A conversion to a non-id object pointer type is better than a
3717 // conversion to a qualified 'id' type
3718 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3719 return ImplicitConversionSequence::Worse;
3720 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3721 return ImplicitConversionSequence::Better;
3722
3723 // A conversion to an a non-Class object pointer type or qualified 'Class'
3724 // type is better than a conversion to 'Class'.
3725 if (ToPtr1->isObjCClassType() &&
3726 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3727 return ImplicitConversionSequence::Worse;
3728 if (ToPtr2->isObjCClassType() &&
3729 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3730 return ImplicitConversionSequence::Better;
3731
3732 // A conversion to a non-Class object pointer type is better than a
3733 // conversion to a qualified 'Class' type.
3734 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3735 return ImplicitConversionSequence::Worse;
3736 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3737 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Douglas Gregor395cc372011-01-31 18:51:41 +00003739 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3740 if (S.Context.hasSameType(FromType1, FromType2) &&
3741 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3742 (ToAssignLeft != ToAssignRight))
3743 return ToAssignLeft? ImplicitConversionSequence::Worse
3744 : ImplicitConversionSequence::Better;
3745
3746 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3747 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3748 (FromAssignLeft != FromAssignRight))
3749 return FromAssignLeft? ImplicitConversionSequence::Better
3750 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003751 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003752 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003753
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003754 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003755 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3756 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3757 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003758 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003759 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003760 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003761 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003762 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003763 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003764 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003765 ToType2->getAs<MemberPointerType>();
3766 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3767 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3768 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3769 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3770 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3771 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3772 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3773 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003774 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003775 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003776 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003777 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003778 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003779 return ImplicitConversionSequence::Better;
3780 }
3781 // conversion of B::* to C::* is better than conversion of A::* to C::*
3782 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003783 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003784 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003785 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003786 return ImplicitConversionSequence::Worse;
3787 }
3788 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003789
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003790 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003791 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003792 // -- binding of an expression of type C to a reference of type
3793 // B& is better than binding an expression of type C to a
3794 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003795 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3796 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3797 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003798 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003799 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003800 return ImplicitConversionSequence::Worse;
3801 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003802
Douglas Gregor225c41e2008-11-03 19:09:14 +00003803 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003804 // -- binding of an expression of type B to a reference of type
3805 // A& is better than binding an expression of type C to a
3806 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003807 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3808 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3809 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003810 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003811 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003812 return ImplicitConversionSequence::Worse;
3813 }
3814 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003815
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003816 return ImplicitConversionSequence::Indistinguishable;
3817}
3818
Douglas Gregorabe183d2010-04-13 16:31:36 +00003819/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3820/// determine whether they are reference-related,
3821/// reference-compatible, reference-compatible with added
3822/// qualification, or incompatible, for use in C++ initialization by
3823/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3824/// type, and the first type (T1) is the pointee type of the reference
3825/// type being initialized.
3826Sema::ReferenceCompareResult
3827Sema::CompareReferenceRelationship(SourceLocation Loc,
3828 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003829 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003830 bool &ObjCConversion,
3831 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003832 assert(!OrigT1->isReferenceType() &&
3833 "T1 must be the pointee type of the reference type");
3834 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3835
3836 QualType T1 = Context.getCanonicalType(OrigT1);
3837 QualType T2 = Context.getCanonicalType(OrigT2);
3838 Qualifiers T1Quals, T2Quals;
3839 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3840 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3841
3842 // C++ [dcl.init.ref]p4:
3843 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3844 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3845 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003846 DerivedToBase = false;
3847 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003848 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003849 if (UnqualT1 == UnqualT2) {
3850 // Nothing to do.
3851 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003852 IsDerivedFrom(UnqualT2, UnqualT1))
3853 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003854 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3855 UnqualT2->isObjCObjectOrInterfaceType() &&
3856 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3857 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003858 else
3859 return Ref_Incompatible;
3860
3861 // At this point, we know that T1 and T2 are reference-related (at
3862 // least).
3863
3864 // If the type is an array type, promote the element qualifiers to the type
3865 // for comparison.
3866 if (isa<ArrayType>(T1) && T1Quals)
3867 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3868 if (isa<ArrayType>(T2) && T2Quals)
3869 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3870
3871 // C++ [dcl.init.ref]p4:
3872 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3873 // reference-related to T2 and cv1 is the same cv-qualification
3874 // as, or greater cv-qualification than, cv2. For purposes of
3875 // overload resolution, cases for which cv1 is greater
3876 // cv-qualification than cv2 are identified as
3877 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003878 //
3879 // Note that we also require equivalence of Objective-C GC and address-space
3880 // qualifiers when performing these computations, so that e.g., an int in
3881 // address space 1 is not reference-compatible with an int in address
3882 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003883 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3884 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3885 T1Quals.removeObjCLifetime();
3886 T2Quals.removeObjCLifetime();
3887 ObjCLifetimeConversion = true;
3888 }
3889
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003890 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003891 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003892 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003893 return Ref_Compatible_With_Added_Qualification;
3894 else
3895 return Ref_Related;
3896}
3897
Douglas Gregor604eb652010-08-11 02:15:33 +00003898/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003899/// with DeclType. Return true if something definite is found.
3900static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003901FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3902 QualType DeclType, SourceLocation DeclLoc,
3903 Expr *Init, QualType T2, bool AllowRvalues,
3904 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003905 assert(T2->isRecordType() && "Can only find conversions of record types.");
3906 CXXRecordDecl *T2RecordDecl
3907 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3908
3909 OverloadCandidateSet CandidateSet(DeclLoc);
3910 const UnresolvedSetImpl *Conversions
3911 = T2RecordDecl->getVisibleConversionFunctions();
3912 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3913 E = Conversions->end(); I != E; ++I) {
3914 NamedDecl *D = *I;
3915 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3916 if (isa<UsingShadowDecl>(D))
3917 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3918
3919 FunctionTemplateDecl *ConvTemplate
3920 = dyn_cast<FunctionTemplateDecl>(D);
3921 CXXConversionDecl *Conv;
3922 if (ConvTemplate)
3923 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3924 else
3925 Conv = cast<CXXConversionDecl>(D);
3926
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003927 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003928 // explicit conversions, skip it.
3929 if (!AllowExplicit && Conv->isExplicit())
3930 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931
Douglas Gregor604eb652010-08-11 02:15:33 +00003932 if (AllowRvalues) {
3933 bool DerivedToBase = false;
3934 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003935 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003936
3937 // If we are initializing an rvalue reference, don't permit conversion
3938 // functions that return lvalues.
3939 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3940 const ReferenceType *RefType
3941 = Conv->getConversionType()->getAs<LValueReferenceType>();
3942 if (RefType && !RefType->getPointeeType()->isFunctionType())
3943 continue;
3944 }
3945
Douglas Gregor604eb652010-08-11 02:15:33 +00003946 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003947 S.CompareReferenceRelationship(
3948 DeclLoc,
3949 Conv->getConversionType().getNonReferenceType()
3950 .getUnqualifiedType(),
3951 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003952 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003953 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003954 continue;
3955 } else {
3956 // If the conversion function doesn't return a reference type,
3957 // it can't be considered for this conversion. An rvalue reference
3958 // is only acceptable if its referencee is a function type.
3959
3960 const ReferenceType *RefType =
3961 Conv->getConversionType()->getAs<ReferenceType>();
3962 if (!RefType ||
3963 (!RefType->isLValueReferenceType() &&
3964 !RefType->getPointeeType()->isFunctionType()))
3965 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003966 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003967
Douglas Gregor604eb652010-08-11 02:15:33 +00003968 if (ConvTemplate)
3969 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003970 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003971 else
3972 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003973 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003974 }
3975
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003976 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3977
Sebastian Redl4680bf22010-06-30 18:13:39 +00003978 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003979 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003980 case OR_Success:
3981 // C++ [over.ics.ref]p1:
3982 //
3983 // [...] If the parameter binds directly to the result of
3984 // applying a conversion function to the argument
3985 // expression, the implicit conversion sequence is a
3986 // user-defined conversion sequence (13.3.3.1.2), with the
3987 // second standard conversion sequence either an identity
3988 // conversion or, if the conversion function returns an
3989 // entity of a type that is a derived class of the parameter
3990 // type, a derived-to-base Conversion.
3991 if (!Best->FinalConversion.DirectBinding)
3992 return false;
3993
Chandler Carruth25ca4212011-02-25 19:41:05 +00003994 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003995 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003996 ICS.setUserDefined();
3997 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3998 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003999 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004000 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004001 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004002 ICS.UserDefined.EllipsisConversion = false;
4003 assert(ICS.UserDefined.After.ReferenceBinding &&
4004 ICS.UserDefined.After.DirectBinding &&
4005 "Expected a direct reference binding!");
4006 return true;
4007
4008 case OR_Ambiguous:
4009 ICS.setAmbiguous();
4010 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4011 Cand != CandidateSet.end(); ++Cand)
4012 if (Cand->Viable)
4013 ICS.Ambiguous.addConversion(Cand->Function);
4014 return true;
4015
4016 case OR_No_Viable_Function:
4017 case OR_Deleted:
4018 // There was no suitable conversion, or we found a deleted
4019 // conversion; continue with other checks.
4020 return false;
4021 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022
David Blaikie7530c032012-01-17 06:56:22 +00004023 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004024}
4025
Douglas Gregorabe183d2010-04-13 16:31:36 +00004026/// \brief Compute an implicit conversion sequence for reference
4027/// initialization.
4028static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004029TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004030 SourceLocation DeclLoc,
4031 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004032 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004033 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4034
4035 // Most paths end in a failed conversion.
4036 ImplicitConversionSequence ICS;
4037 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4038
4039 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4040 QualType T2 = Init->getType();
4041
4042 // If the initializer is the address of an overloaded function, try
4043 // to resolve the overloaded function. If all goes well, T2 is the
4044 // type of the resulting function.
4045 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4046 DeclAccessPair Found;
4047 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4048 false, Found))
4049 T2 = Fn->getType();
4050 }
4051
4052 // Compute some basic properties of the types and the initializer.
4053 bool isRValRef = DeclType->isRValueReferenceType();
4054 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004055 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004056 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004057 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004058 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004059 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004060 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004061
Douglas Gregorabe183d2010-04-13 16:31:36 +00004062
Sebastian Redl4680bf22010-06-30 18:13:39 +00004063 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004064 // A reference to type "cv1 T1" is initialized by an expression
4065 // of type "cv2 T2" as follows:
4066
Sebastian Redl4680bf22010-06-30 18:13:39 +00004067 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004068 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004069 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4070 // reference-compatible with "cv2 T2," or
4071 //
4072 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4073 if (InitCategory.isLValue() &&
4074 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004075 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004076 // When a parameter of reference type binds directly (8.5.3)
4077 // to an argument expression, the implicit conversion sequence
4078 // is the identity conversion, unless the argument expression
4079 // has a type that is a derived class of the parameter type,
4080 // in which case the implicit conversion sequence is a
4081 // derived-to-base Conversion (13.3.3.1).
4082 ICS.setStandard();
4083 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004084 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4085 : ObjCConversion? ICK_Compatible_Conversion
4086 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004087 ICS.Standard.Third = ICK_Identity;
4088 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4089 ICS.Standard.setToType(0, T2);
4090 ICS.Standard.setToType(1, T1);
4091 ICS.Standard.setToType(2, T1);
4092 ICS.Standard.ReferenceBinding = true;
4093 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004094 ICS.Standard.IsLvalueReference = !isRValRef;
4095 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4096 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004097 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004098 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004099 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004100
Sebastian Redl4680bf22010-06-30 18:13:39 +00004101 // Nothing more to do: the inaccessibility/ambiguity check for
4102 // derived-to-base conversions is suppressed when we're
4103 // computing the implicit conversion sequence (C++
4104 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004105 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004106 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004107
Sebastian Redl4680bf22010-06-30 18:13:39 +00004108 // -- has a class type (i.e., T2 is a class type), where T1 is
4109 // not reference-related to T2, and can be implicitly
4110 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4111 // is reference-compatible with "cv3 T3" 92) (this
4112 // conversion is selected by enumerating the applicable
4113 // conversion functions (13.3.1.6) and choosing the best
4114 // one through overload resolution (13.3)),
4115 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004117 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004118 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4119 Init, T2, /*AllowRvalues=*/false,
4120 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004121 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004122 }
4123 }
4124
Sebastian Redl4680bf22010-06-30 18:13:39 +00004125 // -- Otherwise, the reference shall be an lvalue reference to a
4126 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004127 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004128 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004129 // We actually handle one oddity of C++ [over.ics.ref] at this
4130 // point, which is that, due to p2 (which short-circuits reference
4131 // binding by only attempting a simple conversion for non-direct
4132 // bindings) and p3's strange wording, we allow a const volatile
4133 // reference to bind to an rvalue. Hence the check for the presence
4134 // of "const" rather than checking for "const" being the only
4135 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004136 // This is also the point where rvalue references and lvalue inits no longer
4137 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004138 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00004139 return ICS;
4140
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004141 // -- If the initializer expression
4142 //
4143 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004144 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004145 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4146 (InitCategory.isXValue() ||
4147 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4148 (InitCategory.isLValue() && T2->isFunctionType()))) {
4149 ICS.setStandard();
4150 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004151 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004152 : ObjCConversion? ICK_Compatible_Conversion
4153 : ICK_Identity;
4154 ICS.Standard.Third = ICK_Identity;
4155 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4156 ICS.Standard.setToType(0, T2);
4157 ICS.Standard.setToType(1, T1);
4158 ICS.Standard.setToType(2, T1);
4159 ICS.Standard.ReferenceBinding = true;
4160 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4161 // binding unless we're binding to a class prvalue.
4162 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4163 // allow the use of rvalue references in C++98/03 for the benefit of
4164 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004165 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004166 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004167 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004168 ICS.Standard.IsLvalueReference = !isRValRef;
4169 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004170 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004171 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004172 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004173 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004174 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004175 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004176
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004177 // -- has a class type (i.e., T2 is a class type), where T1 is not
4178 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004179 // an xvalue, class prvalue, or function lvalue of type
4180 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004181 // "cv3 T3",
4182 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004183 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004184 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004186 // class subobject).
4187 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004188 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004189 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4190 Init, T2, /*AllowRvalues=*/true,
4191 AllowExplicit)) {
4192 // In the second case, if the reference is an rvalue reference
4193 // and the second standard conversion sequence of the
4194 // user-defined conversion sequence includes an lvalue-to-rvalue
4195 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004196 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004197 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4198 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4199
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004200 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004202
Douglas Gregorabe183d2010-04-13 16:31:36 +00004203 // -- Otherwise, a temporary of type "cv1 T1" is created and
4204 // initialized from the initializer expression using the
4205 // rules for a non-reference copy initialization (8.5). The
4206 // reference is then bound to the temporary. If T1 is
4207 // reference-related to T2, cv1 must be the same
4208 // cv-qualification as, or greater cv-qualification than,
4209 // cv2; otherwise, the program is ill-formed.
4210 if (RefRelationship == Sema::Ref_Related) {
4211 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4212 // we would be reference-compatible or reference-compatible with
4213 // added qualification. But that wasn't the case, so the reference
4214 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004215 //
4216 // Note that we only want to check address spaces and cvr-qualifiers here.
4217 // ObjC GC and lifetime qualifiers aren't important.
4218 Qualifiers T1Quals = T1.getQualifiers();
4219 Qualifiers T2Quals = T2.getQualifiers();
4220 T1Quals.removeObjCGCAttr();
4221 T1Quals.removeObjCLifetime();
4222 T2Quals.removeObjCGCAttr();
4223 T2Quals.removeObjCLifetime();
4224 if (!T1Quals.compatiblyIncludes(T2Quals))
4225 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004226 }
4227
4228 // If at least one of the types is a class type, the types are not
4229 // related, and we aren't allowed any user conversions, the
4230 // reference binding fails. This case is important for breaking
4231 // recursion, since TryImplicitConversion below will attempt to
4232 // create a temporary through the use of a copy constructor.
4233 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4234 (T1->isRecordType() || T2->isRecordType()))
4235 return ICS;
4236
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004237 // If T1 is reference-related to T2 and the reference is an rvalue
4238 // reference, the initializer expression shall not be an lvalue.
4239 if (RefRelationship >= Sema::Ref_Related &&
4240 isRValRef && Init->Classify(S.Context).isLValue())
4241 return ICS;
4242
Douglas Gregorabe183d2010-04-13 16:31:36 +00004243 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004244 // When a parameter of reference type is not bound directly to
4245 // an argument expression, the conversion sequence is the one
4246 // required to convert the argument expression to the
4247 // underlying type of the reference according to
4248 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4249 // to copy-initializing a temporary of the underlying type with
4250 // the argument expression. Any difference in top-level
4251 // cv-qualification is subsumed by the initialization itself
4252 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004253 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4254 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004255 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004256 /*CStyle=*/false,
4257 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004258
4259 // Of course, that's still a reference binding.
4260 if (ICS.isStandard()) {
4261 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004262 ICS.Standard.IsLvalueReference = !isRValRef;
4263 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4264 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004265 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004266 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004267 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004268 // Don't allow rvalue references to bind to lvalues.
4269 if (DeclType->isRValueReferenceType()) {
4270 if (const ReferenceType *RefType
4271 = ICS.UserDefined.ConversionFunction->getResultType()
4272 ->getAs<LValueReferenceType>()) {
4273 if (!RefType->getPointeeType()->isFunctionType()) {
4274 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4275 DeclType);
4276 return ICS;
4277 }
4278 }
4279 }
4280
Douglas Gregorabe183d2010-04-13 16:31:36 +00004281 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004282 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4283 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4284 ICS.UserDefined.After.BindsToRvalue = true;
4285 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4286 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004287 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004288
Douglas Gregorabe183d2010-04-13 16:31:36 +00004289 return ICS;
4290}
4291
Sebastian Redl5405b812011-10-16 18:19:34 +00004292static ImplicitConversionSequence
4293TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4294 bool SuppressUserConversions,
4295 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004296 bool AllowObjCWritebackConversion,
4297 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004298
4299/// TryListConversion - Try to copy-initialize a value of type ToType from the
4300/// initializer list From.
4301static ImplicitConversionSequence
4302TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4303 bool SuppressUserConversions,
4304 bool InOverloadResolution,
4305 bool AllowObjCWritebackConversion) {
4306 // C++11 [over.ics.list]p1:
4307 // When an argument is an initializer list, it is not an expression and
4308 // special rules apply for converting it to a parameter type.
4309
4310 ImplicitConversionSequence Result;
4311 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004312 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004313
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004314 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004315 // initialized from init lists.
4316 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4317 return Result;
4318
Sebastian Redl5405b812011-10-16 18:19:34 +00004319 // C++11 [over.ics.list]p2:
4320 // If the parameter type is std::initializer_list<X> or "array of X" and
4321 // all the elements can be implicitly converted to X, the implicit
4322 // conversion sequence is the worst conversion necessary to convert an
4323 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004324 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004325 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004326 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004327 X = S.Context.getBaseElementType(ToType);
4328 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004329 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004330 if (!X.isNull()) {
4331 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4332 Expr *Init = From->getInit(i);
4333 ImplicitConversionSequence ICS =
4334 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4335 InOverloadResolution,
4336 AllowObjCWritebackConversion);
4337 // If a single element isn't convertible, fail.
4338 if (ICS.isBad()) {
4339 Result = ICS;
4340 break;
4341 }
4342 // Otherwise, look for the worst conversion.
4343 if (Result.isBad() ||
4344 CompareImplicitConversionSequences(S, ICS, Result) ==
4345 ImplicitConversionSequence::Worse)
4346 Result = ICS;
4347 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004348
4349 // For an empty list, we won't have computed any conversion sequence.
4350 // Introduce the identity conversion sequence.
4351 if (From->getNumInits() == 0) {
4352 Result.setStandard();
4353 Result.Standard.setAsIdentityConversion();
4354 Result.Standard.setFromType(ToType);
4355 Result.Standard.setAllToTypes(ToType);
4356 }
4357
Sebastian Redlfe592282012-01-17 22:49:48 +00004358 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004359 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004360 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004361 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004362
4363 // C++11 [over.ics.list]p3:
4364 // Otherwise, if the parameter is a non-aggregate class X and overload
4365 // resolution chooses a single best constructor [...] the implicit
4366 // conversion sequence is a user-defined conversion sequence. If multiple
4367 // constructors are viable but none is better than the others, the
4368 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004369 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4370 // This function can deal with initializer lists.
4371 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4372 /*AllowExplicit=*/false,
4373 InOverloadResolution, /*CStyle=*/false,
4374 AllowObjCWritebackConversion);
4375 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004376 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004377 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004378
4379 // C++11 [over.ics.list]p4:
4380 // Otherwise, if the parameter has an aggregate type which can be
4381 // initialized from the initializer list [...] the implicit conversion
4382 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004383 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004384 // Type is an aggregate, argument is an init list. At this point it comes
4385 // down to checking whether the initialization works.
4386 // FIXME: Find out whether this parameter is consumed or not.
4387 InitializedEntity Entity =
4388 InitializedEntity::InitializeParameter(S.Context, ToType,
4389 /*Consumed=*/false);
4390 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4391 Result.setUserDefined();
4392 Result.UserDefined.Before.setAsIdentityConversion();
4393 // Initializer lists don't have a type.
4394 Result.UserDefined.Before.setFromType(QualType());
4395 Result.UserDefined.Before.setAllToTypes(QualType());
4396
4397 Result.UserDefined.After.setAsIdentityConversion();
4398 Result.UserDefined.After.setFromType(ToType);
4399 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004400 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004401 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004402 return Result;
4403 }
4404
4405 // C++11 [over.ics.list]p5:
4406 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004407 if (ToType->isReferenceType()) {
4408 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4409 // mention initializer lists in any way. So we go by what list-
4410 // initialization would do and try to extrapolate from that.
4411
4412 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4413
4414 // If the initializer list has a single element that is reference-related
4415 // to the parameter type, we initialize the reference from that.
4416 if (From->getNumInits() == 1) {
4417 Expr *Init = From->getInit(0);
4418
4419 QualType T2 = Init->getType();
4420
4421 // If the initializer is the address of an overloaded function, try
4422 // to resolve the overloaded function. If all goes well, T2 is the
4423 // type of the resulting function.
4424 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4425 DeclAccessPair Found;
4426 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4427 Init, ToType, false, Found))
4428 T2 = Fn->getType();
4429 }
4430
4431 // Compute some basic properties of the types and the initializer.
4432 bool dummy1 = false;
4433 bool dummy2 = false;
4434 bool dummy3 = false;
4435 Sema::ReferenceCompareResult RefRelationship
4436 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4437 dummy2, dummy3);
4438
4439 if (RefRelationship >= Sema::Ref_Related)
4440 return TryReferenceInit(S, Init, ToType,
4441 /*FIXME:*/From->getLocStart(),
4442 SuppressUserConversions,
4443 /*AllowExplicit=*/false);
4444 }
4445
4446 // Otherwise, we bind the reference to a temporary created from the
4447 // initializer list.
4448 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4449 InOverloadResolution,
4450 AllowObjCWritebackConversion);
4451 if (Result.isFailure())
4452 return Result;
4453 assert(!Result.isEllipsis() &&
4454 "Sub-initialization cannot result in ellipsis conversion.");
4455
4456 // Can we even bind to a temporary?
4457 if (ToType->isRValueReferenceType() ||
4458 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4459 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4460 Result.UserDefined.After;
4461 SCS.ReferenceBinding = true;
4462 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4463 SCS.BindsToRvalue = true;
4464 SCS.BindsToFunctionLvalue = false;
4465 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4466 SCS.ObjCLifetimeConversionBinding = false;
4467 } else
4468 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4469 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004470 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004471 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004472
4473 // C++11 [over.ics.list]p6:
4474 // Otherwise, if the parameter type is not a class:
4475 if (!ToType->isRecordType()) {
4476 // - if the initializer list has one element, the implicit conversion
4477 // sequence is the one required to convert the element to the
4478 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004479 unsigned NumInits = From->getNumInits();
4480 if (NumInits == 1)
4481 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4482 SuppressUserConversions,
4483 InOverloadResolution,
4484 AllowObjCWritebackConversion);
4485 // - if the initializer list has no elements, the implicit conversion
4486 // sequence is the identity conversion.
4487 else if (NumInits == 0) {
4488 Result.setStandard();
4489 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004490 Result.Standard.setFromType(ToType);
4491 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004492 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004493 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004494 return Result;
4495 }
4496
4497 // C++11 [over.ics.list]p7:
4498 // In all cases other than those enumerated above, no conversion is possible
4499 return Result;
4500}
4501
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004502/// TryCopyInitialization - Try to copy-initialize a value of type
4503/// ToType from the expression From. Return the implicit conversion
4504/// sequence required to pass this argument, which may be a bad
4505/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004506/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004507/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004508static ImplicitConversionSequence
4509TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004511 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004512 bool AllowObjCWritebackConversion,
4513 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004514 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4515 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4516 InOverloadResolution,AllowObjCWritebackConversion);
4517
Douglas Gregorabe183d2010-04-13 16:31:36 +00004518 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004519 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004520 /*FIXME:*/From->getLocStart(),
4521 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004522 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004523
John McCall120d63c2010-08-24 20:38:10 +00004524 return TryImplicitConversion(S, From, ToType,
4525 SuppressUserConversions,
4526 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004527 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004528 /*CStyle=*/false,
4529 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004530}
4531
Anna Zaksf3546ee2011-07-28 19:46:48 +00004532static bool TryCopyInitialization(const CanQualType FromQTy,
4533 const CanQualType ToQTy,
4534 Sema &S,
4535 SourceLocation Loc,
4536 ExprValueKind FromVK) {
4537 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4538 ImplicitConversionSequence ICS =
4539 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4540
4541 return !ICS.isBad();
4542}
4543
Douglas Gregor96176b32008-11-18 23:14:02 +00004544/// TryObjectArgumentInitialization - Try to initialize the object
4545/// parameter of the given member function (@c Method) from the
4546/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004547static ImplicitConversionSequence
4548TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004549 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004550 CXXMethodDecl *Method,
4551 CXXRecordDecl *ActingContext) {
4552 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004553 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4554 // const volatile object.
4555 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4556 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004557 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004558
4559 // Set up the conversion sequence as a "bad" conversion, to allow us
4560 // to exit early.
4561 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004562
4563 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004564 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004565 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004566 FromType = PT->getPointeeType();
4567
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004568 // When we had a pointer, it's implicitly dereferenced, so we
4569 // better have an lvalue.
4570 assert(FromClassification.isLValue());
4571 }
4572
Anders Carlssona552f7c2009-05-01 18:34:30 +00004573 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004574
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004575 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004576 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004577 // parameter is
4578 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004579 // - "lvalue reference to cv X" for functions declared without a
4580 // ref-qualifier or with the & ref-qualifier
4581 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004582 // ref-qualifier
4583 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004584 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004585 // cv-qualification on the member function declaration.
4586 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004587 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004588 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004589 // (C++ [over.match.funcs]p5). We perform a simplified version of
4590 // reference binding here, that allows class rvalues to bind to
4591 // non-constant references.
4592
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004593 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004594 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004595 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004596 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004597 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004598 ICS.setBad(BadConversionSequence::bad_qualifiers,
4599 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004600 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004601 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004602
4603 // Check that we have either the same type or a derived type. It
4604 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004605 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004606 ImplicitConversionKind SecondKind;
4607 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4608 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004609 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004610 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004611 else {
John McCallb1bdc622010-02-25 01:37:24 +00004612 ICS.setBad(BadConversionSequence::unrelated_class,
4613 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004614 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004615 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004616
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004617 // Check the ref-qualifier.
4618 switch (Method->getRefQualifier()) {
4619 case RQ_None:
4620 // Do nothing; we don't care about lvalueness or rvalueness.
4621 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004622
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004623 case RQ_LValue:
4624 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4625 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004626 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004627 ImplicitParamType);
4628 return ICS;
4629 }
4630 break;
4631
4632 case RQ_RValue:
4633 if (!FromClassification.isRValue()) {
4634 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004635 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004636 ImplicitParamType);
4637 return ICS;
4638 }
4639 break;
4640 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004641
Douglas Gregor96176b32008-11-18 23:14:02 +00004642 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004643 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004644 ICS.Standard.setAsIdentityConversion();
4645 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004646 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004647 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004648 ICS.Standard.ReferenceBinding = true;
4649 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004650 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004651 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004652 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4653 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4654 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004655 return ICS;
4656}
4657
4658/// PerformObjectArgumentInitialization - Perform initialization of
4659/// the implicit object parameter for the given Method with the given
4660/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004661ExprResult
4662Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004663 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004664 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004665 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004666 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004667 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004668 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004670 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004671 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004672 FromRecordType = PT->getPointeeType();
4673 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004674 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004675 } else {
4676 FromRecordType = From->getType();
4677 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004678 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004679 }
4680
John McCall701c89e2009-12-03 04:06:58 +00004681 // Note that we always use the true parent context when performing
4682 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004683 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004684 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4685 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004686 if (ICS.isBad()) {
4687 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4688 Qualifiers FromQs = FromRecordType.getQualifiers();
4689 Qualifiers ToQs = DestType.getQualifiers();
4690 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4691 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004692 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004693 diag::err_member_function_call_bad_cvr)
4694 << Method->getDeclName() << FromRecordType << (CVR - 1)
4695 << From->getSourceRange();
4696 Diag(Method->getLocation(), diag::note_previous_decl)
4697 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004698 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004699 }
4700 }
4701
Daniel Dunbar96a00142012-03-09 18:35:03 +00004702 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004703 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004704 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004705 }
Mike Stump1eb44332009-09-09 15:08:12 +00004706
John Wiegley429bb272011-04-08 18:41:53 +00004707 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4708 ExprResult FromRes =
4709 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4710 if (FromRes.isInvalid())
4711 return ExprError();
4712 From = FromRes.take();
4713 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004714
Douglas Gregor5fccd362010-03-03 23:55:11 +00004715 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004716 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004717 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004718 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004719}
4720
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004721/// TryContextuallyConvertToBool - Attempt to contextually convert the
4722/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004723static ImplicitConversionSequence
4724TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004725 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004726 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004727 // FIXME: Are these flags correct?
4728 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004729 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004730 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004731 /*CStyle=*/false,
4732 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004733}
4734
4735/// PerformContextuallyConvertToBool - Perform a contextual conversion
4736/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004737ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004738 if (checkPlaceholderForOverload(*this, From))
4739 return ExprError();
4740
John McCall120d63c2010-08-24 20:38:10 +00004741 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004742 if (!ICS.isBad())
4743 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004744
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004745 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004746 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004747 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004748 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004749 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004750}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004751
Richard Smith8ef7b202012-01-18 23:55:52 +00004752/// Check that the specified conversion is permitted in a converted constant
4753/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4754/// is acceptable.
4755static bool CheckConvertedConstantConversions(Sema &S,
4756 StandardConversionSequence &SCS) {
4757 // Since we know that the target type is an integral or unscoped enumeration
4758 // type, most conversion kinds are impossible. All possible First and Third
4759 // conversions are fine.
4760 switch (SCS.Second) {
4761 case ICK_Identity:
4762 case ICK_Integral_Promotion:
4763 case ICK_Integral_Conversion:
4764 return true;
4765
4766 case ICK_Boolean_Conversion:
4767 // Conversion from an integral or unscoped enumeration type to bool is
4768 // classified as ICK_Boolean_Conversion, but it's also an integral
4769 // conversion, so it's permitted in a converted constant expression.
4770 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4771 SCS.getToType(2)->isBooleanType();
4772
4773 case ICK_Floating_Integral:
4774 case ICK_Complex_Real:
4775 return false;
4776
4777 case ICK_Lvalue_To_Rvalue:
4778 case ICK_Array_To_Pointer:
4779 case ICK_Function_To_Pointer:
4780 case ICK_NoReturn_Adjustment:
4781 case ICK_Qualification:
4782 case ICK_Compatible_Conversion:
4783 case ICK_Vector_Conversion:
4784 case ICK_Vector_Splat:
4785 case ICK_Derived_To_Base:
4786 case ICK_Pointer_Conversion:
4787 case ICK_Pointer_Member:
4788 case ICK_Block_Pointer_Conversion:
4789 case ICK_Writeback_Conversion:
4790 case ICK_Floating_Promotion:
4791 case ICK_Complex_Promotion:
4792 case ICK_Complex_Conversion:
4793 case ICK_Floating_Conversion:
4794 case ICK_TransparentUnionConversion:
4795 llvm_unreachable("unexpected second conversion kind");
4796
4797 case ICK_Num_Conversion_Kinds:
4798 break;
4799 }
4800
4801 llvm_unreachable("unknown conversion kind");
4802}
4803
4804/// CheckConvertedConstantExpression - Check that the expression From is a
4805/// converted constant expression of type T, perform the conversion and produce
4806/// the converted expression, per C++11 [expr.const]p3.
4807ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4808 llvm::APSInt &Value,
4809 CCEKind CCE) {
4810 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4811 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4812
4813 if (checkPlaceholderForOverload(*this, From))
4814 return ExprError();
4815
4816 // C++11 [expr.const]p3 with proposed wording fixes:
4817 // A converted constant expression of type T is a core constant expression,
4818 // implicitly converted to a prvalue of type T, where the converted
4819 // expression is a literal constant expression and the implicit conversion
4820 // sequence contains only user-defined conversions, lvalue-to-rvalue
4821 // conversions, integral promotions, and integral conversions other than
4822 // narrowing conversions.
4823 ImplicitConversionSequence ICS =
4824 TryImplicitConversion(From, T,
4825 /*SuppressUserConversions=*/false,
4826 /*AllowExplicit=*/false,
4827 /*InOverloadResolution=*/false,
4828 /*CStyle=*/false,
4829 /*AllowObjcWritebackConversion=*/false);
4830 StandardConversionSequence *SCS = 0;
4831 switch (ICS.getKind()) {
4832 case ImplicitConversionSequence::StandardConversion:
4833 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004834 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004835 diag::err_typecheck_converted_constant_expression_disallowed)
4836 << From->getType() << From->getSourceRange() << T;
4837 SCS = &ICS.Standard;
4838 break;
4839 case ImplicitConversionSequence::UserDefinedConversion:
4840 // We are converting from class type to an integral or enumeration type, so
4841 // the Before sequence must be trivial.
4842 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004843 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004844 diag::err_typecheck_converted_constant_expression_disallowed)
4845 << From->getType() << From->getSourceRange() << T;
4846 SCS = &ICS.UserDefined.After;
4847 break;
4848 case ImplicitConversionSequence::AmbiguousConversion:
4849 case ImplicitConversionSequence::BadConversion:
4850 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004851 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004852 diag::err_typecheck_converted_constant_expression)
4853 << From->getType() << From->getSourceRange() << T;
4854 return ExprError();
4855
4856 case ImplicitConversionSequence::EllipsisConversion:
4857 llvm_unreachable("ellipsis conversion in converted constant expression");
4858 }
4859
4860 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4861 if (Result.isInvalid())
4862 return Result;
4863
4864 // Check for a narrowing implicit conversion.
4865 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004866 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004867 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4868 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004869 case NK_Variable_Narrowing:
4870 // Implicit conversion to a narrower type, and the value is not a constant
4871 // expression. We'll diagnose this in a moment.
4872 case NK_Not_Narrowing:
4873 break;
4874
4875 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004876 Diag(From->getLocStart(),
4877 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4878 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004879 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004880 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004881 break;
4882
4883 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004884 Diag(From->getLocStart(),
4885 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4886 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004887 << CCE << /*Constant*/0 << From->getType() << T;
4888 break;
4889 }
4890
4891 // Check the expression is a constant expression.
4892 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4893 Expr::EvalResult Eval;
4894 Eval.Diag = &Notes;
4895
4896 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4897 // The expression can't be folded, so we can't keep it at this position in
4898 // the AST.
4899 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004900 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004901 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004902
4903 if (Notes.empty()) {
4904 // It's a constant expression.
4905 return Result;
4906 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004907 }
4908
4909 // It's not a constant expression. Produce an appropriate diagnostic.
4910 if (Notes.size() == 1 &&
4911 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4912 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4913 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004914 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004915 << CCE << From->getSourceRange();
4916 for (unsigned I = 0; I < Notes.size(); ++I)
4917 Diag(Notes[I].first, Notes[I].second);
4918 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004919 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004920}
4921
John McCall0bcc9bc2011-09-09 06:11:02 +00004922/// dropPointerConversions - If the given standard conversion sequence
4923/// involves any pointer conversions, remove them. This may change
4924/// the result type of the conversion sequence.
4925static void dropPointerConversion(StandardConversionSequence &SCS) {
4926 if (SCS.Second == ICK_Pointer_Conversion) {
4927 SCS.Second = ICK_Identity;
4928 SCS.Third = ICK_Identity;
4929 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4930 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004931}
John McCall120d63c2010-08-24 20:38:10 +00004932
John McCall0bcc9bc2011-09-09 06:11:02 +00004933/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4934/// convert the expression From to an Objective-C pointer type.
4935static ImplicitConversionSequence
4936TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4937 // Do an implicit conversion to 'id'.
4938 QualType Ty = S.Context.getObjCIdType();
4939 ImplicitConversionSequence ICS
4940 = TryImplicitConversion(S, From, Ty,
4941 // FIXME: Are these flags correct?
4942 /*SuppressUserConversions=*/false,
4943 /*AllowExplicit=*/true,
4944 /*InOverloadResolution=*/false,
4945 /*CStyle=*/false,
4946 /*AllowObjCWritebackConversion=*/false);
4947
4948 // Strip off any final conversions to 'id'.
4949 switch (ICS.getKind()) {
4950 case ImplicitConversionSequence::BadConversion:
4951 case ImplicitConversionSequence::AmbiguousConversion:
4952 case ImplicitConversionSequence::EllipsisConversion:
4953 break;
4954
4955 case ImplicitConversionSequence::UserDefinedConversion:
4956 dropPointerConversion(ICS.UserDefined.After);
4957 break;
4958
4959 case ImplicitConversionSequence::StandardConversion:
4960 dropPointerConversion(ICS.Standard);
4961 break;
4962 }
4963
4964 return ICS;
4965}
4966
4967/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4968/// conversion of the expression From to an Objective-C pointer type.
4969ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004970 if (checkPlaceholderForOverload(*this, From))
4971 return ExprError();
4972
John McCallc12c5bb2010-05-15 11:32:37 +00004973 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004974 ImplicitConversionSequence ICS =
4975 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004976 if (!ICS.isBad())
4977 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004978 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004979}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004980
Richard Smithf39aec12012-02-04 07:07:42 +00004981/// Determine whether the provided type is an integral type, or an enumeration
4982/// type of a permitted flavor.
4983static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4984 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4985 : T->isIntegralOrUnscopedEnumerationType();
4986}
4987
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004988/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004989/// enumeration type.
4990///
4991/// This routine will attempt to convert an expression of class type to an
4992/// integral or enumeration type, if that class type only has a single
4993/// conversion to an integral or enumeration type.
4994///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004995/// \param Loc The source location of the construct that requires the
4996/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004997///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004998/// \param FromE The expression we're converting from.
4999///
5000/// \param NotIntDiag The diagnostic to be emitted if the expression does not
5001/// have integral or enumeration type.
5002///
5003/// \param IncompleteDiag The diagnostic to be emitted if the expression has
5004/// incomplete class type.
5005///
5006/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5007/// explicit conversion function (because no implicit conversion functions
5008/// were available). This is a recovery mode.
5009///
5010/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5011/// showing which conversion was picked.
5012///
5013/// \param AmbigDiag The diagnostic to be emitted if there is more than one
5014/// conversion function that could convert to integral or enumeration type.
5015///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005016/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005017/// usable conversion function.
5018///
5019/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5020/// function, which may be an extension in this case.
5021///
Richard Smithf39aec12012-02-04 07:07:42 +00005022/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5023/// enumerations should be considered.
5024///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005025/// \returns The expression, converted to an integral or enumeration type if
5026/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005027ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005028Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00005029 const PartialDiagnostic &NotIntDiag,
5030 const PartialDiagnostic &IncompleteDiag,
5031 const PartialDiagnostic &ExplicitConvDiag,
5032 const PartialDiagnostic &ExplicitConvNote,
5033 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005034 const PartialDiagnostic &AmbigNote,
Richard Smithf39aec12012-02-04 07:07:42 +00005035 const PartialDiagnostic &ConvDiag,
5036 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005037 // We can't perform any more checking for type-dependent expressions.
5038 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005039 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005040
Eli Friedmanceccab92012-01-26 00:26:18 +00005041 // Process placeholders immediately.
5042 if (From->hasPlaceholderType()) {
5043 ExprResult result = CheckPlaceholderExpr(From);
5044 if (result.isInvalid()) return result;
5045 From = result.take();
5046 }
5047
Douglas Gregorc30614b2010-06-29 23:17:37 +00005048 // If the expression already has integral or enumeration type, we're golden.
5049 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005050 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005051 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005052
5053 // FIXME: Check for missing '()' if T is a function type?
5054
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005055 // 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 +00005056 // expression of integral or enumeration type.
5057 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005058 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith282e7e62012-02-04 09:53:13 +00005059 if (NotIntDiag.getDiagID())
5060 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005061 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005063
Douglas Gregorc30614b2010-06-29 23:17:37 +00005064 // We must have a complete class type.
5065 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00005066 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067
Douglas Gregorc30614b2010-06-29 23:17:37 +00005068 // Look for a conversion to an integral or enumeration type.
5069 UnresolvedSet<4> ViableConversions;
5070 UnresolvedSet<4> ExplicitConversions;
5071 const UnresolvedSetImpl *Conversions
5072 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005073
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005074 bool HadMultipleCandidates = (Conversions->size() > 1);
5075
Douglas Gregorc30614b2010-06-29 23:17:37 +00005076 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005077 E = Conversions->end();
5078 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005079 ++I) {
5080 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005081 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5082 if (isIntegralOrEnumerationType(
5083 Conversion->getConversionType().getNonReferenceType(),
5084 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005085 if (Conversion->isExplicit())
5086 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5087 else
5088 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5089 }
Richard Smithf39aec12012-02-04 07:07:42 +00005090 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005091 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005092
Douglas Gregorc30614b2010-06-29 23:17:37 +00005093 switch (ViableConversions.size()) {
5094 case 0:
Richard Smith282e7e62012-02-04 09:53:13 +00005095 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005096 DeclAccessPair Found = ExplicitConversions[0];
5097 CXXConversionDecl *Conversion
5098 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005099
Douglas Gregorc30614b2010-06-29 23:17:37 +00005100 // The user probably meant to invoke the given explicit
5101 // conversion; use it.
5102 QualType ConvTy
5103 = Conversion->getConversionType().getNonReferenceType();
5104 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005105 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005106
Douglas Gregorc30614b2010-06-29 23:17:37 +00005107 Diag(Loc, ExplicitConvDiag)
5108 << T << ConvTy
5109 << FixItHint::CreateInsertion(From->getLocStart(),
5110 "static_cast<" + TypeStr + ">(")
5111 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5112 ")");
5113 Diag(Conversion->getLocation(), ExplicitConvNote)
5114 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005115
5116 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005117 // explicit conversion function.
5118 if (isSFINAEContext())
5119 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005120
Douglas Gregorc30614b2010-06-29 23:17:37 +00005121 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005122 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5123 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005124 if (Result.isInvalid())
5125 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005126 // Record usage of conversion in an implicit cast.
5127 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5128 CK_UserDefinedConversion,
5129 Result.get(), 0,
5130 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005132
Douglas Gregorc30614b2010-06-29 23:17:37 +00005133 // We'll complain below about a non-integral condition type.
5134 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005135
Douglas Gregorc30614b2010-06-29 23:17:37 +00005136 case 1: {
5137 // Apply this conversion.
5138 DeclAccessPair Found = ViableConversions[0];
5139 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005140
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005141 CXXConversionDecl *Conversion
5142 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5143 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005144 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005145 if (ConvDiag.getDiagID()) {
5146 if (isSFINAEContext())
5147 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005148
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005149 Diag(Loc, ConvDiag)
5150 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5151 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005152
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005153 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5154 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005155 if (Result.isInvalid())
5156 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005157 // Record usage of conversion in an implicit cast.
5158 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5159 CK_UserDefinedConversion,
5160 Result.get(), 0,
5161 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005162 break;
5163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005164
Douglas Gregorc30614b2010-06-29 23:17:37 +00005165 default:
Richard Smith282e7e62012-02-04 09:53:13 +00005166 if (!AmbigDiag.getDiagID())
5167 return Owned(From);
5168
Douglas Gregorc30614b2010-06-29 23:17:37 +00005169 Diag(Loc, AmbigDiag)
5170 << T << From->getSourceRange();
5171 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5172 CXXConversionDecl *Conv
5173 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5174 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5175 Diag(Conv->getLocation(), AmbigNote)
5176 << ConvTy->isEnumeralType() << ConvTy;
5177 }
John McCall9ae2f072010-08-23 23:25:46 +00005178 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005180
Richard Smith282e7e62012-02-04 09:53:13 +00005181 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5182 NotIntDiag.getDiagID())
5183 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005184
Eli Friedmanceccab92012-01-26 00:26:18 +00005185 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005186}
5187
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005188/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005189/// candidate functions, using the given function call arguments. If
5190/// @p SuppressUserConversions, then don't allow user-defined
5191/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005192///
5193/// \para PartialOverloading true if we are performing "partial" overloading
5194/// based on an incomplete set of function arguments. This feature is used by
5195/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005196void
5197Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005198 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005199 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005200 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005201 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005202 bool PartialOverloading,
5203 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005204 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005205 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005206 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005207 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005208 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005209
Douglas Gregor88a35142008-12-22 05:46:06 +00005210 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005211 if (!isa<CXXConstructorDecl>(Method)) {
5212 // If we get here, it's because we're calling a member function
5213 // that is named without a member access expression (e.g.,
5214 // "this->f") that was either written explicitly or created
5215 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005216 // function, e.g., X::f(). We use an empty type for the implied
5217 // object argument (C++ [over.call.func]p3), and the acting context
5218 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005219 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005220 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005221 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005222 return;
5223 }
5224 // We treat a constructor like a non-member function, since its object
5225 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005226 }
5227
Douglas Gregorfd476482009-11-13 23:59:09 +00005228 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005229 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005230
Douglas Gregor7edfb692009-11-23 12:27:39 +00005231 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005232 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005233
Douglas Gregor66724ea2009-11-14 01:20:54 +00005234 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5235 // C++ [class.copy]p3:
5236 // A member function template is never instantiated to perform the copy
5237 // of a class object to an object of its class type.
5238 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005239 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005240 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005241 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5242 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005243 return;
5244 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005245
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005246 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005247 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005248 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005249 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005250 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005251 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005252 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005253 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005254
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005255 unsigned NumArgsInProto = Proto->getNumArgs();
5256
5257 // (C++ 13.3.2p2): A candidate function having fewer than m
5258 // parameters is viable only if it has an ellipsis in its parameter
5259 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005260 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005261 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005262 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005263 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005264 return;
5265 }
5266
5267 // (C++ 13.3.2p2): A candidate function having more than m parameters
5268 // is viable only if the (m+1)st parameter has a default argument
5269 // (8.3.6). For the purposes of overload resolution, the
5270 // parameter list is truncated on the right, so that there are
5271 // exactly m parameters.
5272 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005273 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005274 // Not enough arguments.
5275 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005276 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005277 return;
5278 }
5279
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005280 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005281 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005282 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5283 if (CheckCUDATarget(Caller, Function)) {
5284 Candidate.Viable = false;
5285 Candidate.FailureKind = ovl_fail_bad_target;
5286 return;
5287 }
5288
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005289 // Determine the implicit conversion sequences for each of the
5290 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005291 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005292 if (ArgIdx < NumArgsInProto) {
5293 // (C++ 13.3.2p3): for F to be a viable function, there shall
5294 // exist for each argument an implicit conversion sequence
5295 // (13.3.3.1) that converts that argument to the corresponding
5296 // parameter of F.
5297 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005298 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005299 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005300 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005301 /*InOverloadResolution=*/true,
5302 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005303 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005304 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005305 if (Candidate.Conversions[ArgIdx].isBad()) {
5306 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005307 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005308 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005309 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005310 } else {
5311 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5312 // argument for which there is no corresponding parameter is
5313 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005314 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005315 }
5316 }
5317}
5318
Douglas Gregor063daf62009-03-13 18:40:31 +00005319/// \brief Add all of the function declarations in the given function set to
5320/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005321void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005322 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005323 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005324 bool SuppressUserConversions,
5325 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005326 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005327 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5328 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005329 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005330 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005331 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005332 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005333 Args.slice(1), CandidateSet,
5334 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005335 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005336 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005337 SuppressUserConversions);
5338 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005339 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005340 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5341 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005342 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005343 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005344 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005345 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005346 Args[0]->Classify(Context), Args.slice(1),
5347 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005348 else
John McCall9aa472c2010-03-19 07:35:19 +00005349 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005350 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005351 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005352 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005353 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005354}
5355
John McCall314be4e2009-11-17 07:50:12 +00005356/// AddMethodCandidate - Adds a named decl (which is some kind of
5357/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005358void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005359 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005360 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005361 Expr **Args, unsigned NumArgs,
5362 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005363 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005364 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005365 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005366
5367 if (isa<UsingShadowDecl>(Decl))
5368 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005369
John McCall314be4e2009-11-17 07:50:12 +00005370 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5371 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5372 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005373 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5374 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005375 ObjectType, ObjectClassification,
5376 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005377 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005378 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005379 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005380 ObjectType, ObjectClassification,
5381 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005382 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005383 }
5384}
5385
Douglas Gregor96176b32008-11-18 23:14:02 +00005386/// AddMethodCandidate - Adds the given C++ member function to the set
5387/// of candidate functions, using the given function call arguments
5388/// and the object argument (@c Object). For example, in a call
5389/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5390/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5391/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005392/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005393void
John McCall9aa472c2010-03-19 07:35:19 +00005394Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005395 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005396 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005397 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005398 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005399 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005400 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005401 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005402 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005403 assert(!isa<CXXConstructorDecl>(Method) &&
5404 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005405
Douglas Gregor3f396022009-09-28 04:47:19 +00005406 if (!CandidateSet.isNewCandidate(Method))
5407 return;
5408
Douglas Gregor7edfb692009-11-23 12:27:39 +00005409 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005410 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005411
Douglas Gregor96176b32008-11-18 23:14:02 +00005412 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005413 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005414 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005415 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005416 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005417 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005418 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005419
5420 unsigned NumArgsInProto = Proto->getNumArgs();
5421
5422 // (C++ 13.3.2p2): A candidate function having fewer than m
5423 // parameters is viable only if it has an ellipsis in its parameter
5424 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005425 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005426 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005427 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005428 return;
5429 }
5430
5431 // (C++ 13.3.2p2): A candidate function having more than m parameters
5432 // is viable only if the (m+1)st parameter has a default argument
5433 // (8.3.6). For the purposes of overload resolution, the
5434 // parameter list is truncated on the right, so that there are
5435 // exactly m parameters.
5436 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005437 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005438 // Not enough arguments.
5439 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005440 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005441 return;
5442 }
5443
5444 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005445
John McCall701c89e2009-12-03 04:06:58 +00005446 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005447 // The implicit object argument is ignored.
5448 Candidate.IgnoreObjectArgument = true;
5449 else {
5450 // Determine the implicit conversion sequence for the object
5451 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005452 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005453 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5454 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005455 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005456 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005457 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005458 return;
5459 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005460 }
5461
5462 // Determine the implicit conversion sequences for each of the
5463 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005464 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005465 if (ArgIdx < NumArgsInProto) {
5466 // (C++ 13.3.2p3): for F to be a viable function, there shall
5467 // exist for each argument an implicit conversion sequence
5468 // (13.3.3.1) that converts that argument to the corresponding
5469 // parameter of F.
5470 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005471 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005472 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005473 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005474 /*InOverloadResolution=*/true,
5475 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005476 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005477 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005478 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005479 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005480 break;
5481 }
5482 } else {
5483 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5484 // argument for which there is no corresponding parameter is
5485 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005486 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005487 }
5488 }
5489}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005490
Douglas Gregor6b906862009-08-21 00:16:32 +00005491/// \brief Add a C++ member function template as a candidate to the candidate
5492/// set, using template argument deduction to produce an appropriate member
5493/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005494void
Douglas Gregor6b906862009-08-21 00:16:32 +00005495Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005496 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005497 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005498 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005499 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005500 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005501 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005502 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005503 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005504 if (!CandidateSet.isNewCandidate(MethodTmpl))
5505 return;
5506
Douglas Gregor6b906862009-08-21 00:16:32 +00005507 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005508 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005509 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005510 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005511 // candidate functions in the usual way.113) A given name can refer to one
5512 // or more function templates and also to a set of overloaded non-template
5513 // functions. In such a case, the candidate functions generated from each
5514 // function template are combined with the set of non-template candidate
5515 // functions.
John McCall5769d612010-02-08 23:07:23 +00005516 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005517 FunctionDecl *Specialization = 0;
5518 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005519 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5520 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005521 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005522 Candidate.FoundDecl = FoundDecl;
5523 Candidate.Function = MethodTmpl->getTemplatedDecl();
5524 Candidate.Viable = false;
5525 Candidate.FailureKind = ovl_fail_bad_deduction;
5526 Candidate.IsSurrogate = false;
5527 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005528 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005529 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005530 Info);
5531 return;
5532 }
Mike Stump1eb44332009-09-09 15:08:12 +00005533
Douglas Gregor6b906862009-08-21 00:16:32 +00005534 // Add the function template specialization produced by template argument
5535 // deduction as a candidate.
5536 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005537 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005538 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005539 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005540 ActingContext, ObjectType, ObjectClassification, Args,
5541 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005542}
5543
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005544/// \brief Add a C++ function template specialization as a candidate
5545/// in the candidate set, using template argument deduction to produce
5546/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005547void
Douglas Gregore53060f2009-06-25 22:08:12 +00005548Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005549 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005550 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005551 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005552 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005553 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005554 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5555 return;
5556
Douglas Gregore53060f2009-06-25 22:08:12 +00005557 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005558 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005559 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005560 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005561 // candidate functions in the usual way.113) A given name can refer to one
5562 // or more function templates and also to a set of overloaded non-template
5563 // functions. In such a case, the candidate functions generated from each
5564 // function template are combined with the set of non-template candidate
5565 // functions.
John McCall5769d612010-02-08 23:07:23 +00005566 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005567 FunctionDecl *Specialization = 0;
5568 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005569 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5570 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005571 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005572 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005573 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5574 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005575 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005576 Candidate.IsSurrogate = false;
5577 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005578 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005579 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005580 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005581 return;
5582 }
Mike Stump1eb44332009-09-09 15:08:12 +00005583
Douglas Gregore53060f2009-06-25 22:08:12 +00005584 // Add the function template specialization produced by template argument
5585 // deduction as a candidate.
5586 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005587 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005588 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005589}
Mike Stump1eb44332009-09-09 15:08:12 +00005590
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005591/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005592/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005593/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005594/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005595/// (which may or may not be the same type as the type that the
5596/// conversion function produces).
5597void
5598Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005599 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005600 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005601 Expr *From, QualType ToType,
5602 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005603 assert(!Conversion->getDescribedFunctionTemplate() &&
5604 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005605 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005606 if (!CandidateSet.isNewCandidate(Conversion))
5607 return;
5608
Douglas Gregor7edfb692009-11-23 12:27:39 +00005609 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005610 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005611
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005612 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005613 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005614 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005615 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005616 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005617 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005618 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005619 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005620 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005621 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005622 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005623
Douglas Gregorbca39322010-08-19 15:37:02 +00005624 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005625 // For conversion functions, the function is considered to be a member of
5626 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005627 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005628 //
5629 // Determine the implicit conversion sequence for the implicit
5630 // object parameter.
5631 QualType ImplicitParamType = From->getType();
5632 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5633 ImplicitParamType = FromPtrType->getPointeeType();
5634 CXXRecordDecl *ConversionContext
5635 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005636
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005637 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005638 = TryObjectArgumentInitialization(*this, From->getType(),
5639 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005640 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005641
John McCall1d318332010-01-12 00:44:57 +00005642 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005643 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005644 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005645 return;
5646 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005647
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005648 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005649 // derived to base as such conversions are given Conversion Rank. They only
5650 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5651 QualType FromCanon
5652 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5653 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5654 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5655 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005656 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005657 return;
5658 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005659
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005660 // To determine what the conversion from the result of calling the
5661 // conversion function to the type we're eventually trying to
5662 // convert to (ToType), we need to synthesize a call to the
5663 // conversion function and attempt copy initialization from it. This
5664 // makes sure that we get the right semantics with respect to
5665 // lvalues/rvalues and the type. Fortunately, we can allocate this
5666 // call on the stack and we don't need its arguments to be
5667 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005668 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005669 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005670 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5671 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005672 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005673 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005674
Richard Smith87c1f1f2011-07-13 22:53:21 +00005675 QualType ConversionType = Conversion->getConversionType();
5676 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005677 Candidate.Viable = false;
5678 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5679 return;
5680 }
5681
Richard Smith87c1f1f2011-07-13 22:53:21 +00005682 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005683
Mike Stump1eb44332009-09-09 15:08:12 +00005684 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005685 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5686 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005687 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005688 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005689 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005690 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005691 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005692 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005693 /*InOverloadResolution=*/false,
5694 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005695
John McCall1d318332010-01-12 00:44:57 +00005696 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005697 case ImplicitConversionSequence::StandardConversion:
5698 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005699
Douglas Gregorc520c842010-04-12 23:42:09 +00005700 // C++ [over.ics.user]p3:
5701 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005702 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005703 // shall have exact match rank.
5704 if (Conversion->getPrimaryTemplate() &&
5705 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5706 Candidate.Viable = false;
5707 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5708 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005709
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005710 // C++0x [dcl.init.ref]p5:
5711 // In the second case, if the reference is an rvalue reference and
5712 // the second standard conversion sequence of the user-defined
5713 // conversion sequence includes an lvalue-to-rvalue conversion, the
5714 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005715 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005716 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5717 Candidate.Viable = false;
5718 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5719 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005720 break;
5721
5722 case ImplicitConversionSequence::BadConversion:
5723 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005724 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005725 break;
5726
5727 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005728 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005729 "Can only end up with a standard conversion sequence or failure");
5730 }
5731}
5732
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005733/// \brief Adds a conversion function template specialization
5734/// candidate to the overload set, using template argument deduction
5735/// to deduce the template arguments of the conversion function
5736/// template from the type that we are converting to (C++
5737/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005738void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005739Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005740 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005741 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005742 Expr *From, QualType ToType,
5743 OverloadCandidateSet &CandidateSet) {
5744 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5745 "Only conversion function templates permitted here");
5746
Douglas Gregor3f396022009-09-28 04:47:19 +00005747 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5748 return;
5749
John McCall5769d612010-02-08 23:07:23 +00005750 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005751 CXXConversionDecl *Specialization = 0;
5752 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005753 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005754 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005755 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005756 Candidate.FoundDecl = FoundDecl;
5757 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5758 Candidate.Viable = false;
5759 Candidate.FailureKind = ovl_fail_bad_deduction;
5760 Candidate.IsSurrogate = false;
5761 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005762 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005763 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005764 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005765 return;
5766 }
Mike Stump1eb44332009-09-09 15:08:12 +00005767
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005768 // Add the conversion function template specialization produced by
5769 // template argument deduction as a candidate.
5770 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005771 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005772 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005773}
5774
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005775/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5776/// converts the given @c Object to a function pointer via the
5777/// conversion function @c Conversion, and then attempts to call it
5778/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5779/// the type of function that we'll eventually be calling.
5780void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005781 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005782 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005783 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005784 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005785 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005786 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005787 if (!CandidateSet.isNewCandidate(Conversion))
5788 return;
5789
Douglas Gregor7edfb692009-11-23 12:27:39 +00005790 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005791 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005792
Ahmed Charles13a140c2012-02-25 11:00:22 +00005793 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005794 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005795 Candidate.Function = 0;
5796 Candidate.Surrogate = Conversion;
5797 Candidate.Viable = true;
5798 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005799 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005800 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005801
5802 // Determine the implicit conversion sequence for the implicit
5803 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005804 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005805 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005806 Object->Classify(Context),
5807 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005808 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005809 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005810 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005811 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005812 return;
5813 }
5814
5815 // The first conversion is actually a user-defined conversion whose
5816 // first conversion is ObjectInit's standard conversion (which is
5817 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005818 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005819 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005820 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005821 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005822 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005823 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005824 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005825 = Candidate.Conversions[0].UserDefined.Before;
5826 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5827
Mike Stump1eb44332009-09-09 15:08:12 +00005828 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005829 unsigned NumArgsInProto = Proto->getNumArgs();
5830
5831 // (C++ 13.3.2p2): A candidate function having fewer than m
5832 // parameters is viable only if it has an ellipsis in its parameter
5833 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005834 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005835 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005836 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005837 return;
5838 }
5839
5840 // Function types don't have any default arguments, so just check if
5841 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005842 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005843 // Not enough arguments.
5844 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005845 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005846 return;
5847 }
5848
5849 // Determine the implicit conversion sequences for each of the
5850 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005851 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005852 if (ArgIdx < NumArgsInProto) {
5853 // (C++ 13.3.2p3): for F to be a viable function, there shall
5854 // exist for each argument an implicit conversion sequence
5855 // (13.3.3.1) that converts that argument to the corresponding
5856 // parameter of F.
5857 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005858 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005859 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005860 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005861 /*InOverloadResolution=*/false,
5862 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005863 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005864 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005865 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005866 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005867 break;
5868 }
5869 } else {
5870 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5871 // argument for which there is no corresponding parameter is
5872 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005873 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005874 }
5875 }
5876}
5877
Douglas Gregor063daf62009-03-13 18:40:31 +00005878/// \brief Add overload candidates for overloaded operators that are
5879/// member functions.
5880///
5881/// Add the overloaded operator candidates that are member functions
5882/// for the operator Op that was used in an operator expression such
5883/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5884/// CandidateSet will store the added overload candidates. (C++
5885/// [over.match.oper]).
5886void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5887 SourceLocation OpLoc,
5888 Expr **Args, unsigned NumArgs,
5889 OverloadCandidateSet& CandidateSet,
5890 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005891 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5892
5893 // C++ [over.match.oper]p3:
5894 // For a unary operator @ with an operand of a type whose
5895 // cv-unqualified version is T1, and for a binary operator @ with
5896 // a left operand of a type whose cv-unqualified version is T1 and
5897 // a right operand of a type whose cv-unqualified version is T2,
5898 // three sets of candidate functions, designated member
5899 // candidates, non-member candidates and built-in candidates, are
5900 // constructed as follows:
5901 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005902
5903 // -- If T1 is a class type, the set of member candidates is the
5904 // result of the qualified lookup of T1::operator@
5905 // (13.3.1.1.1); otherwise, the set of member candidates is
5906 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005907 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005908 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005909 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005910 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005911
John McCalla24dc2e2009-11-17 02:14:36 +00005912 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5913 LookupQualifiedName(Operators, T1Rec->getDecl());
5914 Operators.suppressDiagnostics();
5915
Mike Stump1eb44332009-09-09 15:08:12 +00005916 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005917 OperEnd = Operators.end();
5918 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005919 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005920 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005921 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005922 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005923 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005924 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005925}
5926
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005927/// AddBuiltinCandidate - Add a candidate for a built-in
5928/// operator. ResultTy and ParamTys are the result and parameter types
5929/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005930/// arguments being passed to the candidate. IsAssignmentOperator
5931/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005932/// operator. NumContextualBoolArguments is the number of arguments
5933/// (at the beginning of the argument list) that will be contextually
5934/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005935void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005936 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005937 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005938 bool IsAssignmentOperator,
5939 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005940 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005941 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005942
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005943 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005944 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005945 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005946 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005947 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005948 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005949 Candidate.BuiltinTypes.ResultTy = ResultTy;
5950 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5951 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5952
5953 // Determine the implicit conversion sequences for each of the
5954 // arguments.
5955 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005956 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005957 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005958 // C++ [over.match.oper]p4:
5959 // For the built-in assignment operators, conversions of the
5960 // left operand are restricted as follows:
5961 // -- no temporaries are introduced to hold the left operand, and
5962 // -- no user-defined conversions are applied to the left
5963 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005964 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005965 //
5966 // We block these conversions by turning off user-defined
5967 // conversions, since that is the only way that initialization of
5968 // a reference to a non-class type can occur from something that
5969 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005970 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005971 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005972 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005973 Candidate.Conversions[ArgIdx]
5974 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005975 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005976 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005977 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005978 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005979 /*InOverloadResolution=*/false,
5980 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005981 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005982 }
John McCall1d318332010-01-12 00:44:57 +00005983 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005984 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005985 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005986 break;
5987 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005988 }
5989}
5990
5991/// BuiltinCandidateTypeSet - A set of types that will be used for the
5992/// candidate operator functions for built-in operators (C++
5993/// [over.built]). The types are separated into pointer types and
5994/// enumeration types.
5995class BuiltinCandidateTypeSet {
5996 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005997 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005998
5999 /// PointerTypes - The set of pointer types that will be used in the
6000 /// built-in candidates.
6001 TypeSet PointerTypes;
6002
Sebastian Redl78eb8742009-04-19 21:53:20 +00006003 /// MemberPointerTypes - The set of member pointer types that will be
6004 /// used in the built-in candidates.
6005 TypeSet MemberPointerTypes;
6006
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006007 /// EnumerationTypes - The set of enumeration types that will be
6008 /// used in the built-in candidates.
6009 TypeSet EnumerationTypes;
6010
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006011 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006012 /// candidates.
6013 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006014
6015 /// \brief A flag indicating non-record types are viable candidates
6016 bool HasNonRecordTypes;
6017
6018 /// \brief A flag indicating whether either arithmetic or enumeration types
6019 /// were present in the candidate set.
6020 bool HasArithmeticOrEnumeralTypes;
6021
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006022 /// \brief A flag indicating whether the nullptr type was present in the
6023 /// candidate set.
6024 bool HasNullPtrType;
6025
Douglas Gregor5842ba92009-08-24 15:23:48 +00006026 /// Sema - The semantic analysis instance where we are building the
6027 /// candidate type set.
6028 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006029
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006030 /// Context - The AST context in which we will build the type sets.
6031 ASTContext &Context;
6032
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006033 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6034 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006035 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006036
6037public:
6038 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006039 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006040
Mike Stump1eb44332009-09-09 15:08:12 +00006041 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006042 : HasNonRecordTypes(false),
6043 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006044 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006045 SemaRef(SemaRef),
6046 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006047
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006048 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006049 SourceLocation Loc,
6050 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006051 bool AllowExplicitConversions,
6052 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006053
6054 /// pointer_begin - First pointer type found;
6055 iterator pointer_begin() { return PointerTypes.begin(); }
6056
Sebastian Redl78eb8742009-04-19 21:53:20 +00006057 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006058 iterator pointer_end() { return PointerTypes.end(); }
6059
Sebastian Redl78eb8742009-04-19 21:53:20 +00006060 /// member_pointer_begin - First member pointer type found;
6061 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6062
6063 /// member_pointer_end - Past the last member pointer type found;
6064 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6065
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006066 /// enumeration_begin - First enumeration type found;
6067 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6068
Sebastian Redl78eb8742009-04-19 21:53:20 +00006069 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006070 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006071
Douglas Gregor26bcf672010-05-19 03:21:00 +00006072 iterator vector_begin() { return VectorTypes.begin(); }
6073 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006074
6075 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6076 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006077 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006078};
6079
Sebastian Redl78eb8742009-04-19 21:53:20 +00006080/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006081/// the set of pointer types along with any more-qualified variants of
6082/// that type. For example, if @p Ty is "int const *", this routine
6083/// will add "int const *", "int const volatile *", "int const
6084/// restrict *", and "int const volatile restrict *" to the set of
6085/// pointer types. Returns true if the add of @p Ty itself succeeded,
6086/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006087///
6088/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006089bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006090BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6091 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006092
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006093 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006094 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006095 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006096
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006097 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006098 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006099 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006100 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006101 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006102 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006103 buildObjCPtr = true;
6104 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006105 else
David Blaikieb219cfc2011-09-23 05:06:16 +00006106 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006107 }
6108 else
6109 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006110
Sebastian Redla9efada2009-11-18 20:39:26 +00006111 // Don't add qualified variants of arrays. For one, they're not allowed
6112 // (the qualifier would sink to the element type), and for another, the
6113 // only overload situation where it matters is subscript or pointer +- int,
6114 // and those shouldn't have qualifier variants anyway.
6115 if (PointeeTy->isArrayType())
6116 return true;
John McCall0953e762009-09-24 19:53:00 +00006117 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00006118 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00006119 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006120 bool hasVolatile = VisibleQuals.hasVolatile();
6121 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006122
John McCall0953e762009-09-24 19:53:00 +00006123 // Iterate through all strict supersets of BaseCVR.
6124 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6125 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006126 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6127 // in the types.
6128 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6129 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00006130 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006131 if (!buildObjCPtr)
6132 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6133 else
6134 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006135 }
6136
6137 return true;
6138}
6139
Sebastian Redl78eb8742009-04-19 21:53:20 +00006140/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6141/// to the set of pointer types along with any more-qualified variants of
6142/// that type. For example, if @p Ty is "int const *", this routine
6143/// will add "int const *", "int const volatile *", "int const
6144/// restrict *", and "int const volatile restrict *" to the set of
6145/// pointer types. Returns true if the add of @p Ty itself succeeded,
6146/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006147///
6148/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006149bool
6150BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6151 QualType Ty) {
6152 // Insert this type.
6153 if (!MemberPointerTypes.insert(Ty))
6154 return false;
6155
John McCall0953e762009-09-24 19:53:00 +00006156 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6157 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006158
John McCall0953e762009-09-24 19:53:00 +00006159 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006160 // Don't add qualified variants of arrays. For one, they're not allowed
6161 // (the qualifier would sink to the element type), and for another, the
6162 // only overload situation where it matters is subscript or pointer +- int,
6163 // and those shouldn't have qualifier variants anyway.
6164 if (PointeeTy->isArrayType())
6165 return true;
John McCall0953e762009-09-24 19:53:00 +00006166 const Type *ClassTy = PointerTy->getClass();
6167
6168 // Iterate through all strict supersets of the pointee type's CVR
6169 // qualifiers.
6170 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6171 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6172 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006173
John McCall0953e762009-09-24 19:53:00 +00006174 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006175 MemberPointerTypes.insert(
6176 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006177 }
6178
6179 return true;
6180}
6181
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006182/// AddTypesConvertedFrom - Add each of the types to which the type @p
6183/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006184/// primarily interested in pointer types and enumeration types. We also
6185/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006186/// AllowUserConversions is true if we should look at the conversion
6187/// functions of a class type, and AllowExplicitConversions if we
6188/// should also include the explicit conversion functions of a class
6189/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006190void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006191BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006192 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006193 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006194 bool AllowExplicitConversions,
6195 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006196 // Only deal with canonical types.
6197 Ty = Context.getCanonicalType(Ty);
6198
6199 // Look through reference types; they aren't part of the type of an
6200 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006201 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006202 Ty = RefTy->getPointeeType();
6203
John McCall3b657512011-01-19 10:06:00 +00006204 // If we're dealing with an array type, decay to the pointer.
6205 if (Ty->isArrayType())
6206 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6207
6208 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006209 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006210
Chandler Carruth6a577462010-12-13 01:44:01 +00006211 // Flag if we ever add a non-record type.
6212 const RecordType *TyRec = Ty->getAs<RecordType>();
6213 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6214
Chandler Carruth6a577462010-12-13 01:44:01 +00006215 // Flag if we encounter an arithmetic type.
6216 HasArithmeticOrEnumeralTypes =
6217 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6218
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006219 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6220 PointerTypes.insert(Ty);
6221 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006222 // Insert our type, and its more-qualified variants, into the set
6223 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006224 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006225 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006226 } else if (Ty->isMemberPointerType()) {
6227 // Member pointers are far easier, since the pointee can't be converted.
6228 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6229 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006230 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006231 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006232 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006233 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006234 // We treat vector types as arithmetic types in many contexts as an
6235 // extension.
6236 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006237 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006238 } else if (Ty->isNullPtrType()) {
6239 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006240 } else if (AllowUserConversions && TyRec) {
6241 // No conversion functions in incomplete types.
6242 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6243 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006244
Chandler Carruth6a577462010-12-13 01:44:01 +00006245 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6246 const UnresolvedSetImpl *Conversions
6247 = ClassDecl->getVisibleConversionFunctions();
6248 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6249 E = Conversions->end(); I != E; ++I) {
6250 NamedDecl *D = I.getDecl();
6251 if (isa<UsingShadowDecl>(D))
6252 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006253
Chandler Carruth6a577462010-12-13 01:44:01 +00006254 // Skip conversion function templates; they don't tell us anything
6255 // about which builtin types we can convert to.
6256 if (isa<FunctionTemplateDecl>(D))
6257 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006258
Chandler Carruth6a577462010-12-13 01:44:01 +00006259 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6260 if (AllowExplicitConversions || !Conv->isExplicit()) {
6261 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6262 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006263 }
6264 }
6265 }
6266}
6267
Douglas Gregor19b7b152009-08-24 13:43:27 +00006268/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6269/// the volatile- and non-volatile-qualified assignment operators for the
6270/// given type to the candidate set.
6271static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6272 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006273 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006274 unsigned NumArgs,
6275 OverloadCandidateSet &CandidateSet) {
6276 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006277
Douglas Gregor19b7b152009-08-24 13:43:27 +00006278 // T& operator=(T&, T)
6279 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6280 ParamTypes[1] = T;
6281 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6282 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006283
Douglas Gregor19b7b152009-08-24 13:43:27 +00006284 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6285 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006286 ParamTypes[0]
6287 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006288 ParamTypes[1] = T;
6289 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006290 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006291 }
6292}
Mike Stump1eb44332009-09-09 15:08:12 +00006293
Sebastian Redl9994a342009-10-25 17:03:50 +00006294/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6295/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006296static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6297 Qualifiers VRQuals;
6298 const RecordType *TyRec;
6299 if (const MemberPointerType *RHSMPType =
6300 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006301 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006302 else
6303 TyRec = ArgExpr->getType()->getAs<RecordType>();
6304 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006305 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006306 VRQuals.addVolatile();
6307 VRQuals.addRestrict();
6308 return VRQuals;
6309 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006310
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006311 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006312 if (!ClassDecl->hasDefinition())
6313 return VRQuals;
6314
John McCalleec51cf2010-01-20 00:46:10 +00006315 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006316 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006317
John McCalleec51cf2010-01-20 00:46:10 +00006318 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006319 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006320 NamedDecl *D = I.getDecl();
6321 if (isa<UsingShadowDecl>(D))
6322 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6323 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006324 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6325 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6326 CanTy = ResTypeRef->getPointeeType();
6327 // Need to go down the pointer/mempointer chain and add qualifiers
6328 // as see them.
6329 bool done = false;
6330 while (!done) {
6331 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6332 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006333 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006334 CanTy->getAs<MemberPointerType>())
6335 CanTy = ResTypeMPtr->getPointeeType();
6336 else
6337 done = true;
6338 if (CanTy.isVolatileQualified())
6339 VRQuals.addVolatile();
6340 if (CanTy.isRestrictQualified())
6341 VRQuals.addRestrict();
6342 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6343 return VRQuals;
6344 }
6345 }
6346 }
6347 return VRQuals;
6348}
John McCall00071ec2010-11-13 05:51:15 +00006349
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006350namespace {
John McCall00071ec2010-11-13 05:51:15 +00006351
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006352/// \brief Helper class to manage the addition of builtin operator overload
6353/// candidates. It provides shared state and utility methods used throughout
6354/// the process, as well as a helper method to add each group of builtin
6355/// operator overloads from the standard to a candidate set.
6356class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006357 // Common instance state available to all overload candidate addition methods.
6358 Sema &S;
6359 Expr **Args;
6360 unsigned NumArgs;
6361 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006362 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006363 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006364 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006365
Chandler Carruth6d695582010-12-12 10:35:00 +00006366 // Define some constants used to index and iterate over the arithemetic types
6367 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006368 // The "promoted arithmetic types" are the arithmetic
6369 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006370 static const unsigned FirstIntegralType = 3;
6371 static const unsigned LastIntegralType = 18;
6372 static const unsigned FirstPromotedIntegralType = 3,
6373 LastPromotedIntegralType = 9;
6374 static const unsigned FirstPromotedArithmeticType = 0,
6375 LastPromotedArithmeticType = 9;
6376 static const unsigned NumArithmeticTypes = 18;
6377
Chandler Carruth6d695582010-12-12 10:35:00 +00006378 /// \brief Get the canonical type for a given arithmetic type index.
6379 CanQualType getArithmeticType(unsigned index) {
6380 assert(index < NumArithmeticTypes);
6381 static CanQualType ASTContext::* const
6382 ArithmeticTypes[NumArithmeticTypes] = {
6383 // Start of promoted types.
6384 &ASTContext::FloatTy,
6385 &ASTContext::DoubleTy,
6386 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006387
Chandler Carruth6d695582010-12-12 10:35:00 +00006388 // Start of integral types.
6389 &ASTContext::IntTy,
6390 &ASTContext::LongTy,
6391 &ASTContext::LongLongTy,
6392 &ASTContext::UnsignedIntTy,
6393 &ASTContext::UnsignedLongTy,
6394 &ASTContext::UnsignedLongLongTy,
6395 // End of promoted types.
6396
6397 &ASTContext::BoolTy,
6398 &ASTContext::CharTy,
6399 &ASTContext::WCharTy,
6400 &ASTContext::Char16Ty,
6401 &ASTContext::Char32Ty,
6402 &ASTContext::SignedCharTy,
6403 &ASTContext::ShortTy,
6404 &ASTContext::UnsignedCharTy,
6405 &ASTContext::UnsignedShortTy,
6406 // End of integral types.
6407 // FIXME: What about complex?
6408 };
6409 return S.Context.*ArithmeticTypes[index];
6410 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006411
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006412 /// \brief Gets the canonical type resulting from the usual arithemetic
6413 /// converions for the given arithmetic types.
6414 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6415 // Accelerator table for performing the usual arithmetic conversions.
6416 // The rules are basically:
6417 // - if either is floating-point, use the wider floating-point
6418 // - if same signedness, use the higher rank
6419 // - if same size, use unsigned of the higher rank
6420 // - use the larger type
6421 // These rules, together with the axiom that higher ranks are
6422 // never smaller, are sufficient to precompute all of these results
6423 // *except* when dealing with signed types of higher rank.
6424 // (we could precompute SLL x UI for all known platforms, but it's
6425 // better not to make any assumptions).
6426 enum PromotedType {
6427 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6428 };
6429 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6430 [LastPromotedArithmeticType] = {
6431 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6432 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6433 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6434 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6435 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6436 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6437 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6438 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6439 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6440 };
6441
6442 assert(L < LastPromotedArithmeticType);
6443 assert(R < LastPromotedArithmeticType);
6444 int Idx = ConversionsTable[L][R];
6445
6446 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006447 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006448
6449 // Slow path: we need to compare widths.
6450 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006451 CanQualType LT = getArithmeticType(L),
6452 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006453 unsigned LW = S.Context.getIntWidth(LT),
6454 RW = S.Context.getIntWidth(RT);
6455
6456 // If they're different widths, use the signed type.
6457 if (LW > RW) return LT;
6458 else if (LW < RW) return RT;
6459
6460 // Otherwise, use the unsigned type of the signed type's rank.
6461 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6462 assert(L == SLL || R == SLL);
6463 return S.Context.UnsignedLongLongTy;
6464 }
6465
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006466 /// \brief Helper method to factor out the common pattern of adding overloads
6467 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006468 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6469 bool HasVolatile) {
6470 QualType ParamTypes[2] = {
6471 S.Context.getLValueReferenceType(CandidateTy),
6472 S.Context.IntTy
6473 };
6474
6475 // Non-volatile version.
6476 if (NumArgs == 1)
6477 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6478 else
6479 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6480
6481 // Use a heuristic to reduce number of builtin candidates in the set:
6482 // add volatile version only if there are conversions to a volatile type.
6483 if (HasVolatile) {
6484 ParamTypes[0] =
6485 S.Context.getLValueReferenceType(
6486 S.Context.getVolatileType(CandidateTy));
6487 if (NumArgs == 1)
6488 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6489 else
6490 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6491 }
6492 }
6493
6494public:
6495 BuiltinOperatorOverloadBuilder(
6496 Sema &S, Expr **Args, unsigned NumArgs,
6497 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006498 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006499 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006500 OverloadCandidateSet &CandidateSet)
6501 : S(S), Args(Args), NumArgs(NumArgs),
6502 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006503 HasArithmeticOrEnumeralCandidateType(
6504 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006505 CandidateTypes(CandidateTypes),
6506 CandidateSet(CandidateSet) {
6507 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006508 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006509 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006510 assert(getArithmeticType(LastPromotedIntegralType - 1)
6511 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006512 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006513 assert(getArithmeticType(FirstPromotedArithmeticType)
6514 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006515 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006516 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6517 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006518 "Invalid last promoted arithmetic type");
6519 }
6520
6521 // C++ [over.built]p3:
6522 //
6523 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6524 // is either volatile or empty, there exist candidate operator
6525 // functions of the form
6526 //
6527 // VQ T& operator++(VQ T&);
6528 // T operator++(VQ T&, int);
6529 //
6530 // C++ [over.built]p4:
6531 //
6532 // For every pair (T, VQ), where T is an arithmetic type other
6533 // than bool, and VQ is either volatile or empty, there exist
6534 // candidate operator functions of the form
6535 //
6536 // VQ T& operator--(VQ T&);
6537 // T operator--(VQ T&, int);
6538 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006539 if (!HasArithmeticOrEnumeralCandidateType)
6540 return;
6541
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006542 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6543 Arith < NumArithmeticTypes; ++Arith) {
6544 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006545 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006546 VisibleTypeConversionsQuals.hasVolatile());
6547 }
6548 }
6549
6550 // C++ [over.built]p5:
6551 //
6552 // For every pair (T, VQ), where T is a cv-qualified or
6553 // cv-unqualified object type, and VQ is either volatile or
6554 // empty, there exist candidate operator functions of the form
6555 //
6556 // T*VQ& operator++(T*VQ&);
6557 // T*VQ& operator--(T*VQ&);
6558 // T* operator++(T*VQ&, int);
6559 // T* operator--(T*VQ&, int);
6560 void addPlusPlusMinusMinusPointerOverloads() {
6561 for (BuiltinCandidateTypeSet::iterator
6562 Ptr = CandidateTypes[0].pointer_begin(),
6563 PtrEnd = CandidateTypes[0].pointer_end();
6564 Ptr != PtrEnd; ++Ptr) {
6565 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006566 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006567 continue;
6568
6569 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6570 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6571 VisibleTypeConversionsQuals.hasVolatile()));
6572 }
6573 }
6574
6575 // C++ [over.built]p6:
6576 // For every cv-qualified or cv-unqualified object type T, there
6577 // exist candidate operator functions of the form
6578 //
6579 // T& operator*(T*);
6580 //
6581 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006582 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006583 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006584 // T& operator*(T*);
6585 void addUnaryStarPointerOverloads() {
6586 for (BuiltinCandidateTypeSet::iterator
6587 Ptr = CandidateTypes[0].pointer_begin(),
6588 PtrEnd = CandidateTypes[0].pointer_end();
6589 Ptr != PtrEnd; ++Ptr) {
6590 QualType ParamTy = *Ptr;
6591 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006592 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6593 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006594
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006595 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6596 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6597 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006598
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006599 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6600 &ParamTy, Args, 1, CandidateSet);
6601 }
6602 }
6603
6604 // C++ [over.built]p9:
6605 // For every promoted arithmetic type T, there exist candidate
6606 // operator functions of the form
6607 //
6608 // T operator+(T);
6609 // T operator-(T);
6610 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006611 if (!HasArithmeticOrEnumeralCandidateType)
6612 return;
6613
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006614 for (unsigned Arith = FirstPromotedArithmeticType;
6615 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006616 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006617 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6618 }
6619
6620 // Extension: We also add these operators for vector types.
6621 for (BuiltinCandidateTypeSet::iterator
6622 Vec = CandidateTypes[0].vector_begin(),
6623 VecEnd = CandidateTypes[0].vector_end();
6624 Vec != VecEnd; ++Vec) {
6625 QualType VecTy = *Vec;
6626 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6627 }
6628 }
6629
6630 // C++ [over.built]p8:
6631 // For every type T, there exist candidate operator functions of
6632 // the form
6633 //
6634 // T* operator+(T*);
6635 void addUnaryPlusPointerOverloads() {
6636 for (BuiltinCandidateTypeSet::iterator
6637 Ptr = CandidateTypes[0].pointer_begin(),
6638 PtrEnd = CandidateTypes[0].pointer_end();
6639 Ptr != PtrEnd; ++Ptr) {
6640 QualType ParamTy = *Ptr;
6641 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6642 }
6643 }
6644
6645 // C++ [over.built]p10:
6646 // For every promoted integral type T, there exist candidate
6647 // operator functions of the form
6648 //
6649 // T operator~(T);
6650 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006651 if (!HasArithmeticOrEnumeralCandidateType)
6652 return;
6653
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006654 for (unsigned Int = FirstPromotedIntegralType;
6655 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006656 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006657 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6658 }
6659
6660 // Extension: We also add this operator for vector types.
6661 for (BuiltinCandidateTypeSet::iterator
6662 Vec = CandidateTypes[0].vector_begin(),
6663 VecEnd = CandidateTypes[0].vector_end();
6664 Vec != VecEnd; ++Vec) {
6665 QualType VecTy = *Vec;
6666 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6667 }
6668 }
6669
6670 // C++ [over.match.oper]p16:
6671 // For every pointer to member type T, there exist candidate operator
6672 // functions of the form
6673 //
6674 // bool operator==(T,T);
6675 // bool operator!=(T,T);
6676 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6677 /// Set of (canonical) types that we've already handled.
6678 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6679
6680 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6681 for (BuiltinCandidateTypeSet::iterator
6682 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6683 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6684 MemPtr != MemPtrEnd;
6685 ++MemPtr) {
6686 // Don't add the same builtin candidate twice.
6687 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6688 continue;
6689
6690 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6691 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6692 CandidateSet);
6693 }
6694 }
6695 }
6696
6697 // C++ [over.built]p15:
6698 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006699 // For every T, where T is an enumeration type, a pointer type, or
6700 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006701 //
6702 // bool operator<(T, T);
6703 // bool operator>(T, T);
6704 // bool operator<=(T, T);
6705 // bool operator>=(T, T);
6706 // bool operator==(T, T);
6707 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006708 void addRelationalPointerOrEnumeralOverloads() {
6709 // C++ [over.built]p1:
6710 // If there is a user-written candidate with the same name and parameter
6711 // types as a built-in candidate operator function, the built-in operator
6712 // function is hidden and is not included in the set of candidate
6713 // functions.
6714 //
6715 // The text is actually in a note, but if we don't implement it then we end
6716 // up with ambiguities when the user provides an overloaded operator for
6717 // an enumeration type. Note that only enumeration types have this problem,
6718 // so we track which enumeration types we've seen operators for. Also, the
6719 // only other overloaded operator with enumeration argumenst, operator=,
6720 // cannot be overloaded for enumeration types, so this is the only place
6721 // where we must suppress candidates like this.
6722 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6723 UserDefinedBinaryOperators;
6724
6725 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6726 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6727 CandidateTypes[ArgIdx].enumeration_end()) {
6728 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6729 CEnd = CandidateSet.end();
6730 C != CEnd; ++C) {
6731 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6732 continue;
6733
6734 QualType FirstParamType =
6735 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6736 QualType SecondParamType =
6737 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6738
6739 // Skip if either parameter isn't of enumeral type.
6740 if (!FirstParamType->isEnumeralType() ||
6741 !SecondParamType->isEnumeralType())
6742 continue;
6743
6744 // Add this operator to the set of known user-defined operators.
6745 UserDefinedBinaryOperators.insert(
6746 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6747 S.Context.getCanonicalType(SecondParamType)));
6748 }
6749 }
6750 }
6751
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006752 /// Set of (canonical) types that we've already handled.
6753 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6754
6755 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6756 for (BuiltinCandidateTypeSet::iterator
6757 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6758 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6759 Ptr != PtrEnd; ++Ptr) {
6760 // Don't add the same builtin candidate twice.
6761 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6762 continue;
6763
6764 QualType ParamTypes[2] = { *Ptr, *Ptr };
6765 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6766 CandidateSet);
6767 }
6768 for (BuiltinCandidateTypeSet::iterator
6769 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6770 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6771 Enum != EnumEnd; ++Enum) {
6772 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6773
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006774 // Don't add the same builtin candidate twice, or if a user defined
6775 // candidate exists.
6776 if (!AddedTypes.insert(CanonType) ||
6777 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6778 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006779 continue;
6780
6781 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006782 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6783 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006784 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006785
6786 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6787 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6788 if (AddedTypes.insert(NullPtrTy) &&
6789 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6790 NullPtrTy))) {
6791 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6792 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6793 CandidateSet);
6794 }
6795 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006796 }
6797 }
6798
6799 // C++ [over.built]p13:
6800 //
6801 // For every cv-qualified or cv-unqualified object type T
6802 // there exist candidate operator functions of the form
6803 //
6804 // T* operator+(T*, ptrdiff_t);
6805 // T& operator[](T*, ptrdiff_t); [BELOW]
6806 // T* operator-(T*, ptrdiff_t);
6807 // T* operator+(ptrdiff_t, T*);
6808 // T& operator[](ptrdiff_t, T*); [BELOW]
6809 //
6810 // C++ [over.built]p14:
6811 //
6812 // For every T, where T is a pointer to object type, there
6813 // exist candidate operator functions of the form
6814 //
6815 // ptrdiff_t operator-(T, T);
6816 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6817 /// Set of (canonical) types that we've already handled.
6818 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6819
6820 for (int Arg = 0; Arg < 2; ++Arg) {
6821 QualType AsymetricParamTypes[2] = {
6822 S.Context.getPointerDiffType(),
6823 S.Context.getPointerDiffType(),
6824 };
6825 for (BuiltinCandidateTypeSet::iterator
6826 Ptr = CandidateTypes[Arg].pointer_begin(),
6827 PtrEnd = CandidateTypes[Arg].pointer_end();
6828 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006829 QualType PointeeTy = (*Ptr)->getPointeeType();
6830 if (!PointeeTy->isObjectType())
6831 continue;
6832
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006833 AsymetricParamTypes[Arg] = *Ptr;
6834 if (Arg == 0 || Op == OO_Plus) {
6835 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6836 // T* operator+(ptrdiff_t, T*);
6837 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6838 CandidateSet);
6839 }
6840 if (Op == OO_Minus) {
6841 // ptrdiff_t operator-(T, T);
6842 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6843 continue;
6844
6845 QualType ParamTypes[2] = { *Ptr, *Ptr };
6846 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6847 Args, 2, CandidateSet);
6848 }
6849 }
6850 }
6851 }
6852
6853 // C++ [over.built]p12:
6854 //
6855 // For every pair of promoted arithmetic types L and R, there
6856 // exist candidate operator functions of the form
6857 //
6858 // LR operator*(L, R);
6859 // LR operator/(L, R);
6860 // LR operator+(L, R);
6861 // LR operator-(L, R);
6862 // bool operator<(L, R);
6863 // bool operator>(L, R);
6864 // bool operator<=(L, R);
6865 // bool operator>=(L, R);
6866 // bool operator==(L, R);
6867 // bool operator!=(L, R);
6868 //
6869 // where LR is the result of the usual arithmetic conversions
6870 // between types L and R.
6871 //
6872 // C++ [over.built]p24:
6873 //
6874 // For every pair of promoted arithmetic types L and R, there exist
6875 // candidate operator functions of the form
6876 //
6877 // LR operator?(bool, L, R);
6878 //
6879 // where LR is the result of the usual arithmetic conversions
6880 // between types L and R.
6881 // Our candidates ignore the first parameter.
6882 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006883 if (!HasArithmeticOrEnumeralCandidateType)
6884 return;
6885
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006886 for (unsigned Left = FirstPromotedArithmeticType;
6887 Left < LastPromotedArithmeticType; ++Left) {
6888 for (unsigned Right = FirstPromotedArithmeticType;
6889 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006890 QualType LandR[2] = { getArithmeticType(Left),
6891 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006892 QualType Result =
6893 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006894 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006895 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6896 }
6897 }
6898
6899 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6900 // conditional operator for vector types.
6901 for (BuiltinCandidateTypeSet::iterator
6902 Vec1 = CandidateTypes[0].vector_begin(),
6903 Vec1End = CandidateTypes[0].vector_end();
6904 Vec1 != Vec1End; ++Vec1) {
6905 for (BuiltinCandidateTypeSet::iterator
6906 Vec2 = CandidateTypes[1].vector_begin(),
6907 Vec2End = CandidateTypes[1].vector_end();
6908 Vec2 != Vec2End; ++Vec2) {
6909 QualType LandR[2] = { *Vec1, *Vec2 };
6910 QualType Result = S.Context.BoolTy;
6911 if (!isComparison) {
6912 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6913 Result = *Vec1;
6914 else
6915 Result = *Vec2;
6916 }
6917
6918 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6919 }
6920 }
6921 }
6922
6923 // C++ [over.built]p17:
6924 //
6925 // For every pair of promoted integral types L and R, there
6926 // exist candidate operator functions of the form
6927 //
6928 // LR operator%(L, R);
6929 // LR operator&(L, R);
6930 // LR operator^(L, R);
6931 // LR operator|(L, R);
6932 // L operator<<(L, R);
6933 // L operator>>(L, R);
6934 //
6935 // where LR is the result of the usual arithmetic conversions
6936 // between types L and R.
6937 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006938 if (!HasArithmeticOrEnumeralCandidateType)
6939 return;
6940
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006941 for (unsigned Left = FirstPromotedIntegralType;
6942 Left < LastPromotedIntegralType; ++Left) {
6943 for (unsigned Right = FirstPromotedIntegralType;
6944 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006945 QualType LandR[2] = { getArithmeticType(Left),
6946 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006947 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6948 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006949 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006950 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6951 }
6952 }
6953 }
6954
6955 // C++ [over.built]p20:
6956 //
6957 // For every pair (T, VQ), where T is an enumeration or
6958 // pointer to member type and VQ is either volatile or
6959 // empty, there exist candidate operator functions of the form
6960 //
6961 // VQ T& operator=(VQ T&, T);
6962 void addAssignmentMemberPointerOrEnumeralOverloads() {
6963 /// Set of (canonical) types that we've already handled.
6964 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6965
6966 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6967 for (BuiltinCandidateTypeSet::iterator
6968 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6969 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6970 Enum != EnumEnd; ++Enum) {
6971 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6972 continue;
6973
6974 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6975 CandidateSet);
6976 }
6977
6978 for (BuiltinCandidateTypeSet::iterator
6979 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6980 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6981 MemPtr != MemPtrEnd; ++MemPtr) {
6982 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6983 continue;
6984
6985 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6986 CandidateSet);
6987 }
6988 }
6989 }
6990
6991 // C++ [over.built]p19:
6992 //
6993 // For every pair (T, VQ), where T is any type and VQ is either
6994 // volatile or empty, there exist candidate operator functions
6995 // of the form
6996 //
6997 // T*VQ& operator=(T*VQ&, T*);
6998 //
6999 // C++ [over.built]p21:
7000 //
7001 // For every pair (T, VQ), where T is a cv-qualified or
7002 // cv-unqualified object type and VQ is either volatile or
7003 // empty, there exist candidate operator functions of the form
7004 //
7005 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7006 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7007 void addAssignmentPointerOverloads(bool isEqualOp) {
7008 /// Set of (canonical) types that we've already handled.
7009 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7010
7011 for (BuiltinCandidateTypeSet::iterator
7012 Ptr = CandidateTypes[0].pointer_begin(),
7013 PtrEnd = CandidateTypes[0].pointer_end();
7014 Ptr != PtrEnd; ++Ptr) {
7015 // If this is operator=, keep track of the builtin candidates we added.
7016 if (isEqualOp)
7017 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007018 else if (!(*Ptr)->getPointeeType()->isObjectType())
7019 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007020
7021 // non-volatile version
7022 QualType ParamTypes[2] = {
7023 S.Context.getLValueReferenceType(*Ptr),
7024 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7025 };
7026 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7027 /*IsAssigmentOperator=*/ isEqualOp);
7028
7029 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7030 VisibleTypeConversionsQuals.hasVolatile()) {
7031 // volatile version
7032 ParamTypes[0] =
7033 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7034 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7035 /*IsAssigmentOperator=*/isEqualOp);
7036 }
7037 }
7038
7039 if (isEqualOp) {
7040 for (BuiltinCandidateTypeSet::iterator
7041 Ptr = CandidateTypes[1].pointer_begin(),
7042 PtrEnd = CandidateTypes[1].pointer_end();
7043 Ptr != PtrEnd; ++Ptr) {
7044 // Make sure we don't add the same candidate twice.
7045 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7046 continue;
7047
Chandler Carruth6df868e2010-12-12 08:17:55 +00007048 QualType ParamTypes[2] = {
7049 S.Context.getLValueReferenceType(*Ptr),
7050 *Ptr,
7051 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007052
7053 // non-volatile version
7054 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7055 /*IsAssigmentOperator=*/true);
7056
7057 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7058 VisibleTypeConversionsQuals.hasVolatile()) {
7059 // volatile version
7060 ParamTypes[0] =
7061 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007062 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7063 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007064 }
7065 }
7066 }
7067 }
7068
7069 // C++ [over.built]p18:
7070 //
7071 // For every triple (L, VQ, R), where L is an arithmetic type,
7072 // VQ is either volatile or empty, and R is a promoted
7073 // arithmetic type, there exist candidate operator functions of
7074 // the form
7075 //
7076 // VQ L& operator=(VQ L&, R);
7077 // VQ L& operator*=(VQ L&, R);
7078 // VQ L& operator/=(VQ L&, R);
7079 // VQ L& operator+=(VQ L&, R);
7080 // VQ L& operator-=(VQ L&, R);
7081 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007082 if (!HasArithmeticOrEnumeralCandidateType)
7083 return;
7084
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007085 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7086 for (unsigned Right = FirstPromotedArithmeticType;
7087 Right < LastPromotedArithmeticType; ++Right) {
7088 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007089 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007090
7091 // Add this built-in operator as a candidate (VQ is empty).
7092 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007093 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007094 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7095 /*IsAssigmentOperator=*/isEqualOp);
7096
7097 // Add this built-in operator as a candidate (VQ is 'volatile').
7098 if (VisibleTypeConversionsQuals.hasVolatile()) {
7099 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007100 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007101 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007102 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7103 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007104 /*IsAssigmentOperator=*/isEqualOp);
7105 }
7106 }
7107 }
7108
7109 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7110 for (BuiltinCandidateTypeSet::iterator
7111 Vec1 = CandidateTypes[0].vector_begin(),
7112 Vec1End = CandidateTypes[0].vector_end();
7113 Vec1 != Vec1End; ++Vec1) {
7114 for (BuiltinCandidateTypeSet::iterator
7115 Vec2 = CandidateTypes[1].vector_begin(),
7116 Vec2End = CandidateTypes[1].vector_end();
7117 Vec2 != Vec2End; ++Vec2) {
7118 QualType ParamTypes[2];
7119 ParamTypes[1] = *Vec2;
7120 // Add this built-in operator as a candidate (VQ is empty).
7121 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7123 /*IsAssigmentOperator=*/isEqualOp);
7124
7125 // Add this built-in operator as a candidate (VQ is 'volatile').
7126 if (VisibleTypeConversionsQuals.hasVolatile()) {
7127 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7128 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007129 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7130 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007131 /*IsAssigmentOperator=*/isEqualOp);
7132 }
7133 }
7134 }
7135 }
7136
7137 // C++ [over.built]p22:
7138 //
7139 // For every triple (L, VQ, R), where L is an integral type, VQ
7140 // is either volatile or empty, and R is a promoted integral
7141 // type, there exist candidate operator functions of the form
7142 //
7143 // VQ L& operator%=(VQ L&, R);
7144 // VQ L& operator<<=(VQ L&, R);
7145 // VQ L& operator>>=(VQ L&, R);
7146 // VQ L& operator&=(VQ L&, R);
7147 // VQ L& operator^=(VQ L&, R);
7148 // VQ L& operator|=(VQ L&, R);
7149 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007150 if (!HasArithmeticOrEnumeralCandidateType)
7151 return;
7152
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007153 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7154 for (unsigned Right = FirstPromotedIntegralType;
7155 Right < LastPromotedIntegralType; ++Right) {
7156 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007157 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007158
7159 // Add this built-in operator as a candidate (VQ is empty).
7160 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007161 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7163 if (VisibleTypeConversionsQuals.hasVolatile()) {
7164 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007165 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007166 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7167 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7169 CandidateSet);
7170 }
7171 }
7172 }
7173 }
7174
7175 // C++ [over.operator]p23:
7176 //
7177 // There also exist candidate operator functions of the form
7178 //
7179 // bool operator!(bool);
7180 // bool operator&&(bool, bool);
7181 // bool operator||(bool, bool);
7182 void addExclaimOverload() {
7183 QualType ParamTy = S.Context.BoolTy;
7184 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7185 /*IsAssignmentOperator=*/false,
7186 /*NumContextualBoolArguments=*/1);
7187 }
7188 void addAmpAmpOrPipePipeOverload() {
7189 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7190 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7191 /*IsAssignmentOperator=*/false,
7192 /*NumContextualBoolArguments=*/2);
7193 }
7194
7195 // C++ [over.built]p13:
7196 //
7197 // For every cv-qualified or cv-unqualified object type T there
7198 // exist candidate operator functions of the form
7199 //
7200 // T* operator+(T*, ptrdiff_t); [ABOVE]
7201 // T& operator[](T*, ptrdiff_t);
7202 // T* operator-(T*, ptrdiff_t); [ABOVE]
7203 // T* operator+(ptrdiff_t, T*); [ABOVE]
7204 // T& operator[](ptrdiff_t, T*);
7205 void addSubscriptOverloads() {
7206 for (BuiltinCandidateTypeSet::iterator
7207 Ptr = CandidateTypes[0].pointer_begin(),
7208 PtrEnd = CandidateTypes[0].pointer_end();
7209 Ptr != PtrEnd; ++Ptr) {
7210 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7211 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007212 if (!PointeeType->isObjectType())
7213 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007214
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007215 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7216
7217 // T& operator[](T*, ptrdiff_t)
7218 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7219 }
7220
7221 for (BuiltinCandidateTypeSet::iterator
7222 Ptr = CandidateTypes[1].pointer_begin(),
7223 PtrEnd = CandidateTypes[1].pointer_end();
7224 Ptr != PtrEnd; ++Ptr) {
7225 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7226 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007227 if (!PointeeType->isObjectType())
7228 continue;
7229
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007230 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7231
7232 // T& operator[](ptrdiff_t, T*)
7233 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7234 }
7235 }
7236
7237 // C++ [over.built]p11:
7238 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7239 // C1 is the same type as C2 or is a derived class of C2, T is an object
7240 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7241 // there exist candidate operator functions of the form
7242 //
7243 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7244 //
7245 // where CV12 is the union of CV1 and CV2.
7246 void addArrowStarOverloads() {
7247 for (BuiltinCandidateTypeSet::iterator
7248 Ptr = CandidateTypes[0].pointer_begin(),
7249 PtrEnd = CandidateTypes[0].pointer_end();
7250 Ptr != PtrEnd; ++Ptr) {
7251 QualType C1Ty = (*Ptr);
7252 QualType C1;
7253 QualifierCollector Q1;
7254 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7255 if (!isa<RecordType>(C1))
7256 continue;
7257 // heuristic to reduce number of builtin candidates in the set.
7258 // Add volatile/restrict version only if there are conversions to a
7259 // volatile/restrict type.
7260 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7261 continue;
7262 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7263 continue;
7264 for (BuiltinCandidateTypeSet::iterator
7265 MemPtr = CandidateTypes[1].member_pointer_begin(),
7266 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7267 MemPtr != MemPtrEnd; ++MemPtr) {
7268 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7269 QualType C2 = QualType(mptr->getClass(), 0);
7270 C2 = C2.getUnqualifiedType();
7271 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7272 break;
7273 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7274 // build CV12 T&
7275 QualType T = mptr->getPointeeType();
7276 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7277 T.isVolatileQualified())
7278 continue;
7279 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7280 T.isRestrictQualified())
7281 continue;
7282 T = Q1.apply(S.Context, T);
7283 QualType ResultTy = S.Context.getLValueReferenceType(T);
7284 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7285 }
7286 }
7287 }
7288
7289 // Note that we don't consider the first argument, since it has been
7290 // contextually converted to bool long ago. The candidates below are
7291 // therefore added as binary.
7292 //
7293 // C++ [over.built]p25:
7294 // For every type T, where T is a pointer, pointer-to-member, or scoped
7295 // enumeration type, there exist candidate operator functions of the form
7296 //
7297 // T operator?(bool, T, T);
7298 //
7299 void addConditionalOperatorOverloads() {
7300 /// Set of (canonical) types that we've already handled.
7301 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7302
7303 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7304 for (BuiltinCandidateTypeSet::iterator
7305 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7306 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7307 Ptr != PtrEnd; ++Ptr) {
7308 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7309 continue;
7310
7311 QualType ParamTypes[2] = { *Ptr, *Ptr };
7312 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7313 }
7314
7315 for (BuiltinCandidateTypeSet::iterator
7316 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7317 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7318 MemPtr != MemPtrEnd; ++MemPtr) {
7319 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7320 continue;
7321
7322 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7323 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7324 }
7325
David Blaikie4e4d0842012-03-11 07:00:24 +00007326 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007327 for (BuiltinCandidateTypeSet::iterator
7328 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7329 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7330 Enum != EnumEnd; ++Enum) {
7331 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7332 continue;
7333
7334 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7335 continue;
7336
7337 QualType ParamTypes[2] = { *Enum, *Enum };
7338 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7339 }
7340 }
7341 }
7342 }
7343};
7344
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007345} // end anonymous namespace
7346
7347/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7348/// operator overloads to the candidate set (C++ [over.built]), based
7349/// on the operator @p Op and the arguments given. For example, if the
7350/// operator is a binary '+', this routine might add "int
7351/// operator+(int, int)" to cover integer addition.
7352void
7353Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7354 SourceLocation OpLoc,
7355 Expr **Args, unsigned NumArgs,
7356 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007357 // Find all of the types that the arguments can convert to, but only
7358 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007359 // that make use of these types. Also record whether we encounter non-record
7360 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007361 Qualifiers VisibleTypeConversionsQuals;
7362 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007363 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7364 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007365
7366 bool HasNonRecordCandidateType = false;
7367 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007368 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007369 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7370 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7371 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7372 OpLoc,
7373 true,
7374 (Op == OO_Exclaim ||
7375 Op == OO_AmpAmp ||
7376 Op == OO_PipePipe),
7377 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007378 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7379 CandidateTypes[ArgIdx].hasNonRecordTypes();
7380 HasArithmeticOrEnumeralCandidateType =
7381 HasArithmeticOrEnumeralCandidateType ||
7382 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007383 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007384
Chandler Carruth6a577462010-12-13 01:44:01 +00007385 // Exit early when no non-record types have been added to the candidate set
7386 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007387 //
7388 // We can't exit early for !, ||, or &&, since there we have always have
7389 // 'bool' overloads.
7390 if (!HasNonRecordCandidateType &&
7391 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007392 return;
7393
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007394 // Setup an object to manage the common state for building overloads.
7395 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7396 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007397 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007398 CandidateTypes, CandidateSet);
7399
7400 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007401 switch (Op) {
7402 case OO_None:
7403 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007404 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007405
Chandler Carruthabb71842010-12-12 08:51:33 +00007406 case OO_New:
7407 case OO_Delete:
7408 case OO_Array_New:
7409 case OO_Array_Delete:
7410 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007411 llvm_unreachable(
7412 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007413
7414 case OO_Comma:
7415 case OO_Arrow:
7416 // C++ [over.match.oper]p3:
7417 // -- For the operator ',', the unary operator '&', or the
7418 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007419 break;
7420
7421 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007422 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007423 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007424 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007425
7426 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007427 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007428 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007429 } else {
7430 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7431 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7432 }
Douglas Gregor74253732008-11-19 15:42:04 +00007433 break;
7434
Chandler Carruthabb71842010-12-12 08:51:33 +00007435 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007436 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007437 OpBuilder.addUnaryStarPointerOverloads();
7438 else
7439 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7440 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007441
Chandler Carruthabb71842010-12-12 08:51:33 +00007442 case OO_Slash:
7443 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007444 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007445
7446 case OO_PlusPlus:
7447 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007448 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7449 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007450 break;
7451
Douglas Gregor19b7b152009-08-24 13:43:27 +00007452 case OO_EqualEqual:
7453 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007454 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007455 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007456
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007457 case OO_Less:
7458 case OO_Greater:
7459 case OO_LessEqual:
7460 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007461 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007462 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7463 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007464
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007465 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007466 case OO_Caret:
7467 case OO_Pipe:
7468 case OO_LessLess:
7469 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007470 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007471 break;
7472
Chandler Carruthabb71842010-12-12 08:51:33 +00007473 case OO_Amp: // '&' is either unary or binary
7474 if (NumArgs == 1)
7475 // C++ [over.match.oper]p3:
7476 // -- For the operator ',', the unary operator '&', or the
7477 // operator '->', the built-in candidates set is empty.
7478 break;
7479
7480 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7481 break;
7482
7483 case OO_Tilde:
7484 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7485 break;
7486
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007487 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007488 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007489 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007490
7491 case OO_PlusEqual:
7492 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007493 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007494 // Fall through.
7495
7496 case OO_StarEqual:
7497 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007498 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007499 break;
7500
7501 case OO_PercentEqual:
7502 case OO_LessLessEqual:
7503 case OO_GreaterGreaterEqual:
7504 case OO_AmpEqual:
7505 case OO_CaretEqual:
7506 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007507 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007508 break;
7509
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007510 case OO_Exclaim:
7511 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007512 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007513
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007514 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007515 case OO_PipePipe:
7516 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007517 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007518
7519 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007520 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007521 break;
7522
7523 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007524 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007525 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007526
7527 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007528 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007529 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7530 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007531 }
7532}
7533
Douglas Gregorfa047642009-02-04 00:32:51 +00007534/// \brief Add function candidates found via argument-dependent lookup
7535/// to the set of overloading candidates.
7536///
7537/// This routine performs argument-dependent name lookup based on the
7538/// given function name (which may also be an operator name) and adds
7539/// all of the overload candidates found by ADL to the overload
7540/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007541void
Douglas Gregorfa047642009-02-04 00:32:51 +00007542Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007543 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007544 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007545 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007546 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007547 bool PartialOverloading,
7548 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007549 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007550
John McCalla113e722010-01-26 06:04:06 +00007551 // FIXME: This approach for uniquing ADL results (and removing
7552 // redundant candidates from the set) relies on pointer-equality,
7553 // which means we need to key off the canonical decl. However,
7554 // always going back to the canonical decl might not get us the
7555 // right set of default arguments. What default arguments are
7556 // we supposed to consider on ADL candidates, anyway?
7557
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007558 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007559 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007560 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007561
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007562 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007563 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7564 CandEnd = CandidateSet.end();
7565 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007566 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007567 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007568 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007569 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007570 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007571
7572 // For each of the ADL candidates we found, add it to the overload
7573 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007574 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007575 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007576 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007577 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007578 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007579
Ahmed Charles13a140c2012-02-25 11:00:22 +00007580 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7581 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007582 } else
John McCall6e266892010-01-26 03:27:55 +00007583 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007584 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007585 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007586 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007587}
7588
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007589/// isBetterOverloadCandidate - Determines whether the first overload
7590/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007591bool
John McCall120d63c2010-08-24 20:38:10 +00007592isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007593 const OverloadCandidate &Cand1,
7594 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007595 SourceLocation Loc,
7596 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007597 // Define viable functions to be better candidates than non-viable
7598 // functions.
7599 if (!Cand2.Viable)
7600 return Cand1.Viable;
7601 else if (!Cand1.Viable)
7602 return false;
7603
Douglas Gregor88a35142008-12-22 05:46:06 +00007604 // C++ [over.match.best]p1:
7605 //
7606 // -- if F is a static member function, ICS1(F) is defined such
7607 // that ICS1(F) is neither better nor worse than ICS1(G) for
7608 // any function G, and, symmetrically, ICS1(G) is neither
7609 // better nor worse than ICS1(F).
7610 unsigned StartArg = 0;
7611 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7612 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007613
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007614 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007615 // A viable function F1 is defined to be a better function than another
7616 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007617 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007618 unsigned NumArgs = Cand1.NumConversions;
7619 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007620 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007621 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007622 switch (CompareImplicitConversionSequences(S,
7623 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007624 Cand2.Conversions[ArgIdx])) {
7625 case ImplicitConversionSequence::Better:
7626 // Cand1 has a better conversion sequence.
7627 HasBetterConversion = true;
7628 break;
7629
7630 case ImplicitConversionSequence::Worse:
7631 // Cand1 can't be better than Cand2.
7632 return false;
7633
7634 case ImplicitConversionSequence::Indistinguishable:
7635 // Do nothing.
7636 break;
7637 }
7638 }
7639
Mike Stump1eb44332009-09-09 15:08:12 +00007640 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007641 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007642 if (HasBetterConversion)
7643 return true;
7644
Mike Stump1eb44332009-09-09 15:08:12 +00007645 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007646 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007647 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007648 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7649 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007650
7651 // -- F1 and F2 are function template specializations, and the function
7652 // template for F1 is more specialized than the template for F2
7653 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007654 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007655 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007656 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007657 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007658 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7659 Cand2.Function->getPrimaryTemplate(),
7660 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007661 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007662 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007663 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007664 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007665 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007666
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007667 // -- the context is an initialization by user-defined conversion
7668 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7669 // from the return type of F1 to the destination type (i.e.,
7670 // the type of the entity being initialized) is a better
7671 // conversion sequence than the standard conversion sequence
7672 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007673 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007674 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007675 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007676 // First check whether we prefer one of the conversion functions over the
7677 // other. This only distinguishes the results in non-standard, extension
7678 // cases such as the conversion from a lambda closure type to a function
7679 // pointer or block.
7680 ImplicitConversionSequence::CompareKind FuncResult
7681 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7682 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7683 return FuncResult;
7684
John McCall120d63c2010-08-24 20:38:10 +00007685 switch (CompareStandardConversionSequences(S,
7686 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007687 Cand2.FinalConversion)) {
7688 case ImplicitConversionSequence::Better:
7689 // Cand1 has a better conversion sequence.
7690 return true;
7691
7692 case ImplicitConversionSequence::Worse:
7693 // Cand1 can't be better than Cand2.
7694 return false;
7695
7696 case ImplicitConversionSequence::Indistinguishable:
7697 // Do nothing
7698 break;
7699 }
7700 }
7701
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007702 return false;
7703}
7704
Mike Stump1eb44332009-09-09 15:08:12 +00007705/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007706/// within an overload candidate set.
7707///
7708/// \param CandidateSet the set of candidate functions.
7709///
7710/// \param Loc the location of the function name (or operator symbol) for
7711/// which overload resolution occurs.
7712///
Mike Stump1eb44332009-09-09 15:08:12 +00007713/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007714/// function, Best points to the candidate function found.
7715///
7716/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007717OverloadingResult
7718OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007719 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007720 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007721 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007722 Best = end();
7723 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7724 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007725 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007726 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007727 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007728 }
7729
7730 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007731 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007732 return OR_No_Viable_Function;
7733
7734 // Make sure that this function is better than every other viable
7735 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007736 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007737 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007738 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007739 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007740 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007741 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007742 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007743 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007744 }
Mike Stump1eb44332009-09-09 15:08:12 +00007745
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007746 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007747 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007748 (Best->Function->isDeleted() ||
7749 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007750 return OR_Deleted;
7751
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007752 return OR_Success;
7753}
7754
John McCall3c80f572010-01-12 02:15:36 +00007755namespace {
7756
7757enum OverloadCandidateKind {
7758 oc_function,
7759 oc_method,
7760 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007761 oc_function_template,
7762 oc_method_template,
7763 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007764 oc_implicit_default_constructor,
7765 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007766 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007767 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007768 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007769 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007770};
7771
John McCall220ccbf2010-01-13 00:25:19 +00007772OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7773 FunctionDecl *Fn,
7774 std::string &Description) {
7775 bool isTemplate = false;
7776
7777 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7778 isTemplate = true;
7779 Description = S.getTemplateArgumentBindingsText(
7780 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7781 }
John McCallb1622a12010-01-06 09:43:14 +00007782
7783 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007784 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007785 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007786
Sebastian Redlf677ea32011-02-05 19:23:19 +00007787 if (Ctor->getInheritedConstructor())
7788 return oc_implicit_inherited_constructor;
7789
Sean Hunt82713172011-05-25 23:16:36 +00007790 if (Ctor->isDefaultConstructor())
7791 return oc_implicit_default_constructor;
7792
7793 if (Ctor->isMoveConstructor())
7794 return oc_implicit_move_constructor;
7795
7796 assert(Ctor->isCopyConstructor() &&
7797 "unexpected sort of implicit constructor");
7798 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007799 }
7800
7801 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7802 // This actually gets spelled 'candidate function' for now, but
7803 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007804 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007805 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007806
Sean Hunt82713172011-05-25 23:16:36 +00007807 if (Meth->isMoveAssignmentOperator())
7808 return oc_implicit_move_assignment;
7809
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007810 if (Meth->isCopyAssignmentOperator())
7811 return oc_implicit_copy_assignment;
7812
7813 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7814 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007815 }
7816
John McCall220ccbf2010-01-13 00:25:19 +00007817 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007818}
7819
Sebastian Redlf677ea32011-02-05 19:23:19 +00007820void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7821 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7822 if (!Ctor) return;
7823
7824 Ctor = Ctor->getInheritedConstructor();
7825 if (!Ctor) return;
7826
7827 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7828}
7829
John McCall3c80f572010-01-12 02:15:36 +00007830} // end anonymous namespace
7831
7832// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007833void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007834 std::string FnDesc;
7835 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007836 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7837 << (unsigned) K << FnDesc;
7838 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7839 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007840 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007841}
7842
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007843//Notes the location of all overload candidates designated through
7844// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007845void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007846 assert(OverloadedExpr->getType() == Context.OverloadTy);
7847
7848 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7849 OverloadExpr *OvlExpr = Ovl.Expression;
7850
7851 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7852 IEnd = OvlExpr->decls_end();
7853 I != IEnd; ++I) {
7854 if (FunctionTemplateDecl *FunTmpl =
7855 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007856 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007857 } else if (FunctionDecl *Fun
7858 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007859 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007860 }
7861 }
7862}
7863
John McCall1d318332010-01-12 00:44:57 +00007864/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7865/// "lead" diagnostic; it will be given two arguments, the source and
7866/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007867void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7868 Sema &S,
7869 SourceLocation CaretLoc,
7870 const PartialDiagnostic &PDiag) const {
7871 S.Diag(CaretLoc, PDiag)
7872 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007873 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007874 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7875 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007876 }
John McCall81201622010-01-08 04:41:39 +00007877}
7878
John McCall1d318332010-01-12 00:44:57 +00007879namespace {
7880
John McCalladbb8f82010-01-13 09:16:55 +00007881void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7882 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7883 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007884 assert(Cand->Function && "for now, candidate must be a function");
7885 FunctionDecl *Fn = Cand->Function;
7886
7887 // There's a conversion slot for the object argument if this is a
7888 // non-constructor method. Note that 'I' corresponds the
7889 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007890 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007891 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007892 if (I == 0)
7893 isObjectArgument = true;
7894 else
7895 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007896 }
7897
John McCall220ccbf2010-01-13 00:25:19 +00007898 std::string FnDesc;
7899 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7900
John McCalladbb8f82010-01-13 09:16:55 +00007901 Expr *FromExpr = Conv.Bad.FromExpr;
7902 QualType FromTy = Conv.Bad.getFromType();
7903 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007904
John McCall5920dbb2010-02-02 02:42:52 +00007905 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007906 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007907 Expr *E = FromExpr->IgnoreParens();
7908 if (isa<UnaryOperator>(E))
7909 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007910 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007911
7912 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7913 << (unsigned) FnKind << FnDesc
7914 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7915 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007916 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007917 return;
7918 }
7919
John McCall258b2032010-01-23 08:10:49 +00007920 // Do some hand-waving analysis to see if the non-viability is due
7921 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007922 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7923 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7924 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7925 CToTy = RT->getPointeeType();
7926 else {
7927 // TODO: detect and diagnose the full richness of const mismatches.
7928 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7929 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7930 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7931 }
7932
7933 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7934 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00007935 Qualifiers FromQs = CFromTy.getQualifiers();
7936 Qualifiers ToQs = CToTy.getQualifiers();
7937
7938 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7939 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7940 << (unsigned) FnKind << FnDesc
7941 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7942 << FromTy
7943 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7944 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007945 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007946 return;
7947 }
7948
John McCallf85e1932011-06-15 23:02:42 +00007949 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007950 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007951 << (unsigned) FnKind << FnDesc
7952 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7953 << FromTy
7954 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7955 << (unsigned) isObjectArgument << I+1;
7956 MaybeEmitInheritedConstructorNote(S, Fn);
7957 return;
7958 }
7959
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007960 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7961 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7962 << (unsigned) FnKind << FnDesc
7963 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7964 << FromTy
7965 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7966 << (unsigned) isObjectArgument << I+1;
7967 MaybeEmitInheritedConstructorNote(S, Fn);
7968 return;
7969 }
7970
John McCall651f3ee2010-01-14 03:28:57 +00007971 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7972 assert(CVR && "unexpected qualifiers mismatch");
7973
7974 if (isObjectArgument) {
7975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7976 << (unsigned) FnKind << FnDesc
7977 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7978 << FromTy << (CVR - 1);
7979 } else {
7980 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7981 << (unsigned) FnKind << FnDesc
7982 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7983 << FromTy << (CVR - 1) << I+1;
7984 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007985 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007986 return;
7987 }
7988
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007989 // Special diagnostic for failure to convert an initializer list, since
7990 // telling the user that it has type void is not useful.
7991 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7992 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7993 << (unsigned) FnKind << FnDesc
7994 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7995 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7996 MaybeEmitInheritedConstructorNote(S, Fn);
7997 return;
7998 }
7999
John McCall258b2032010-01-23 08:10:49 +00008000 // Diagnose references or pointers to incomplete types differently,
8001 // since it's far from impossible that the incompleteness triggered
8002 // the failure.
8003 QualType TempFromTy = FromTy.getNonReferenceType();
8004 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8005 TempFromTy = PTy->getPointeeType();
8006 if (TempFromTy->isIncompleteType()) {
8007 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8008 << (unsigned) FnKind << FnDesc
8009 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8010 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008011 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008012 return;
8013 }
8014
Douglas Gregor85789812010-06-30 23:01:39 +00008015 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008016 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008017 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8018 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8019 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8020 FromPtrTy->getPointeeType()) &&
8021 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8022 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008023 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008024 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008025 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008026 }
8027 } else if (const ObjCObjectPointerType *FromPtrTy
8028 = FromTy->getAs<ObjCObjectPointerType>()) {
8029 if (const ObjCObjectPointerType *ToPtrTy
8030 = ToTy->getAs<ObjCObjectPointerType>())
8031 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8032 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8033 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8034 FromPtrTy->getPointeeType()) &&
8035 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008036 BaseToDerivedConversion = 2;
8037 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8038 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8039 !FromTy->isIncompleteType() &&
8040 !ToRefTy->getPointeeType()->isIncompleteType() &&
8041 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
8042 BaseToDerivedConversion = 3;
8043 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008044
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008045 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008046 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008047 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008048 << (unsigned) FnKind << FnDesc
8049 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008050 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008051 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008052 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008053 return;
8054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008055
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008056 if (isa<ObjCObjectPointerType>(CFromTy) &&
8057 isa<PointerType>(CToTy)) {
8058 Qualifiers FromQs = CFromTy.getQualifiers();
8059 Qualifiers ToQs = CToTy.getQualifiers();
8060 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8061 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8062 << (unsigned) FnKind << FnDesc
8063 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8064 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8065 MaybeEmitInheritedConstructorNote(S, Fn);
8066 return;
8067 }
8068 }
8069
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008070 // Emit the generic diagnostic and, optionally, add the hints to it.
8071 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8072 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008074 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8075 << (unsigned) (Cand->Fix.Kind);
8076
8077 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008078 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8079 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008080 FDiag << *HI;
8081 S.Diag(Fn->getLocation(), FDiag);
8082
Sebastian Redlf677ea32011-02-05 19:23:19 +00008083 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008084}
8085
8086void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8087 unsigned NumFormalArgs) {
8088 // TODO: treat calls to a missing default constructor as a special case
8089
8090 FunctionDecl *Fn = Cand->Function;
8091 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8092
8093 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008094
Douglas Gregor439d3c32011-05-05 00:13:13 +00008095 // With invalid overloaded operators, it's possible that we think we
8096 // have an arity mismatch when it fact it looks like we have the
8097 // right number of arguments, because only overloaded operators have
8098 // the weird behavior of overloading member and non-member functions.
8099 // Just don't report anything.
8100 if (Fn->isInvalidDecl() &&
8101 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8102 return;
8103
John McCalladbb8f82010-01-13 09:16:55 +00008104 // at least / at most / exactly
8105 unsigned mode, modeCount;
8106 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008107 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8108 (Cand->FailureKind == ovl_fail_bad_deduction &&
8109 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008110 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008111 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008112 mode = 0; // "at least"
8113 else
8114 mode = 2; // "exactly"
8115 modeCount = MinParams;
8116 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008117 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8118 (Cand->FailureKind == ovl_fail_bad_deduction &&
8119 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008120 if (MinParams != FnTy->getNumArgs())
8121 mode = 1; // "at most"
8122 else
8123 mode = 2; // "exactly"
8124 modeCount = FnTy->getNumArgs();
8125 }
8126
8127 std::string Description;
8128 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8129
8130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008131 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00008132 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008133 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008134}
8135
John McCall342fec42010-02-01 18:53:26 +00008136/// Diagnose a failed template-argument deduction.
8137void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008138 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008139 FunctionDecl *Fn = Cand->Function; // pattern
8140
Douglas Gregora9333192010-05-08 17:41:32 +00008141 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008142 NamedDecl *ParamD;
8143 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8144 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8145 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008146 switch (Cand->DeductionFailure.Result) {
8147 case Sema::TDK_Success:
8148 llvm_unreachable("TDK_success while diagnosing bad deduction");
8149
8150 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008151 assert(ParamD && "no parameter found for incomplete deduction result");
8152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8153 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008154 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008155 return;
8156 }
8157
John McCall57e97782010-08-05 09:05:08 +00008158 case Sema::TDK_Underqualified: {
8159 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8160 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8161
8162 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8163
8164 // Param will have been canonicalized, but it should just be a
8165 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008166 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008167 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008168 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008169 assert(S.Context.hasSameType(Param, NonCanonParam));
8170
8171 // Arg has also been canonicalized, but there's nothing we can do
8172 // about that. It also doesn't matter as much, because it won't
8173 // have any template parameters in it (because deduction isn't
8174 // done on dependent types).
8175 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8176
8177 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8178 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008179 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008180 return;
8181 }
8182
8183 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008184 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008185 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008186 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008187 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008188 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008189 which = 1;
8190 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008191 which = 2;
8192 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008193
Douglas Gregora9333192010-05-08 17:41:32 +00008194 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008195 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008196 << *Cand->DeductionFailure.getFirstArg()
8197 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008198 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008199 return;
8200 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008201
Douglas Gregorf1a84452010-05-08 19:15:54 +00008202 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008203 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008204 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008205 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008206 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8207 << ParamD->getDeclName();
8208 else {
8209 int index = 0;
8210 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8211 index = TTP->getIndex();
8212 else if (NonTypeTemplateParmDecl *NTTP
8213 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8214 index = NTTP->getIndex();
8215 else
8216 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008217 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008218 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8219 << (index + 1);
8220 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008221 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008222 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008223
Douglas Gregora18592e2010-05-08 18:13:28 +00008224 case Sema::TDK_TooManyArguments:
8225 case Sema::TDK_TooFewArguments:
8226 DiagnoseArityMismatch(S, Cand, NumArgs);
8227 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008228
8229 case Sema::TDK_InstantiationDepth:
8230 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008231 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008232 return;
8233
8234 case Sema::TDK_SubstitutionFailure: {
8235 std::string ArgString;
8236 if (TemplateArgumentList *Args
8237 = Cand->DeductionFailure.getTemplateArgumentList())
8238 ArgString = S.getTemplateArgumentBindingsText(
8239 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8240 *Args);
8241 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8242 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008243 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008244 return;
8245 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008246
John McCall342fec42010-02-01 18:53:26 +00008247 // TODO: diagnose these individually, then kill off
8248 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008249 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008250 case Sema::TDK_FailedOverloadResolution:
8251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008252 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008253 return;
8254 }
8255}
8256
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008257/// CUDA: diagnose an invalid call across targets.
8258void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8259 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8260 FunctionDecl *Callee = Cand->Function;
8261
8262 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8263 CalleeTarget = S.IdentifyCUDATarget(Callee);
8264
8265 std::string FnDesc;
8266 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8267
8268 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8269 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8270}
8271
John McCall342fec42010-02-01 18:53:26 +00008272/// Generates a 'note' diagnostic for an overload candidate. We've
8273/// already generated a primary error at the call site.
8274///
8275/// It really does need to be a single diagnostic with its caret
8276/// pointed at the candidate declaration. Yes, this creates some
8277/// major challenges of technical writing. Yes, this makes pointing
8278/// out problems with specific arguments quite awkward. It's still
8279/// better than generating twenty screens of text for every failed
8280/// overload.
8281///
8282/// It would be great to be able to express per-candidate problems
8283/// more richly for those diagnostic clients that cared, but we'd
8284/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008285void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008286 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008287 FunctionDecl *Fn = Cand->Function;
8288
John McCall81201622010-01-08 04:41:39 +00008289 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008290 if (Cand->Viable && (Fn->isDeleted() ||
8291 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008292 std::string FnDesc;
8293 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008294
8295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008296 << FnKind << FnDesc
8297 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008298 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008299 return;
John McCall81201622010-01-08 04:41:39 +00008300 }
8301
John McCall220ccbf2010-01-13 00:25:19 +00008302 // We don't really have anything else to say about viable candidates.
8303 if (Cand->Viable) {
8304 S.NoteOverloadCandidate(Fn);
8305 return;
8306 }
John McCall1d318332010-01-12 00:44:57 +00008307
John McCalladbb8f82010-01-13 09:16:55 +00008308 switch (Cand->FailureKind) {
8309 case ovl_fail_too_many_arguments:
8310 case ovl_fail_too_few_arguments:
8311 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008312
John McCalladbb8f82010-01-13 09:16:55 +00008313 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008314 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008315
John McCall717e8912010-01-23 05:17:32 +00008316 case ovl_fail_trivial_conversion:
8317 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008318 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008319 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008320
John McCallb1bdc622010-02-25 01:37:24 +00008321 case ovl_fail_bad_conversion: {
8322 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008323 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008324 if (Cand->Conversions[I].isBad())
8325 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008326
John McCalladbb8f82010-01-13 09:16:55 +00008327 // FIXME: this currently happens when we're called from SemaInit
8328 // when user-conversion overload fails. Figure out how to handle
8329 // those conditions and diagnose them well.
8330 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008331 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008332
8333 case ovl_fail_bad_target:
8334 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008335 }
John McCalla1d7d622010-01-08 00:58:21 +00008336}
8337
8338void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8339 // Desugar the type of the surrogate down to a function type,
8340 // retaining as many typedefs as possible while still showing
8341 // the function type (and, therefore, its parameter types).
8342 QualType FnType = Cand->Surrogate->getConversionType();
8343 bool isLValueReference = false;
8344 bool isRValueReference = false;
8345 bool isPointer = false;
8346 if (const LValueReferenceType *FnTypeRef =
8347 FnType->getAs<LValueReferenceType>()) {
8348 FnType = FnTypeRef->getPointeeType();
8349 isLValueReference = true;
8350 } else if (const RValueReferenceType *FnTypeRef =
8351 FnType->getAs<RValueReferenceType>()) {
8352 FnType = FnTypeRef->getPointeeType();
8353 isRValueReference = true;
8354 }
8355 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8356 FnType = FnTypePtr->getPointeeType();
8357 isPointer = true;
8358 }
8359 // Desugar down to a function type.
8360 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8361 // Reconstruct the pointer/reference as appropriate.
8362 if (isPointer) FnType = S.Context.getPointerType(FnType);
8363 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8364 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8365
8366 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8367 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008368 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008369}
8370
8371void NoteBuiltinOperatorCandidate(Sema &S,
8372 const char *Opc,
8373 SourceLocation OpLoc,
8374 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008375 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008376 std::string TypeStr("operator");
8377 TypeStr += Opc;
8378 TypeStr += "(";
8379 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008380 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008381 TypeStr += ")";
8382 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8383 } else {
8384 TypeStr += ", ";
8385 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8386 TypeStr += ")";
8387 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8388 }
8389}
8390
8391void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8392 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008393 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008394 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8395 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008396 if (ICS.isBad()) break; // all meaningless after first invalid
8397 if (!ICS.isAmbiguous()) continue;
8398
John McCall120d63c2010-08-24 20:38:10 +00008399 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008400 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008401 }
8402}
8403
John McCall1b77e732010-01-15 23:32:50 +00008404SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8405 if (Cand->Function)
8406 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008407 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008408 return Cand->Surrogate->getLocation();
8409 return SourceLocation();
8410}
8411
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008412static unsigned
8413RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008414 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008415 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008416 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008417
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008418 case Sema::TDK_Incomplete:
8419 return 1;
8420
8421 case Sema::TDK_Underqualified:
8422 case Sema::TDK_Inconsistent:
8423 return 2;
8424
8425 case Sema::TDK_SubstitutionFailure:
8426 case Sema::TDK_NonDeducedMismatch:
8427 return 3;
8428
8429 case Sema::TDK_InstantiationDepth:
8430 case Sema::TDK_FailedOverloadResolution:
8431 return 4;
8432
8433 case Sema::TDK_InvalidExplicitArguments:
8434 return 5;
8435
8436 case Sema::TDK_TooManyArguments:
8437 case Sema::TDK_TooFewArguments:
8438 return 6;
8439 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008440 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008441}
8442
John McCallbf65c0b2010-01-12 00:48:53 +00008443struct CompareOverloadCandidatesForDisplay {
8444 Sema &S;
8445 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008446
8447 bool operator()(const OverloadCandidate *L,
8448 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008449 // Fast-path this check.
8450 if (L == R) return false;
8451
John McCall81201622010-01-08 04:41:39 +00008452 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008453 if (L->Viable) {
8454 if (!R->Viable) return true;
8455
8456 // TODO: introduce a tri-valued comparison for overload
8457 // candidates. Would be more worthwhile if we had a sort
8458 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008459 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8460 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008461 } else if (R->Viable)
8462 return false;
John McCall81201622010-01-08 04:41:39 +00008463
John McCall1b77e732010-01-15 23:32:50 +00008464 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008465
John McCall1b77e732010-01-15 23:32:50 +00008466 // Criteria by which we can sort non-viable candidates:
8467 if (!L->Viable) {
8468 // 1. Arity mismatches come after other candidates.
8469 if (L->FailureKind == ovl_fail_too_many_arguments ||
8470 L->FailureKind == ovl_fail_too_few_arguments)
8471 return false;
8472 if (R->FailureKind == ovl_fail_too_many_arguments ||
8473 R->FailureKind == ovl_fail_too_few_arguments)
8474 return true;
John McCall81201622010-01-08 04:41:39 +00008475
John McCall717e8912010-01-23 05:17:32 +00008476 // 2. Bad conversions come first and are ordered by the number
8477 // of bad conversions and quality of good conversions.
8478 if (L->FailureKind == ovl_fail_bad_conversion) {
8479 if (R->FailureKind != ovl_fail_bad_conversion)
8480 return true;
8481
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008482 // The conversion that can be fixed with a smaller number of changes,
8483 // comes first.
8484 unsigned numLFixes = L->Fix.NumConversionsFixed;
8485 unsigned numRFixes = R->Fix.NumConversionsFixed;
8486 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8487 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008488 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008489 if (numLFixes < numRFixes)
8490 return true;
8491 else
8492 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008493 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008494
John McCall717e8912010-01-23 05:17:32 +00008495 // If there's any ordering between the defined conversions...
8496 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008497 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008498
8499 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008500 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008501 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008502 switch (CompareImplicitConversionSequences(S,
8503 L->Conversions[I],
8504 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008505 case ImplicitConversionSequence::Better:
8506 leftBetter++;
8507 break;
8508
8509 case ImplicitConversionSequence::Worse:
8510 leftBetter--;
8511 break;
8512
8513 case ImplicitConversionSequence::Indistinguishable:
8514 break;
8515 }
8516 }
8517 if (leftBetter > 0) return true;
8518 if (leftBetter < 0) return false;
8519
8520 } else if (R->FailureKind == ovl_fail_bad_conversion)
8521 return false;
8522
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008523 if (L->FailureKind == ovl_fail_bad_deduction) {
8524 if (R->FailureKind != ovl_fail_bad_deduction)
8525 return true;
8526
8527 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8528 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008529 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008530 } else if (R->FailureKind == ovl_fail_bad_deduction)
8531 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008532
John McCall1b77e732010-01-15 23:32:50 +00008533 // TODO: others?
8534 }
8535
8536 // Sort everything else by location.
8537 SourceLocation LLoc = GetLocationForCandidate(L);
8538 SourceLocation RLoc = GetLocationForCandidate(R);
8539
8540 // Put candidates without locations (e.g. builtins) at the end.
8541 if (LLoc.isInvalid()) return false;
8542 if (RLoc.isInvalid()) return true;
8543
8544 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008545 }
8546};
8547
John McCall717e8912010-01-23 05:17:32 +00008548/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008549/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008550void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008551 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008552 assert(!Cand->Viable);
8553
8554 // Don't do anything on failures other than bad conversion.
8555 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8556
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008557 // We only want the FixIts if all the arguments can be corrected.
8558 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008559 // Use a implicit copy initialization to check conversion fixes.
8560 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008561
John McCall717e8912010-01-23 05:17:32 +00008562 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008563 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008564 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008565 while (true) {
8566 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8567 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008568 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008569 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008570 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008571 }
John McCall717e8912010-01-23 05:17:32 +00008572 }
8573
8574 if (ConvIdx == ConvCount)
8575 return;
8576
John McCallb1bdc622010-02-25 01:37:24 +00008577 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8578 "remaining conversion is initialized?");
8579
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008580 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008581 // operation somehow.
8582 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008583
8584 const FunctionProtoType* Proto;
8585 unsigned ArgIdx = ConvIdx;
8586
8587 if (Cand->IsSurrogate) {
8588 QualType ConvType
8589 = Cand->Surrogate->getConversionType().getNonReferenceType();
8590 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8591 ConvType = ConvPtrType->getPointeeType();
8592 Proto = ConvType->getAs<FunctionProtoType>();
8593 ArgIdx--;
8594 } else if (Cand->Function) {
8595 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8596 if (isa<CXXMethodDecl>(Cand->Function) &&
8597 !isa<CXXConstructorDecl>(Cand->Function))
8598 ArgIdx--;
8599 } else {
8600 // Builtin binary operator with a bad first conversion.
8601 assert(ConvCount <= 3);
8602 for (; ConvIdx != ConvCount; ++ConvIdx)
8603 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008604 = TryCopyInitialization(S, Args[ConvIdx],
8605 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008606 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008607 /*InOverloadResolution*/ true,
8608 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008609 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008610 return;
8611 }
8612
8613 // Fill in the rest of the conversions.
8614 unsigned NumArgsInProto = Proto->getNumArgs();
8615 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008616 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008617 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008618 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008619 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008620 /*InOverloadResolution=*/true,
8621 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008622 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008623 // Store the FixIt in the candidate if it exists.
8624 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008625 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008626 }
John McCall717e8912010-01-23 05:17:32 +00008627 else
8628 Cand->Conversions[ConvIdx].setEllipsis();
8629 }
8630}
8631
John McCalla1d7d622010-01-08 00:58:21 +00008632} // end anonymous namespace
8633
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008634/// PrintOverloadCandidates - When overload resolution fails, prints
8635/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008636/// set.
John McCall120d63c2010-08-24 20:38:10 +00008637void OverloadCandidateSet::NoteCandidates(Sema &S,
8638 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008639 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008640 const char *Opc,
8641 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008642 // Sort the candidates by viability and position. Sorting directly would
8643 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008644 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008645 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8646 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008647 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008648 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008649 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008650 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008651 if (Cand->Function || Cand->IsSurrogate)
8652 Cands.push_back(Cand);
8653 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8654 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008655 }
8656 }
8657
John McCallbf65c0b2010-01-12 00:48:53 +00008658 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008659 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008660
John McCall1d318332010-01-12 00:44:57 +00008661 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008662
Chris Lattner5f9e2722011-07-23 10:55:15 +00008663 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008664 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8665 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008666 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008667 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8668 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008669
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008670 // Set an arbitrary limit on the number of candidate functions we'll spam
8671 // the user with. FIXME: This limit should depend on details of the
8672 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008673 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008674 break;
8675 }
8676 ++CandsShown;
8677
John McCalla1d7d622010-01-08 00:58:21 +00008678 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008679 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008680 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008681 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008682 else {
8683 assert(Cand->Viable &&
8684 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008685 // Generally we only see ambiguities including viable builtin
8686 // operators if overload resolution got screwed up by an
8687 // ambiguous user-defined conversion.
8688 //
8689 // FIXME: It's quite possible for different conversions to see
8690 // different ambiguities, though.
8691 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008692 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008693 ReportedAmbiguousConversions = true;
8694 }
John McCalla1d7d622010-01-08 00:58:21 +00008695
John McCall1d318332010-01-12 00:44:57 +00008696 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008697 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008698 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008699 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008700
8701 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008702 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008703}
8704
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008705// [PossiblyAFunctionType] --> [Return]
8706// NonFunctionType --> NonFunctionType
8707// R (A) --> R(A)
8708// R (*)(A) --> R (A)
8709// R (&)(A) --> R (A)
8710// R (S::*)(A) --> R (A)
8711QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8712 QualType Ret = PossiblyAFunctionType;
8713 if (const PointerType *ToTypePtr =
8714 PossiblyAFunctionType->getAs<PointerType>())
8715 Ret = ToTypePtr->getPointeeType();
8716 else if (const ReferenceType *ToTypeRef =
8717 PossiblyAFunctionType->getAs<ReferenceType>())
8718 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008719 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008720 PossiblyAFunctionType->getAs<MemberPointerType>())
8721 Ret = MemTypePtr->getPointeeType();
8722 Ret =
8723 Context.getCanonicalType(Ret).getUnqualifiedType();
8724 return Ret;
8725}
Douglas Gregor904eed32008-11-10 20:40:00 +00008726
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008727// A helper class to help with address of function resolution
8728// - allows us to avoid passing around all those ugly parameters
8729class AddressOfFunctionResolver
8730{
8731 Sema& S;
8732 Expr* SourceExpr;
8733 const QualType& TargetType;
8734 QualType TargetFunctionType; // Extracted function type from target type
8735
8736 bool Complain;
8737 //DeclAccessPair& ResultFunctionAccessPair;
8738 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008739
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008740 bool TargetTypeIsNonStaticMemberFunction;
8741 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008742
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008743 OverloadExpr::FindResult OvlExprInfo;
8744 OverloadExpr *OvlExpr;
8745 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008746 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008747
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008748public:
8749 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8750 const QualType& TargetType, bool Complain)
8751 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8752 Complain(Complain), Context(S.getASTContext()),
8753 TargetTypeIsNonStaticMemberFunction(
8754 !!TargetType->getAs<MemberPointerType>()),
8755 FoundNonTemplateFunction(false),
8756 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8757 OvlExpr(OvlExprInfo.Expression)
8758 {
8759 ExtractUnqualifiedFunctionTypeFromTargetType();
8760
8761 if (!TargetFunctionType->isFunctionType()) {
8762 if (OvlExpr->hasExplicitTemplateArgs()) {
8763 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008764 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008765 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008766
8767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8768 if (!Method->isStatic()) {
8769 // If the target type is a non-function type and the function
8770 // found is a non-static member function, pretend as if that was
8771 // the target, it's the only possible type to end up with.
8772 TargetTypeIsNonStaticMemberFunction = true;
8773
8774 // And skip adding the function if its not in the proper form.
8775 // We'll diagnose this due to an empty set of functions.
8776 if (!OvlExprInfo.HasFormOfMemberPointer)
8777 return;
8778 }
8779 }
8780
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008781 Matches.push_back(std::make_pair(dap,Fn));
8782 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008783 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008784 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008785 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008786
8787 if (OvlExpr->hasExplicitTemplateArgs())
8788 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008789
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008790 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8791 // C++ [over.over]p4:
8792 // If more than one function is selected, [...]
8793 if (Matches.size() > 1) {
8794 if (FoundNonTemplateFunction)
8795 EliminateAllTemplateMatches();
8796 else
8797 EliminateAllExceptMostSpecializedTemplate();
8798 }
8799 }
8800 }
8801
8802private:
8803 bool isTargetTypeAFunction() const {
8804 return TargetFunctionType->isFunctionType();
8805 }
8806
8807 // [ToType] [Return]
8808
8809 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8810 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8811 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8812 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8813 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8814 }
8815
8816 // return true if any matching specializations were found
8817 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8818 const DeclAccessPair& CurAccessFunPair) {
8819 if (CXXMethodDecl *Method
8820 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8821 // Skip non-static function templates when converting to pointer, and
8822 // static when converting to member pointer.
8823 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8824 return false;
8825 }
8826 else if (TargetTypeIsNonStaticMemberFunction)
8827 return false;
8828
8829 // C++ [over.over]p2:
8830 // If the name is a function template, template argument deduction is
8831 // done (14.8.2.2), and if the argument deduction succeeds, the
8832 // resulting template argument list is used to generate a single
8833 // function template specialization, which is added to the set of
8834 // overloaded functions considered.
8835 FunctionDecl *Specialization = 0;
8836 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8837 if (Sema::TemplateDeductionResult Result
8838 = S.DeduceTemplateArguments(FunctionTemplate,
8839 &OvlExplicitTemplateArgs,
8840 TargetFunctionType, Specialization,
8841 Info)) {
8842 // FIXME: make a note of the failed deduction for diagnostics.
8843 (void)Result;
8844 return false;
8845 }
8846
8847 // Template argument deduction ensures that we have an exact match.
8848 // This function template specicalization works.
8849 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8850 assert(TargetFunctionType
8851 == Context.getCanonicalType(Specialization->getType()));
8852 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8853 return true;
8854 }
8855
8856 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8857 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008859 // Skip non-static functions when converting to pointer, and static
8860 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008861 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8862 return false;
8863 }
8864 else if (TargetTypeIsNonStaticMemberFunction)
8865 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008866
Chandler Carruthbd647292009-12-29 06:17:27 +00008867 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008868 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008869 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8870 if (S.CheckCUDATarget(Caller, FunDecl))
8871 return false;
8872
Douglas Gregor43c79c22009-12-09 00:47:37 +00008873 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008874 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8875 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008876 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8877 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008878 Matches.push_back(std::make_pair(CurAccessFunPair,
8879 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008880 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008881 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008882 }
Mike Stump1eb44332009-09-09 15:08:12 +00008883 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008884
8885 return false;
8886 }
8887
8888 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8889 bool Ret = false;
8890
8891 // If the overload expression doesn't have the form of a pointer to
8892 // member, don't try to convert it to a pointer-to-member type.
8893 if (IsInvalidFormOfPointerToMemberFunction())
8894 return false;
8895
8896 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8897 E = OvlExpr->decls_end();
8898 I != E; ++I) {
8899 // Look through any using declarations to find the underlying function.
8900 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8901
8902 // C++ [over.over]p3:
8903 // Non-member functions and static member functions match
8904 // targets of type "pointer-to-function" or "reference-to-function."
8905 // Nonstatic member functions match targets of
8906 // type "pointer-to-member-function."
8907 // Note that according to DR 247, the containing class does not matter.
8908 if (FunctionTemplateDecl *FunctionTemplate
8909 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8910 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8911 Ret = true;
8912 }
8913 // If we have explicit template arguments supplied, skip non-templates.
8914 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8915 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8916 Ret = true;
8917 }
8918 assert(Ret || Matches.empty());
8919 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008920 }
8921
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008922 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008923 // [...] and any given function template specialization F1 is
8924 // eliminated if the set contains a second function template
8925 // specialization whose function template is more specialized
8926 // than the function template of F1 according to the partial
8927 // ordering rules of 14.5.5.2.
8928
8929 // The algorithm specified above is quadratic. We instead use a
8930 // two-pass algorithm (similar to the one used to identify the
8931 // best viable function in an overload set) that identifies the
8932 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008933
8934 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8935 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8936 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008937
John McCallc373d482010-01-27 01:50:18 +00008938 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008939 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8940 TPOC_Other, 0, SourceExpr->getLocStart(),
8941 S.PDiag(),
8942 S.PDiag(diag::err_addr_ovl_ambiguous)
8943 << Matches[0].second->getDeclName(),
8944 S.PDiag(diag::note_ovl_candidate)
8945 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008946 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008947
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008948 if (Result != MatchesCopy.end()) {
8949 // Make it the first and only element
8950 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8951 Matches[0].second = cast<FunctionDecl>(*Result);
8952 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008953 }
8954 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008955
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008956 void EliminateAllTemplateMatches() {
8957 // [...] any function template specializations in the set are
8958 // eliminated if the set also contains a non-template function, [...]
8959 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8960 if (Matches[I].second->getPrimaryTemplate() == 0)
8961 ++I;
8962 else {
8963 Matches[I] = Matches[--N];
8964 Matches.set_size(N);
8965 }
8966 }
8967 }
8968
8969public:
8970 void ComplainNoMatchesFound() const {
8971 assert(Matches.empty());
8972 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8973 << OvlExpr->getName() << TargetFunctionType
8974 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008975 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008976 }
8977
8978 bool IsInvalidFormOfPointerToMemberFunction() const {
8979 return TargetTypeIsNonStaticMemberFunction &&
8980 !OvlExprInfo.HasFormOfMemberPointer;
8981 }
8982
8983 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8984 // TODO: Should we condition this on whether any functions might
8985 // have matched, or is it more appropriate to do that in callers?
8986 // TODO: a fixit wouldn't hurt.
8987 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8988 << TargetType << OvlExpr->getSourceRange();
8989 }
8990
8991 void ComplainOfInvalidConversion() const {
8992 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8993 << OvlExpr->getName() << TargetType;
8994 }
8995
8996 void ComplainMultipleMatchesFound() const {
8997 assert(Matches.size() > 1);
8998 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8999 << OvlExpr->getName()
9000 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009001 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009002 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009003
9004 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9005
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009006 int getNumMatches() const { return Matches.size(); }
9007
9008 FunctionDecl* getMatchingFunctionDecl() const {
9009 if (Matches.size() != 1) return 0;
9010 return Matches[0].second;
9011 }
9012
9013 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9014 if (Matches.size() != 1) return 0;
9015 return &Matches[0].first;
9016 }
9017};
9018
9019/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9020/// an overloaded function (C++ [over.over]), where @p From is an
9021/// expression with overloaded function type and @p ToType is the type
9022/// we're trying to resolve to. For example:
9023///
9024/// @code
9025/// int f(double);
9026/// int f(int);
9027///
9028/// int (*pfd)(double) = f; // selects f(double)
9029/// @endcode
9030///
9031/// This routine returns the resulting FunctionDecl if it could be
9032/// resolved, and NULL otherwise. When @p Complain is true, this
9033/// routine will emit diagnostics if there is an error.
9034FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009035Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9036 QualType TargetType,
9037 bool Complain,
9038 DeclAccessPair &FoundResult,
9039 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009040 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009041
9042 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9043 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009044 int NumMatches = Resolver.getNumMatches();
9045 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009046 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009047 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9048 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9049 else
9050 Resolver.ComplainNoMatchesFound();
9051 }
9052 else if (NumMatches > 1 && Complain)
9053 Resolver.ComplainMultipleMatchesFound();
9054 else if (NumMatches == 1) {
9055 Fn = Resolver.getMatchingFunctionDecl();
9056 assert(Fn);
9057 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009058 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009059 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009060 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009061 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009062
9063 if (pHadMultipleCandidates)
9064 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009065 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009066}
9067
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009068/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009069/// resolve that overloaded function expression down to a single function.
9070///
9071/// This routine can only resolve template-ids that refer to a single function
9072/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009073/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009074/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009075FunctionDecl *
9076Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9077 bool Complain,
9078 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009079 // C++ [over.over]p1:
9080 // [...] [Note: any redundant set of parentheses surrounding the
9081 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009082 // C++ [over.over]p1:
9083 // [...] The overloaded function name can be preceded by the &
9084 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009085
Douglas Gregor4b52e252009-12-21 23:17:24 +00009086 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009087 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009088 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009089
9090 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009091 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009092
Douglas Gregor4b52e252009-12-21 23:17:24 +00009093 // Look through all of the overloaded functions, searching for one
9094 // whose type matches exactly.
9095 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009096 for (UnresolvedSetIterator I = ovl->decls_begin(),
9097 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009098 // C++0x [temp.arg.explicit]p3:
9099 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009100 // where deduction is not done, if a template argument list is
9101 // specified and it, along with any default template arguments,
9102 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009103 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009104 FunctionTemplateDecl *FunctionTemplate
9105 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009106
Douglas Gregor4b52e252009-12-21 23:17:24 +00009107 // C++ [over.over]p2:
9108 // If the name is a function template, template argument deduction is
9109 // done (14.8.2.2), and if the argument deduction succeeds, the
9110 // resulting template argument list is used to generate a single
9111 // function template specialization, which is added to the set of
9112 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009113 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009114 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009115 if (TemplateDeductionResult Result
9116 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9117 Specialization, Info)) {
9118 // FIXME: make a note of the failed deduction for diagnostics.
9119 (void)Result;
9120 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009121 }
9122
John McCall864c0412011-04-26 20:42:42 +00009123 assert(Specialization && "no specialization and no error?");
9124
Douglas Gregor4b52e252009-12-21 23:17:24 +00009125 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009126 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009127 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009128 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9129 << ovl->getName();
9130 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009131 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009132 return 0;
John McCall864c0412011-04-26 20:42:42 +00009133 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009134
John McCall864c0412011-04-26 20:42:42 +00009135 Matched = Specialization;
9136 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009138
Douglas Gregor4b52e252009-12-21 23:17:24 +00009139 return Matched;
9140}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009141
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009142
9143
9144
John McCall6dbba4f2011-10-11 23:14:30 +00009145// Resolve and fix an overloaded expression that can be resolved
9146// because it identifies a single function template specialization.
9147//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009148// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009149//
9150// Return true if it was logically possible to so resolve the
9151// expression, regardless of whether or not it succeeded. Always
9152// returns true if 'complain' is set.
9153bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9154 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9155 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009156 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009157 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009158 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009159
John McCall6dbba4f2011-10-11 23:14:30 +00009160 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009161
John McCall864c0412011-04-26 20:42:42 +00009162 DeclAccessPair found;
9163 ExprResult SingleFunctionExpression;
9164 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9165 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009166 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009167 SrcExpr = ExprError();
9168 return true;
9169 }
John McCall864c0412011-04-26 20:42:42 +00009170
9171 // It is only correct to resolve to an instance method if we're
9172 // resolving a form that's permitted to be a pointer to member.
9173 // Otherwise we'll end up making a bound member expression, which
9174 // is illegal in all the contexts we resolve like this.
9175 if (!ovl.HasFormOfMemberPointer &&
9176 isa<CXXMethodDecl>(fn) &&
9177 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009178 if (!complain) return false;
9179
9180 Diag(ovl.Expression->getExprLoc(),
9181 diag::err_bound_member_function)
9182 << 0 << ovl.Expression->getSourceRange();
9183
9184 // TODO: I believe we only end up here if there's a mix of
9185 // static and non-static candidates (otherwise the expression
9186 // would have 'bound member' type, not 'overload' type).
9187 // Ideally we would note which candidate was chosen and why
9188 // the static candidates were rejected.
9189 SrcExpr = ExprError();
9190 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009191 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009192
John McCall864c0412011-04-26 20:42:42 +00009193 // Fix the expresion to refer to 'fn'.
9194 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009195 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009196
9197 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009198 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009199 SingleFunctionExpression =
9200 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009201 if (SingleFunctionExpression.isInvalid()) {
9202 SrcExpr = ExprError();
9203 return true;
9204 }
9205 }
John McCall864c0412011-04-26 20:42:42 +00009206 }
9207
9208 if (!SingleFunctionExpression.isUsable()) {
9209 if (complain) {
9210 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9211 << ovl.Expression->getName()
9212 << DestTypeForComplaining
9213 << OpRangeForComplaining
9214 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009215 NoteAllOverloadCandidates(SrcExpr.get());
9216
9217 SrcExpr = ExprError();
9218 return true;
9219 }
9220
9221 return false;
John McCall864c0412011-04-26 20:42:42 +00009222 }
9223
John McCall6dbba4f2011-10-11 23:14:30 +00009224 SrcExpr = SingleFunctionExpression;
9225 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009226}
9227
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009228/// \brief Add a single candidate to the overload set.
9229static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009230 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009231 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009232 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009233 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009234 bool PartialOverloading,
9235 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009236 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009237 if (isa<UsingShadowDecl>(Callee))
9238 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9239
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009240 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009241 if (ExplicitTemplateArgs) {
9242 assert(!KnownValid && "Explicit template arguments?");
9243 return;
9244 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009245 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9246 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009247 return;
John McCallba135432009-11-21 08:51:07 +00009248 }
9249
9250 if (FunctionTemplateDecl *FuncTemplate
9251 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009252 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009253 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009254 return;
9255 }
9256
Richard Smith2ced0442011-06-26 22:19:54 +00009257 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009258}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009259
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009260/// \brief Add the overload candidates named by callee and/or found by argument
9261/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009262void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009263 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009264 OverloadCandidateSet &CandidateSet,
9265 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009266
9267#ifndef NDEBUG
9268 // Verify that ArgumentDependentLookup is consistent with the rules
9269 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009270 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009271 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9272 // and let Y be the lookup set produced by argument dependent
9273 // lookup (defined as follows). If X contains
9274 //
9275 // -- a declaration of a class member, or
9276 //
9277 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009278 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009279 //
9280 // -- a declaration that is neither a function or a function
9281 // template
9282 //
9283 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009284
John McCall3b4294e2009-12-16 12:17:52 +00009285 if (ULE->requiresADL()) {
9286 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9287 E = ULE->decls_end(); I != E; ++I) {
9288 assert(!(*I)->getDeclContext()->isRecord());
9289 assert(isa<UsingShadowDecl>(*I) ||
9290 !(*I)->getDeclContext()->isFunctionOrMethod());
9291 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009292 }
9293 }
9294#endif
9295
John McCall3b4294e2009-12-16 12:17:52 +00009296 // It would be nice to avoid this copy.
9297 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009298 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009299 if (ULE->hasExplicitTemplateArgs()) {
9300 ULE->copyTemplateArgumentsInto(TABuffer);
9301 ExplicitTemplateArgs = &TABuffer;
9302 }
9303
9304 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9305 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009306 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9307 CandidateSet, PartialOverloading,
9308 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009309
John McCall3b4294e2009-12-16 12:17:52 +00009310 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009311 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009312 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009313 Args, ExplicitTemplateArgs,
9314 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009315 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009316}
John McCall578b69b2009-12-16 08:11:27 +00009317
Richard Smithf50e88a2011-06-05 22:42:48 +00009318/// Attempt to recover from an ill-formed use of a non-dependent name in a
9319/// template, where the non-dependent name was declared after the template
9320/// was defined. This is common in code written for a compilers which do not
9321/// correctly implement two-stage name lookup.
9322///
9323/// Returns true if a viable candidate was found and a diagnostic was issued.
9324static bool
9325DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9326 const CXXScopeSpec &SS, LookupResult &R,
9327 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009328 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009329 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9330 return false;
9331
9332 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009333 if (DC->isTransparentContext())
9334 continue;
9335
Richard Smithf50e88a2011-06-05 22:42:48 +00009336 SemaRef.LookupQualifiedName(R, DC);
9337
9338 if (!R.empty()) {
9339 R.suppressDiagnostics();
9340
9341 if (isa<CXXRecordDecl>(DC)) {
9342 // Don't diagnose names we find in classes; we get much better
9343 // diagnostics for these from DiagnoseEmptyLookup.
9344 R.clear();
9345 return false;
9346 }
9347
9348 OverloadCandidateSet Candidates(FnLoc);
9349 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9350 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009351 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009352 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009353
9354 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009355 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009356 // No viable functions. Don't bother the user with notes for functions
9357 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009358 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009359 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009360 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009361
9362 // Find the namespaces where ADL would have looked, and suggest
9363 // declaring the function there instead.
9364 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9365 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00009366 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009367 AssociatedNamespaces,
9368 AssociatedClasses);
9369 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009370 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009371 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009372 for (Sema::AssociatedNamespaceSet::iterator
9373 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009374 end = AssociatedNamespaces.end(); it != end; ++it) {
9375 if (!Std->Encloses(*it))
9376 SuggestedNamespaces.insert(*it);
9377 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009378 } else {
9379 // Lacking the 'std::' namespace, use all of the associated namespaces.
9380 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009381 }
9382
9383 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9384 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009385 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009386 SemaRef.Diag(Best->Function->getLocation(),
9387 diag::note_not_found_by_two_phase_lookup)
9388 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009389 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009390 SemaRef.Diag(Best->Function->getLocation(),
9391 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009392 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009393 } else {
9394 // FIXME: It would be useful to list the associated namespaces here,
9395 // but the diagnostics infrastructure doesn't provide a way to produce
9396 // a localized representation of a list of items.
9397 SemaRef.Diag(Best->Function->getLocation(),
9398 diag::note_not_found_by_two_phase_lookup)
9399 << R.getLookupName() << 2;
9400 }
9401
9402 // Try to recover by calling this function.
9403 return true;
9404 }
9405
9406 R.clear();
9407 }
9408
9409 return false;
9410}
9411
9412/// Attempt to recover from ill-formed use of a non-dependent operator in a
9413/// template, where the non-dependent operator was declared after the template
9414/// was defined.
9415///
9416/// Returns true if a viable candidate was found and a diagnostic was issued.
9417static bool
9418DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9419 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009420 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009421 DeclarationName OpName =
9422 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9423 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9424 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009425 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009426}
9427
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009428namespace {
9429// Callback to limit the allowed keywords and to only accept typo corrections
9430// that are keywords or whose decls refer to functions (or template functions)
9431// that accept the given number of arguments.
9432class RecoveryCallCCC : public CorrectionCandidateCallback {
9433 public:
9434 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9435 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009436 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009437 WantRemainingKeywords = false;
9438 }
9439
9440 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9441 if (!candidate.getCorrectionDecl())
9442 return candidate.isKeyword();
9443
9444 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9445 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9446 FunctionDecl *FD = 0;
9447 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9448 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9449 FD = FTD->getTemplatedDecl();
9450 if (!HasExplicitTemplateArgs && !FD) {
9451 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9452 // If the Decl is neither a function nor a template function,
9453 // determine if it is a pointer or reference to a function. If so,
9454 // check against the number of arguments expected for the pointee.
9455 QualType ValType = cast<ValueDecl>(ND)->getType();
9456 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9457 ValType = ValType->getPointeeType();
9458 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9459 if (FPT->getNumArgs() == NumArgs)
9460 return true;
9461 }
9462 }
9463 if (FD && FD->getNumParams() >= NumArgs &&
9464 FD->getMinRequiredArguments() <= NumArgs)
9465 return true;
9466 }
9467 return false;
9468 }
9469
9470 private:
9471 unsigned NumArgs;
9472 bool HasExplicitTemplateArgs;
9473};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009474
9475// Callback that effectively disabled typo correction
9476class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9477 public:
9478 NoTypoCorrectionCCC() {
9479 WantTypeSpecifiers = false;
9480 WantExpressionKeywords = false;
9481 WantCXXNamedCasts = false;
9482 WantRemainingKeywords = false;
9483 }
9484
9485 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9486 return false;
9487 }
9488};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009489}
9490
John McCall578b69b2009-12-16 08:11:27 +00009491/// Attempts to recover from a call where no functions were found.
9492///
9493/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009494static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009495BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009496 UnresolvedLookupExpr *ULE,
9497 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009498 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009499 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009500 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009501
9502 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009503 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009504 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009505
John McCall3b4294e2009-12-16 12:17:52 +00009506 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009507 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009508 if (ULE->hasExplicitTemplateArgs()) {
9509 ULE->copyTemplateArgumentsInto(TABuffer);
9510 ExplicitTemplateArgs = &TABuffer;
9511 }
9512
John McCall578b69b2009-12-16 08:11:27 +00009513 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9514 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009515 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009516 NoTypoCorrectionCCC RejectAll;
9517 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9518 (CorrectionCandidateCallback*)&Validator :
9519 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009520 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009521 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009522 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009523 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009524 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009525 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009526
John McCall3b4294e2009-12-16 12:17:52 +00009527 assert(!R.empty() && "lookup results empty despite recovery");
9528
9529 // Build an implicit member call if appropriate. Just drop the
9530 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009531 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009532 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009533 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9534 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009535 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009536 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009537 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009538 else
9539 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9540
9541 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009542 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009543
9544 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009545 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009546 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009547 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009548 MultiExprArg(Args.data(), Args.size()),
9549 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009550}
Douglas Gregord7a95972010-06-08 17:35:15 +00009551
Douglas Gregorf6b89692008-11-26 05:54:23 +00009552/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009553/// (which eventually refers to the declaration Func) and the call
9554/// arguments Args/NumArgs, attempt to resolve the function call down
9555/// to a specific function. If overload resolution succeeds, returns
9556/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009557/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009558/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009559ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009560Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009561 SourceLocation LParenLoc,
9562 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009563 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009564 Expr *ExecConfig,
9565 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009566#ifndef NDEBUG
9567 if (ULE->requiresADL()) {
9568 // To do ADL, we must have found an unqualified name.
9569 assert(!ULE->getQualifier() && "qualified name with ADL");
9570
9571 // We don't perform ADL for implicit declarations of builtins.
9572 // Verify that this was correctly set up.
9573 FunctionDecl *F;
9574 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9575 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9576 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009577 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009578
John McCall3b4294e2009-12-16 12:17:52 +00009579 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009580 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009581 } else
9582 assert(!ULE->isStdAssociatedNamespace() &&
9583 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009584#endif
9585
John McCall5acb0c92011-10-17 18:40:02 +00009586 UnbridgedCastsSet UnbridgedCasts;
9587 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9588 return ExprError();
9589
John McCall5769d612010-02-08 23:07:23 +00009590 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009591
John McCall3b4294e2009-12-16 12:17:52 +00009592 // Add the functions denoted by the callee to the set of candidate
9593 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009594 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9595 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009596
9597 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009598 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9599 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009600 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009601 // In Microsoft mode, if we are inside a template class member function then
9602 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009603 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009604 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009605 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009606 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009607 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9608 Context.DependentTy, VK_RValue,
9609 RParenLoc);
9610 CE->setTypeDependent(true);
9611 return Owned(CE);
9612 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009613 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9614 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009615 RParenLoc, /*EmptyLookup=*/true,
9616 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009617 }
John McCall578b69b2009-12-16 08:11:27 +00009618
John McCall5acb0c92011-10-17 18:40:02 +00009619 UnbridgedCasts.restore();
9620
Douglas Gregorf6b89692008-11-26 05:54:23 +00009621 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009622 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009623 case OR_Success: {
9624 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009625 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009626 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009627 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009628 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009629 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9630 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009631 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009632
Richard Smithf50e88a2011-06-05 22:42:48 +00009633 case OR_No_Viable_Function: {
9634 // Try to recover by looking for viable functions which the user might
9635 // have meant to call.
9636 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009637 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9638 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009639 /*EmptyLookup=*/false,
9640 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009641 if (!Recovery.isInvalid())
9642 return Recovery;
9643
Daniel Dunbar96a00142012-03-09 18:35:03 +00009644 Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009645 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009646 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009647 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9648 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009649 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009650 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009651
9652 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +00009653 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009654 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009655 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9656 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009657 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009658
9659 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009660 {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009661 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009662 << Best->Function->isDeleted()
9663 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009664 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009665 << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009666 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9667 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009668
9669 // We emitted an error for the unvailable/deleted function call but keep
9670 // the call in the AST.
9671 FunctionDecl *FDecl = Best->Function;
9672 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9673 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9674 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009675 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009676 }
9677
Douglas Gregorff331c12010-07-25 18:17:45 +00009678 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009679 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009680}
9681
John McCall6e266892010-01-26 03:27:55 +00009682static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009683 return Functions.size() > 1 ||
9684 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9685}
9686
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009687/// \brief Create a unary operation that may resolve to an overloaded
9688/// operator.
9689///
9690/// \param OpLoc The location of the operator itself (e.g., '*').
9691///
9692/// \param OpcIn The UnaryOperator::Opcode that describes this
9693/// operator.
9694///
9695/// \param Functions The set of non-member functions that will be
9696/// considered by overload resolution. The caller needs to build this
9697/// set based on the context using, e.g.,
9698/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9699/// set should not contain any member functions; those will be added
9700/// by CreateOverloadedUnaryOp().
9701///
9702/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009703ExprResult
John McCall6e266892010-01-26 03:27:55 +00009704Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9705 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009706 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009707 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009708
9709 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9710 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9711 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009712 // TODO: provide better source location info.
9713 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009714
John McCall5acb0c92011-10-17 18:40:02 +00009715 if (checkPlaceholderForOverload(*this, Input))
9716 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009717
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009718 Expr *Args[2] = { Input, 0 };
9719 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009720
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009721 // For post-increment and post-decrement, add the implicit '0' as
9722 // the second argument, so that we know this is a post-increment or
9723 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009724 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009725 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009726 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9727 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009728 NumArgs = 2;
9729 }
9730
9731 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009732 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009733 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009734 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009735 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009736 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009737 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009738
John McCallc373d482010-01-27 01:50:18 +00009739 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009740 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009741 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009742 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009743 /*ADL*/ true, IsOverloaded(Fns),
9744 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009745 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009746 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009747 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009748 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009749 OpLoc));
9750 }
9751
9752 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009753 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009754
9755 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009756 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9757 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009758
9759 // Add operator candidates that are member functions.
9760 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9761
John McCall6e266892010-01-26 03:27:55 +00009762 // Add candidates from ADL.
9763 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009764 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009765 /*ExplicitTemplateArgs*/ 0,
9766 CandidateSet);
9767
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009768 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009769 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009770
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009771 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9772
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009773 // Perform overload resolution.
9774 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009775 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009776 case OR_Success: {
9777 // We found a built-in operator or an overloaded operator.
9778 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009779
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009780 if (FnDecl) {
9781 // We matched an overloaded operator. Build a call to that
9782 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009783
Eli Friedman5f2987c2012-02-02 03:46:19 +00009784 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009785
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009786 // Convert the arguments.
9787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009788 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009789
John Wiegley429bb272011-04-08 18:41:53 +00009790 ExprResult InputRes =
9791 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9792 Best->FoundDecl, Method);
9793 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009794 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009795 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009796 } else {
9797 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009798 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009799 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009800 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009801 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009802 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009803 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009804 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009805 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009806 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009807 }
9808
John McCallb697e082010-05-06 18:15:07 +00009809 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9810
John McCallf89e55a2010-11-18 06:31:45 +00009811 // Determine the result type.
9812 QualType ResultTy = FnDecl->getResultType();
9813 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9814 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009815
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009816 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009817 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009818 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009819 if (FnExpr.isInvalid())
9820 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009821
Eli Friedman4c3b8962009-11-18 03:58:17 +00009822 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009823 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009824 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009825 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009826
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009827 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009828 FnDecl))
9829 return ExprError();
9830
John McCall9ae2f072010-08-23 23:25:46 +00009831 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009832 } else {
9833 // We matched a built-in operator. Convert the arguments, then
9834 // break out so that we will build the appropriate built-in
9835 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009836 ExprResult InputRes =
9837 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9838 Best->Conversions[0], AA_Passing);
9839 if (InputRes.isInvalid())
9840 return ExprError();
9841 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009842 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009843 }
John Wiegley429bb272011-04-08 18:41:53 +00009844 }
9845
9846 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009847 // This is an erroneous use of an operator which can be overloaded by
9848 // a non-member function. Check for non-member operators which were
9849 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009850 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9851 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +00009852 // FIXME: Recover by calling the found function.
9853 return ExprError();
9854
John Wiegley429bb272011-04-08 18:41:53 +00009855 // No viable function; fall through to handling this as a
9856 // built-in operator, which will produce an error message for us.
9857 break;
9858
9859 case OR_Ambiguous:
9860 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9861 << UnaryOperator::getOpcodeStr(Opc)
9862 << Input->getType()
9863 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009864 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9865 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +00009866 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9867 return ExprError();
9868
9869 case OR_Deleted:
9870 Diag(OpLoc, diag::err_ovl_deleted_oper)
9871 << Best->Function->isDeleted()
9872 << UnaryOperator::getOpcodeStr(Opc)
9873 << getDeletedOrUnavailableSuffix(Best->Function)
9874 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009875 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9876 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +00009877 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009878 return ExprError();
9879 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009880
9881 // Either we found no viable overloaded operator or we matched a
9882 // built-in operator. In either case, fall through to trying to
9883 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009884 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009885}
9886
Douglas Gregor063daf62009-03-13 18:40:31 +00009887/// \brief Create a binary operation that may resolve to an overloaded
9888/// operator.
9889///
9890/// \param OpLoc The location of the operator itself (e.g., '+').
9891///
9892/// \param OpcIn The BinaryOperator::Opcode that describes this
9893/// operator.
9894///
9895/// \param Functions The set of non-member functions that will be
9896/// considered by overload resolution. The caller needs to build this
9897/// set based on the context using, e.g.,
9898/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9899/// set should not contain any member functions; those will be added
9900/// by CreateOverloadedBinOp().
9901///
9902/// \param LHS Left-hand argument.
9903/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009904ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009905Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009906 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009907 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009908 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009909 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009910 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009911
9912 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9913 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9914 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9915
9916 // If either side is type-dependent, create an appropriate dependent
9917 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009918 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009919 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009920 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009921 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009922 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009923 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009924 Context.DependentTy,
9925 VK_RValue, OK_Ordinary,
9926 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009927
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009928 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9929 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009930 VK_LValue,
9931 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009932 Context.DependentTy,
9933 Context.DependentTy,
9934 OpLoc));
9935 }
John McCall6e266892010-01-26 03:27:55 +00009936
9937 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009938 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009939 // TODO: provide better source location info in DNLoc component.
9940 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009941 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009942 = UnresolvedLookupExpr::Create(Context, NamingClass,
9943 NestedNameSpecifierLoc(), OpNameInfo,
9944 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009945 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009946 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009947 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009948 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009949 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009950 OpLoc));
9951 }
9952
John McCall5acb0c92011-10-17 18:40:02 +00009953 // Always do placeholder-like conversions on the RHS.
9954 if (checkPlaceholderForOverload(*this, Args[1]))
9955 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009956
John McCall3c3b7f92011-10-25 17:37:35 +00009957 // Do placeholder-like conversion on the LHS; note that we should
9958 // not get here with a PseudoObject LHS.
9959 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009960 if (checkPlaceholderForOverload(*this, Args[0]))
9961 return ExprError();
9962
Sebastian Redl275c2b42009-11-18 23:10:33 +00009963 // If this is the assignment operator, we only perform overload resolution
9964 // if the left-hand side is a class or enumeration type. This is actually
9965 // a hack. The standard requires that we do overload resolution between the
9966 // various built-in candidates, but as DR507 points out, this can lead to
9967 // problems. So we do it this way, which pretty much follows what GCC does.
9968 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009969 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009970 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009971
John McCall0e800c92010-12-04 08:14:53 +00009972 // If this is the .* operator, which is not overloadable, just
9973 // create a built-in binary operator.
9974 if (Opc == BO_PtrMemD)
9975 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9976
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009977 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009978 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009979
9980 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009981 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009982
9983 // Add operator candidates that are member functions.
9984 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9985
John McCall6e266892010-01-26 03:27:55 +00009986 // Add candidates from ADL.
9987 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009988 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +00009989 /*ExplicitTemplateArgs*/ 0,
9990 CandidateSet);
9991
Douglas Gregor063daf62009-03-13 18:40:31 +00009992 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009993 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009994
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009995 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9996
Douglas Gregor063daf62009-03-13 18:40:31 +00009997 // Perform overload resolution.
9998 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009999 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010000 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010001 // We found a built-in operator or an overloaded operator.
10002 FunctionDecl *FnDecl = Best->Function;
10003
10004 if (FnDecl) {
10005 // We matched an overloaded operator. Build a call to that
10006 // operator.
10007
Eli Friedman5f2987c2012-02-02 03:46:19 +000010008 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010009
Douglas Gregor063daf62009-03-13 18:40:31 +000010010 // Convert the arguments.
10011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010012 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010013 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010014
Chandler Carruth6df868e2010-12-12 08:17:55 +000010015 ExprResult Arg1 =
10016 PerformCopyInitialization(
10017 InitializedEntity::InitializeParameter(Context,
10018 FnDecl->getParamDecl(0)),
10019 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010020 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010021 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010022
John Wiegley429bb272011-04-08 18:41:53 +000010023 ExprResult Arg0 =
10024 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10025 Best->FoundDecl, Method);
10026 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010027 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010028 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010029 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010030 } else {
10031 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010032 ExprResult Arg0 = PerformCopyInitialization(
10033 InitializedEntity::InitializeParameter(Context,
10034 FnDecl->getParamDecl(0)),
10035 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010036 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010037 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010038
Chandler Carruth6df868e2010-12-12 08:17:55 +000010039 ExprResult Arg1 =
10040 PerformCopyInitialization(
10041 InitializedEntity::InitializeParameter(Context,
10042 FnDecl->getParamDecl(1)),
10043 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010044 if (Arg1.isInvalid())
10045 return ExprError();
10046 Args[0] = LHS = Arg0.takeAs<Expr>();
10047 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010048 }
10049
John McCallb697e082010-05-06 18:15:07 +000010050 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10051
John McCallf89e55a2010-11-18 06:31:45 +000010052 // Determine the result type.
10053 QualType ResultTy = FnDecl->getResultType();
10054 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10055 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010056
10057 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010058 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10059 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010060 if (FnExpr.isInvalid())
10061 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010062
John McCall9ae2f072010-08-23 23:25:46 +000010063 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010064 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010065 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010066
10067 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010068 FnDecl))
10069 return ExprError();
10070
John McCall9ae2f072010-08-23 23:25:46 +000010071 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010072 } else {
10073 // We matched a built-in operator. Convert the arguments, then
10074 // break out so that we will build the appropriate built-in
10075 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010076 ExprResult ArgsRes0 =
10077 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10078 Best->Conversions[0], AA_Passing);
10079 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010080 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010081 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010082
John Wiegley429bb272011-04-08 18:41:53 +000010083 ExprResult ArgsRes1 =
10084 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10085 Best->Conversions[1], AA_Passing);
10086 if (ArgsRes1.isInvalid())
10087 return ExprError();
10088 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010089 break;
10090 }
10091 }
10092
Douglas Gregor33074752009-09-30 21:46:01 +000010093 case OR_No_Viable_Function: {
10094 // C++ [over.match.oper]p9:
10095 // If the operator is the operator , [...] and there are no
10096 // viable functions, then the operator is assumed to be the
10097 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010098 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010099 break;
10100
Chandler Carruth6df868e2010-12-12 08:17:55 +000010101 // For class as left operand for assignment or compound assigment
10102 // operator do not fall through to handling in built-in, but report that
10103 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010104 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010105 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010106 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010107 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10108 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010109 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010110 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010111 // This is an erroneous use of an operator which can be overloaded by
10112 // a non-member function. Check for non-member operators which were
10113 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010114 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010115 // FIXME: Recover by calling the found function.
10116 return ExprError();
10117
Douglas Gregor33074752009-09-30 21:46:01 +000010118 // No viable function; try to create a built-in operation, which will
10119 // produce an error. Then, show the non-viable candidates.
10120 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010122 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010123 "C++ binary operator overloading is missing candidates!");
10124 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010125 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010126 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010127 return move(Result);
10128 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010129
10130 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010131 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010132 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010133 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010134 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010135 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010136 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010137 return ExprError();
10138
10139 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010140 if (isImplicitlyDeleted(Best->Function)) {
10141 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10142 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10143 << getSpecialMember(Method)
10144 << BinaryOperator::getOpcodeStr(Opc)
10145 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010146
10147 if (getSpecialMember(Method) != CXXInvalid) {
10148 // The user probably meant to call this special member. Just
10149 // explain why it's deleted.
10150 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010151 return ExprError();
10152 }
10153 } else {
10154 Diag(OpLoc, diag::err_ovl_deleted_oper)
10155 << Best->Function->isDeleted()
10156 << BinaryOperator::getOpcodeStr(Opc)
10157 << getDeletedOrUnavailableSuffix(Best->Function)
10158 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10159 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010160 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010161 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010162 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010163 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010164
Douglas Gregor33074752009-09-30 21:46:01 +000010165 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010166 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010167}
10168
John McCall60d7b3a2010-08-24 06:29:42 +000010169ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010170Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10171 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010172 Expr *Base, Expr *Idx) {
10173 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010174 DeclarationName OpName =
10175 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10176
10177 // If either side is type-dependent, create an appropriate dependent
10178 // expression.
10179 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10180
John McCallc373d482010-01-27 01:50:18 +000010181 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010182 // CHECKME: no 'operator' keyword?
10183 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10184 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010185 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010186 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010187 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010188 /*ADL*/ true, /*Overloaded*/ false,
10189 UnresolvedSetIterator(),
10190 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010191 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010192
Sebastian Redlf322ed62009-10-29 20:17:01 +000010193 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10194 Args, 2,
10195 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010196 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010197 RLoc));
10198 }
10199
John McCall5acb0c92011-10-17 18:40:02 +000010200 // Handle placeholders on both operands.
10201 if (checkPlaceholderForOverload(*this, Args[0]))
10202 return ExprError();
10203 if (checkPlaceholderForOverload(*this, Args[1]))
10204 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010205
Sebastian Redlf322ed62009-10-29 20:17:01 +000010206 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010207 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010208
10209 // Subscript can only be overloaded as a member function.
10210
10211 // Add operator candidates that are member functions.
10212 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10213
10214 // Add builtin operator candidates.
10215 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10216
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010217 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10218
Sebastian Redlf322ed62009-10-29 20:17:01 +000010219 // Perform overload resolution.
10220 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010221 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010222 case OR_Success: {
10223 // We found a built-in operator or an overloaded operator.
10224 FunctionDecl *FnDecl = Best->Function;
10225
10226 if (FnDecl) {
10227 // We matched an overloaded operator. Build a call to that
10228 // operator.
10229
Eli Friedman5f2987c2012-02-02 03:46:19 +000010230 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010231
John McCall9aa472c2010-03-19 07:35:19 +000010232 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010233 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010234
Sebastian Redlf322ed62009-10-29 20:17:01 +000010235 // Convert the arguments.
10236 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010237 ExprResult Arg0 =
10238 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10239 Best->FoundDecl, Method);
10240 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010241 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010242 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010243
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010244 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010245 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010246 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010247 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010248 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010249 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010250 Owned(Args[1]));
10251 if (InputInit.isInvalid())
10252 return ExprError();
10253
10254 Args[1] = InputInit.takeAs<Expr>();
10255
Sebastian Redlf322ed62009-10-29 20:17:01 +000010256 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010257 QualType ResultTy = FnDecl->getResultType();
10258 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10259 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010260
10261 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010262 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10263 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010264 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10265 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010266 OpLocInfo.getLoc(),
10267 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010268 if (FnExpr.isInvalid())
10269 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010270
John McCall9ae2f072010-08-23 23:25:46 +000010271 CXXOperatorCallExpr *TheCall =
10272 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010273 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010274 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010275
John McCall9ae2f072010-08-23 23:25:46 +000010276 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010277 FnDecl))
10278 return ExprError();
10279
John McCall9ae2f072010-08-23 23:25:46 +000010280 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010281 } else {
10282 // We matched a built-in operator. Convert the arguments, then
10283 // break out so that we will build the appropriate built-in
10284 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010285 ExprResult ArgsRes0 =
10286 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10287 Best->Conversions[0], AA_Passing);
10288 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010289 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010290 Args[0] = ArgsRes0.take();
10291
10292 ExprResult ArgsRes1 =
10293 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10294 Best->Conversions[1], AA_Passing);
10295 if (ArgsRes1.isInvalid())
10296 return ExprError();
10297 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010298
10299 break;
10300 }
10301 }
10302
10303 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010304 if (CandidateSet.empty())
10305 Diag(LLoc, diag::err_ovl_no_oper)
10306 << Args[0]->getType() << /*subscript*/ 0
10307 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10308 else
10309 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10310 << Args[0]->getType()
10311 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010312 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010313 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010314 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010315 }
10316
10317 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010318 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010319 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010320 << Args[0]->getType() << Args[1]->getType()
10321 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010322 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010323 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010324 return ExprError();
10325
10326 case OR_Deleted:
10327 Diag(LLoc, diag::err_ovl_deleted_oper)
10328 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010329 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010330 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010331 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010332 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010333 return ExprError();
10334 }
10335
10336 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010337 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010338}
10339
Douglas Gregor88a35142008-12-22 05:46:06 +000010340/// BuildCallToMemberFunction - Build a call to a member
10341/// function. MemExpr is the expression that refers to the member
10342/// function (and includes the object parameter), Args/NumArgs are the
10343/// arguments to the function call (not including the object
10344/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010345/// expression refers to a non-static member function or an overloaded
10346/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010347ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010348Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10349 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010350 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010351 assert(MemExprE->getType() == Context.BoundMemberTy ||
10352 MemExprE->getType() == Context.OverloadTy);
10353
Douglas Gregor88a35142008-12-22 05:46:06 +000010354 // Dig out the member expression. This holds both the object
10355 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010356 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010357
John McCall864c0412011-04-26 20:42:42 +000010358 // Determine whether this is a call to a pointer-to-member function.
10359 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10360 assert(op->getType() == Context.BoundMemberTy);
10361 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10362
10363 QualType fnType =
10364 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10365
10366 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10367 QualType resultType = proto->getCallResultType(Context);
10368 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10369
10370 // Check that the object type isn't more qualified than the
10371 // member function we're calling.
10372 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10373
10374 QualType objectType = op->getLHS()->getType();
10375 if (op->getOpcode() == BO_PtrMemI)
10376 objectType = objectType->castAs<PointerType>()->getPointeeType();
10377 Qualifiers objectQuals = objectType.getQualifiers();
10378
10379 Qualifiers difference = objectQuals - funcQuals;
10380 difference.removeObjCGCAttr();
10381 difference.removeAddressSpace();
10382 if (difference) {
10383 std::string qualsString = difference.getAsString();
10384 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10385 << fnType.getUnqualifiedType()
10386 << qualsString
10387 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10388 }
10389
10390 CXXMemberCallExpr *call
10391 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10392 resultType, valueKind, RParenLoc);
10393
10394 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010395 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010396 call, 0))
10397 return ExprError();
10398
10399 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10400 return ExprError();
10401
10402 return MaybeBindToTemporary(call);
10403 }
10404
John McCall5acb0c92011-10-17 18:40:02 +000010405 UnbridgedCastsSet UnbridgedCasts;
10406 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10407 return ExprError();
10408
John McCall129e2df2009-11-30 22:42:35 +000010409 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010410 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010411 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010412 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010413 if (isa<MemberExpr>(NakedMemExpr)) {
10414 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010415 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010416 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010417 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010418 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010419 } else {
10420 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010421 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010422
John McCall701c89e2009-12-03 04:06:58 +000010423 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010424 Expr::Classification ObjectClassification
10425 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10426 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010427
Douglas Gregor88a35142008-12-22 05:46:06 +000010428 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010429 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010430
John McCallaa81e162009-12-01 22:10:20 +000010431 // FIXME: avoid copy.
10432 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10433 if (UnresExpr->hasExplicitTemplateArgs()) {
10434 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10435 TemplateArgs = &TemplateArgsBuffer;
10436 }
10437
John McCall129e2df2009-11-30 22:42:35 +000010438 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10439 E = UnresExpr->decls_end(); I != E; ++I) {
10440
John McCall701c89e2009-12-03 04:06:58 +000010441 NamedDecl *Func = *I;
10442 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10443 if (isa<UsingShadowDecl>(Func))
10444 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10445
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010446
Francois Pichetdbee3412011-01-18 05:04:39 +000010447 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010448 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010449 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10450 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010451 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010452 // If explicit template arguments were provided, we can't call a
10453 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010454 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010455 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010456
John McCall9aa472c2010-03-19 07:35:19 +000010457 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010458 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010459 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010460 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010461 } else {
John McCall129e2df2009-11-30 22:42:35 +000010462 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010463 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010464 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010465 llvm::makeArrayRef(Args, NumArgs),
10466 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010467 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010468 }
Douglas Gregordec06662009-08-21 18:42:58 +000010469 }
Mike Stump1eb44332009-09-09 15:08:12 +000010470
John McCall129e2df2009-11-30 22:42:35 +000010471 DeclarationName DeclName = UnresExpr->getMemberName();
10472
John McCall5acb0c92011-10-17 18:40:02 +000010473 UnbridgedCasts.restore();
10474
Douglas Gregor88a35142008-12-22 05:46:06 +000010475 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010476 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010477 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010478 case OR_Success:
10479 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010480 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010481 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010482 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010483 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010484 break;
10485
10486 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010487 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010488 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010489 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010490 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10491 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010492 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010493 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010494
10495 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010496 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010497 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010498 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10499 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010500 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010501 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010502
10503 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010504 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010505 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010506 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010507 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010508 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10510 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010511 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010512 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010513 }
10514
John McCall6bb80172010-03-30 21:47:33 +000010515 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010516
John McCallaa81e162009-12-01 22:10:20 +000010517 // If overload resolution picked a static member, build a
10518 // non-member call based on that function.
10519 if (Method->isStatic()) {
10520 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10521 Args, NumArgs, RParenLoc);
10522 }
10523
John McCall129e2df2009-11-30 22:42:35 +000010524 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010525 }
10526
John McCallf89e55a2010-11-18 06:31:45 +000010527 QualType ResultType = Method->getResultType();
10528 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10529 ResultType = ResultType.getNonLValueExprType(Context);
10530
Douglas Gregor88a35142008-12-22 05:46:06 +000010531 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010532 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010533 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010534 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010535
Anders Carlssoneed3e692009-10-10 00:06:20 +000010536 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010537 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010538 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010539 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010540
Douglas Gregor88a35142008-12-22 05:46:06 +000010541 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010542 // We only need to do this if there was actually an overload; otherwise
10543 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010544 if (!Method->isStatic()) {
10545 ExprResult ObjectArg =
10546 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10547 FoundDecl, Method);
10548 if (ObjectArg.isInvalid())
10549 return ExprError();
10550 MemExpr->setBase(ObjectArg.take());
10551 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010552
10553 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010554 const FunctionProtoType *Proto =
10555 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010556 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010557 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010558 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010559
Eli Friedmane61eb042012-02-18 04:48:30 +000010560 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10561
John McCall9ae2f072010-08-23 23:25:46 +000010562 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +000010563 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010564
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010565 if ((isa<CXXConstructorDecl>(CurContext) ||
10566 isa<CXXDestructorDecl>(CurContext)) &&
10567 TheCall->getMethodDecl()->isPure()) {
10568 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10569
Chandler Carruthae198062011-06-27 08:31:58 +000010570 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010571 Diag(MemExpr->getLocStart(),
10572 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10573 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10574 << MD->getParent()->getDeclName();
10575
10576 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010577 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010578 }
John McCall9ae2f072010-08-23 23:25:46 +000010579 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010580}
10581
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010582/// BuildCallToObjectOfClassType - Build a call to an object of class
10583/// type (C++ [over.call.object]), which can end up invoking an
10584/// overloaded function call operator (@c operator()) or performing a
10585/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010586ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010587Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010588 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010589 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010590 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010591 if (checkPlaceholderForOverload(*this, Obj))
10592 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010593 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010594
10595 UnbridgedCastsSet UnbridgedCasts;
10596 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10597 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010598
John Wiegley429bb272011-04-08 18:41:53 +000010599 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10600 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010601
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010602 // C++ [over.call.object]p1:
10603 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010604 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010605 // candidate functions includes at least the function call
10606 // operators of T. The function call operators of T are obtained by
10607 // ordinary lookup of the name operator() in the context of
10608 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010609 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010610 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010611
John Wiegley429bb272011-04-08 18:41:53 +000010612 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +000010613 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010614 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010615 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010616
John McCalla24dc2e2009-11-17 02:14:36 +000010617 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10618 LookupQualifiedName(R, Record->getDecl());
10619 R.suppressDiagnostics();
10620
Douglas Gregor593564b2009-11-15 07:48:03 +000010621 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010622 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010623 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10624 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010625 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010626 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010627
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010628 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010629 // In addition, for each (non-explicit in C++0x) conversion function
10630 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010631 //
10632 // operator conversion-type-id () cv-qualifier;
10633 //
10634 // where cv-qualifier is the same cv-qualification as, or a
10635 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010636 // denotes the type "pointer to function of (P1,...,Pn) returning
10637 // R", or the type "reference to pointer to function of
10638 // (P1,...,Pn) returning R", or the type "reference to function
10639 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010640 // is also considered as a candidate function. Similarly,
10641 // surrogate call functions are added to the set of candidate
10642 // functions for each conversion function declared in an
10643 // accessible base class provided the function is not hidden
10644 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010645 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010646 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010647 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010648 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010649 NamedDecl *D = *I;
10650 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10651 if (isa<UsingShadowDecl>(D))
10652 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010653
Douglas Gregor4a27d702009-10-21 06:18:39 +000010654 // Skip over templated conversion functions; they aren't
10655 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010656 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010657 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010658
John McCall701c89e2009-12-03 04:06:58 +000010659 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010660 if (!Conv->isExplicit()) {
10661 // Strip the reference type (if any) and then the pointer type (if
10662 // any) to get down to what might be a function type.
10663 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10664 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10665 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010666
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010667 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10668 {
10669 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010670 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10671 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010672 }
10673 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010674 }
Mike Stump1eb44332009-09-09 15:08:12 +000010675
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010676 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10677
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010678 // Perform overload resolution.
10679 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010680 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010681 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010682 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010683 // Overload resolution succeeded; we'll build the appropriate call
10684 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010685 break;
10686
10687 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010688 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010689 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010690 << Object.get()->getType() << /*call*/ 1
10691 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010692 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010693 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010694 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010695 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010696 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10697 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010698 break;
10699
10700 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010701 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010702 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010703 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010704 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10705 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010706 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010707
10708 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010709 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010710 diag::err_ovl_deleted_object_call)
10711 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010712 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010713 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010714 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010715 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10716 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010717 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010718 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010719
Douglas Gregorff331c12010-07-25 18:17:45 +000010720 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010721 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010722
John McCall5acb0c92011-10-17 18:40:02 +000010723 UnbridgedCasts.restore();
10724
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010725 if (Best->Function == 0) {
10726 // Since there is no function declaration, this is one of the
10727 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010728 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010729 = cast<CXXConversionDecl>(
10730 Best->Conversions[0].UserDefined.ConversionFunction);
10731
John Wiegley429bb272011-04-08 18:41:53 +000010732 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010733 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010734
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010735 // We selected one of the surrogate functions that converts the
10736 // object parameter to a function pointer. Perform the conversion
10737 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010738
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010739 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010740 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010741 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10742 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010743 if (Call.isInvalid())
10744 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010745 // Record usage of conversion in an implicit cast.
10746 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10747 CK_UserDefinedConversion,
10748 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010749
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010750 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010751 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010752 }
10753
Eli Friedman5f2987c2012-02-02 03:46:19 +000010754 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010755 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010756 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010757
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010758 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10759 // that calls this method, using Object for the implicit object
10760 // parameter and passing along the remaining arguments.
10761 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010762 const FunctionProtoType *Proto =
10763 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010764
10765 unsigned NumArgsInProto = Proto->getNumArgs();
10766 unsigned NumArgsToCheck = NumArgs;
10767
10768 // Build the full argument list for the method call (the
10769 // implicit object parameter is placed at the beginning of the
10770 // list).
10771 Expr **MethodArgs;
10772 if (NumArgs < NumArgsInProto) {
10773 NumArgsToCheck = NumArgsInProto;
10774 MethodArgs = new Expr*[NumArgsInProto + 1];
10775 } else {
10776 MethodArgs = new Expr*[NumArgs + 1];
10777 }
John Wiegley429bb272011-04-08 18:41:53 +000010778 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010779 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10780 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010781
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010782 DeclarationNameInfo OpLocInfo(
10783 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10784 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010785 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010786 HadMultipleCandidates,
10787 OpLocInfo.getLoc(),
10788 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010789 if (NewFn.isInvalid())
10790 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010791
10792 // Once we've built TheCall, all of the expressions are properly
10793 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010794 QualType ResultTy = Method->getResultType();
10795 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10796 ResultTy = ResultTy.getNonLValueExprType(Context);
10797
John McCall9ae2f072010-08-23 23:25:46 +000010798 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010799 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010800 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010801 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010802 delete [] MethodArgs;
10803
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010804 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010805 Method))
10806 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010807
Douglas Gregor518fda12009-01-13 05:10:00 +000010808 // We may have default arguments. If so, we need to allocate more
10809 // slots in the call for them.
10810 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010811 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010812 else if (NumArgs > NumArgsInProto)
10813 NumArgsToCheck = NumArgsInProto;
10814
Chris Lattner312531a2009-04-12 08:11:20 +000010815 bool IsError = false;
10816
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010817 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010818 ExprResult ObjRes =
10819 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10820 Best->FoundDecl, Method);
10821 if (ObjRes.isInvalid())
10822 IsError = true;
10823 else
10824 Object = move(ObjRes);
10825 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010826
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010827 // Check the argument types.
10828 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010829 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010830 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010831 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010832
Douglas Gregor518fda12009-01-13 05:10:00 +000010833 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010834
John McCall60d7b3a2010-08-24 06:29:42 +000010835 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010836 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010837 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010838 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010839 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010840
Anders Carlsson3faa4862010-01-29 18:43:53 +000010841 IsError |= InputInit.isInvalid();
10842 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010843 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010844 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010845 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10846 if (DefArg.isInvalid()) {
10847 IsError = true;
10848 break;
10849 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010850
Douglas Gregord47c47d2009-11-09 19:27:57 +000010851 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010852 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010853
10854 TheCall->setArg(i + 1, Arg);
10855 }
10856
10857 // If this is a variadic call, handle args passed through "...".
10858 if (Proto->isVariadic()) {
10859 // Promote the arguments (C99 6.5.2.2p7).
10860 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010861 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10862 IsError |= Arg.isInvalid();
10863 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010864 }
10865 }
10866
Chris Lattner312531a2009-04-12 08:11:20 +000010867 if (IsError) return true;
10868
Eli Friedmane61eb042012-02-18 04:48:30 +000010869 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10870
John McCall9ae2f072010-08-23 23:25:46 +000010871 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010872 return true;
10873
John McCall182f7092010-08-24 06:09:16 +000010874 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010875}
10876
Douglas Gregor8ba10742008-11-20 16:27:02 +000010877/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010878/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010879/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010880ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010881Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010882 assert(Base->getType()->isRecordType() &&
10883 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010884
John McCall5acb0c92011-10-17 18:40:02 +000010885 if (checkPlaceholderForOverload(*this, Base))
10886 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010887
John McCall5769d612010-02-08 23:07:23 +000010888 SourceLocation Loc = Base->getExprLoc();
10889
Douglas Gregor8ba10742008-11-20 16:27:02 +000010890 // C++ [over.ref]p1:
10891 //
10892 // [...] An expression x->m is interpreted as (x.operator->())->m
10893 // for a class object x of type T if T::operator->() exists and if
10894 // the operator is selected as the best match function by the
10895 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010896 DeclarationName OpName =
10897 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010898 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010899 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010900
John McCall5769d612010-02-08 23:07:23 +000010901 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +000010902 PDiag(diag::err_typecheck_incomplete_tag)
10903 << Base->getSourceRange()))
10904 return ExprError();
10905
John McCalla24dc2e2009-11-17 02:14:36 +000010906 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10907 LookupQualifiedName(R, BaseRecord->getDecl());
10908 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010909
10910 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010911 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010912 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10913 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010914 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010915
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010916 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10917
Douglas Gregor8ba10742008-11-20 16:27:02 +000010918 // Perform overload resolution.
10919 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010920 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010921 case OR_Success:
10922 // Overload resolution succeeded; we'll build the call below.
10923 break;
10924
10925 case OR_No_Viable_Function:
10926 if (CandidateSet.empty())
10927 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010928 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010929 else
10930 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010931 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010933 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010934
10935 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010936 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10937 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010938 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010939 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010940
10941 case OR_Deleted:
10942 Diag(OpLoc, diag::err_ovl_deleted_oper)
10943 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010944 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010945 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010946 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010947 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010948 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010949 }
10950
Eli Friedman5f2987c2012-02-02 03:46:19 +000010951 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010952 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010953 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010954
Douglas Gregor8ba10742008-11-20 16:27:02 +000010955 // Convert the object parameter.
10956 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010957 ExprResult BaseResult =
10958 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10959 Best->FoundDecl, Method);
10960 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010961 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010962 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010963
Douglas Gregor8ba10742008-11-20 16:27:02 +000010964 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010965 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010966 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010967 if (FnExpr.isInvalid())
10968 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010969
John McCallf89e55a2010-11-18 06:31:45 +000010970 QualType ResultTy = Method->getResultType();
10971 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10972 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010973 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010974 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010975 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010976
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010977 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010978 Method))
10979 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010980
10981 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010982}
10983
Richard Smith36f5cfe2012-03-09 08:00:36 +000010984/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10985/// a literal operator described by the provided lookup results.
10986ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10987 DeclarationNameInfo &SuffixInfo,
10988 ArrayRef<Expr*> Args,
10989 SourceLocation LitEndLoc,
10990 TemplateArgumentListInfo *TemplateArgs) {
10991 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000010992
Richard Smith36f5cfe2012-03-09 08:00:36 +000010993 OverloadCandidateSet CandidateSet(UDSuffixLoc);
10994 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10995 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000010996
Richard Smith36f5cfe2012-03-09 08:00:36 +000010997 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10998
Richard Smith36f5cfe2012-03-09 08:00:36 +000010999 // Perform overload resolution. This will usually be trivial, but might need
11000 // to perform substitutions for a literal operator template.
11001 OverloadCandidateSet::iterator Best;
11002 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11003 case OR_Success:
11004 case OR_Deleted:
11005 break;
11006
11007 case OR_No_Viable_Function:
11008 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11009 << R.getLookupName();
11010 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11011 return ExprError();
11012
11013 case OR_Ambiguous:
11014 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11015 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11016 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011017 }
11018
Richard Smith36f5cfe2012-03-09 08:00:36 +000011019 FunctionDecl *FD = Best->Function;
11020 MarkFunctionReferenced(UDSuffixLoc, FD);
11021 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011022
Richard Smith36f5cfe2012-03-09 08:00:36 +000011023 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11024 SuffixInfo.getLoc(),
11025 SuffixInfo.getInfo());
11026 if (Fn.isInvalid())
11027 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011028
11029 // Check the argument types. This should almost always be a no-op, except
11030 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011031 Expr *ConvArgs[2];
11032 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11033 ExprResult InputInit = PerformCopyInitialization(
11034 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11035 SourceLocation(), Args[ArgIdx]);
11036 if (InputInit.isInvalid())
11037 return true;
11038 ConvArgs[ArgIdx] = InputInit.take();
11039 }
11040
Richard Smith9fcce652012-03-07 08:35:16 +000011041 QualType ResultTy = FD->getResultType();
11042 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11043 ResultTy = ResultTy.getNonLValueExprType(Context);
11044
Richard Smith9fcce652012-03-07 08:35:16 +000011045 UserDefinedLiteral *UDL =
11046 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11047 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11048
11049 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11050 return ExprError();
11051
11052 if (CheckFunctionCall(FD, UDL))
11053 return ExprError();
11054
11055 return MaybeBindToTemporary(UDL);
11056}
11057
Douglas Gregor904eed32008-11-10 20:40:00 +000011058/// FixOverloadedFunctionReference - E is an expression that refers to
11059/// a C++ overloaded function (possibly with some parentheses and
11060/// perhaps a '&' around it). We have resolved the overloaded function
11061/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011062/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011063Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011064 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011065 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011066 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11067 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011068 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011069 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011070
Douglas Gregor699ee522009-11-20 19:42:02 +000011071 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011072 }
11073
Douglas Gregor699ee522009-11-20 19:42:02 +000011074 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011075 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11076 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011077 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011078 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011079 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011080 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011081 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011082 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011083
11084 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011085 ICE->getCastKind(),
11086 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011087 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011088 }
11089
Douglas Gregor699ee522009-11-20 19:42:02 +000011090 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011091 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011092 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011093 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11094 if (Method->isStatic()) {
11095 // Do nothing: static member functions aren't any different
11096 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011097 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011098 // Fix the sub expression, which really has to be an
11099 // UnresolvedLookupExpr holding an overloaded member function
11100 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011101 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11102 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011103 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011104 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011105
John McCallba135432009-11-21 08:51:07 +000011106 assert(isa<DeclRefExpr>(SubExpr)
11107 && "fixed to something other than a decl ref");
11108 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11109 && "fixed to a member ref with no nested name qualifier");
11110
11111 // We have taken the address of a pointer to member
11112 // function. Perform the computation here so that we get the
11113 // appropriate pointer to member type.
11114 QualType ClassType
11115 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11116 QualType MemPtrType
11117 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11118
John McCallf89e55a2010-11-18 06:31:45 +000011119 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11120 VK_RValue, OK_Ordinary,
11121 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011122 }
11123 }
John McCall6bb80172010-03-30 21:47:33 +000011124 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11125 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011126 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011127 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011128
John McCall2de56d12010-08-25 11:45:40 +000011129 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011130 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011131 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011132 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011133 }
John McCallba135432009-11-21 08:51:07 +000011134
11135 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011136 // FIXME: avoid copy.
11137 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011138 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011139 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11140 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011141 }
11142
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011143 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11144 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011145 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011146 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011147 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011148 ULE->getNameLoc(),
11149 Fn->getType(),
11150 VK_LValue,
11151 Found.getDecl(),
11152 TemplateArgs);
11153 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11154 return DRE;
John McCallba135432009-11-21 08:51:07 +000011155 }
11156
John McCall129e2df2009-11-30 22:42:35 +000011157 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011158 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011159 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11160 if (MemExpr->hasExplicitTemplateArgs()) {
11161 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11162 TemplateArgs = &TemplateArgsBuffer;
11163 }
John McCalld5532b62009-11-23 01:53:49 +000011164
John McCallaa81e162009-12-01 22:10:20 +000011165 Expr *Base;
11166
John McCallf89e55a2010-11-18 06:31:45 +000011167 // If we're filling in a static method where we used to have an
11168 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011169 if (MemExpr->isImplicitAccess()) {
11170 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011171 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11172 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011173 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011174 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011175 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011176 MemExpr->getMemberLoc(),
11177 Fn->getType(),
11178 VK_LValue,
11179 Found.getDecl(),
11180 TemplateArgs);
11181 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11182 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011183 } else {
11184 SourceLocation Loc = MemExpr->getMemberLoc();
11185 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011186 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011187 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011188 Base = new (Context) CXXThisExpr(Loc,
11189 MemExpr->getBaseType(),
11190 /*isImplicit=*/true);
11191 }
John McCallaa81e162009-12-01 22:10:20 +000011192 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011193 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011194
John McCallf5307512011-04-27 00:36:17 +000011195 ExprValueKind valueKind;
11196 QualType type;
11197 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11198 valueKind = VK_LValue;
11199 type = Fn->getType();
11200 } else {
11201 valueKind = VK_RValue;
11202 type = Context.BoundMemberTy;
11203 }
11204
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011205 MemberExpr *ME = MemberExpr::Create(Context, Base,
11206 MemExpr->isArrow(),
11207 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011208 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011209 Fn,
11210 Found,
11211 MemExpr->getMemberNameInfo(),
11212 TemplateArgs,
11213 type, valueKind, OK_Ordinary);
11214 ME->setHadMultipleCandidates(true);
11215 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011216 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011217
John McCall3fa5cae2010-10-26 07:05:15 +000011218 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011219}
11220
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011221ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011222 DeclAccessPair Found,
11223 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011224 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011225}
11226
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011227} // end namespace clang