blob: a3a963f356f76d10fa3cdb0c875a1dc8c737b842 [file] [log] [blame]
Douglas Gregor5251f1b2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000044 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000052}
53
John McCall5c32be02010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-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 McCall5c32be02010-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 Gregor5251f1b2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-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 Lopescfca1f02009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor26bee0b2008-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 Gregore489a7d2010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000202}
203
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-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 Gregor3edc4d52010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-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 Gregor5c407d92008-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 Stump11289f42009-09-09 15:08:12 +0000242bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-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 Gregor5d3d3fa2011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Richard Smith66e05fe2012-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 Smith5614ca72012-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 Smith66e05fe2012-01-18 05:21:49 +0000293NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000294StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
295 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000296 APValue &ConstantValue,
297 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000298 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-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 Smith5614ca72012-03-23 23:55:39 +0000331 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-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 Smith5614ca72012-03-23 23:55:39 +0000361 if (ConvertStatus & llvm::APFloat::opOverflow) {
362 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000363 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000364 }
Richard Smith66e05fe2012-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 Smith5614ca72012-03-23 23:55:39 +0000409 if (ConvertedValue != InitializerValue) {
410 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000411 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000412 }
Richard Smith66e05fe2012-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 Gregor5251f1b2008-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 Lattner0e62c1c2011-07-23 10:55:15 +0000430 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000431 bool PrintedSomething = false;
432 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000434 PrintedSomething = true;
435 }
436
437 if (Second != ICK_Identity) {
438 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000440 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000441 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000442
443 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000444 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000445 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000447 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (Third != ICK_Identity) {
454 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << "No conversions required";
Douglas Gregor5251f1b2008-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 Lattner0e62c1c2011-07-23 10:55:15 +0000469 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 if (Before.First || Before.Second || Before.Third) {
471 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000474 if (ConversionFunction)
475 OS << '\'' << *ConversionFunction << '\'';
476 else
477 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000478 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor5251f1b2008-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 Lattner0e62c1c2011-07-23 10:55:15 +0000487 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 switch (ConversionKind) {
489 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 Standard.DebugPrint();
492 break;
493 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000494 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 UserDefined.DebugPrint();
496 break;
497 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 break;
John McCall0d1da222010-01-12 00:44:57 +0000500 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000502 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000503 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000504 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 break;
506 }
507
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000508 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509}
510
John McCall0d1da222010-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 Gregor3626a5c2010-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 Takumif9cbcc42011-01-27 07:10:08 +0000535
Douglas Gregor3626a5c2010-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 Gregor90cf2c92010-05-08 20:18:54 +0000539static MakeDeductionFailureInfo(ASTContext &Context,
540 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000541 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000548 case Sema::TDK_TooManyArguments:
549 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000550 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000552 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000553 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 Result.Data = Info.Param.getOpaqueValue();
555 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000557 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000558 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-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 Gregor3626a5c2010-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 Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000569 Result.Data = Info.take();
570 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 return Result;
578}
John McCall0d1da222010-01-12 00:44:57 +0000579
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000585 case Sema::TDK_TooManyArguments:
586 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000587 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000591 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000592 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000593 Data = 0;
594 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000595
596 case Sema::TDK_SubstitutionFailure:
597 // FIXME: Destroy the template arugment list?
598 Data = 0;
599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor461761d2010-05-08 18:20:53 +0000601 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_FailedOverloadResolution:
604 break;
605 }
606}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
608TemplateParameter
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000613 case Sema::TDK_TooManyArguments:
614 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000615 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000618 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000619 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000621
622 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000623 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_FailedOverloadResolution:
629 break;
630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 return TemplateParameter();
633}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregord09efd42010-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 McCall42d7d192010-08-05 09:05:08 +0000645 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 return 0;
647
648 case Sema::TDK_SubstitutionFailure:
649 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregord09efd42010-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 Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000665 case Sema::TDK_TooManyArguments:
666 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000667 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000668 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 return 0;
670
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000671 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000672 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000673 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000674
Douglas Gregor461761d2010-05-08 18:20:53 +0000675 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000676 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 case Sema::TDK_FailedOverloadResolution:
678 break;
679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000681 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682}
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000690 case Sema::TDK_TooManyArguments:
691 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000692 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000693 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 return 0;
695
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000697 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000698 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
699
Douglas Gregor461761d2010-05-08 18:20:53 +0000700 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000701 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 case Sema::TDK_FailedOverloadResolution:
703 break;
704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 return 0;
707}
708
709void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-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 Kramer0b9c5092012-01-14 19:31:39 +0000713 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000714 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 Functions.clear();
716}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717
John McCall4124c492011-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 McCall4124c492011-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 Gregor5251f1b2008-10-21 16:13:35 +0000789// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-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 McCalldaa3d6b2009-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 Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000805// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000806//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000811//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000816// signature), IsOverload returns false and MatchedDecl will be set to
817// point to the FunctionDecl for #2.
John McCalle9cccd82010-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 McCalldaa3d6b2009-12-09 03:35:25 +0000823Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000824Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
825 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000826 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000827 I != E; ++I) {
John McCalle9cccd82010-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 McCall3d988d92009-12-02 08:47:38 +0000849 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-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 McCalldaa3d6b2009-12-09 03:35:25 +0000856 Match = *I;
857 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858 }
John McCall3d988d92009-12-02 08:47:38 +0000859 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-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 McCalldaa3d6b2009-12-09 03:35:25 +0000866 Match = *I;
867 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000868 }
John McCalla8987a2942010-11-10 03:01:53 +0000869 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-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 McCalla8987a2942010-11-10 03:01:53 +0000873 } else if (isa<TagDecl>(OldD)) {
874 // We can always overload with tags by hiding them.
John McCall84d87672009-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 McCall1f82f242009-11-18 22:49:29 +0000880 // (C++ 13p1):
881 // Only function declarations can be overloaded; object and type
882 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000883 Match = *I;
884 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000885 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886 }
John McCall1f82f242009-11-18 22:49:29 +0000887
John McCalldaa3d6b2009-12-09 03:35:25 +0000888 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000889}
890
John McCalle9cccd82010-06-16 08:42:20 +0000891bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
892 bool UseUsingDeclRules) {
John McCall8246e352010-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 McCall1f82f242009-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 McCall424cec92011-01-19 06:33:43 +0000921 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
922 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-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 Jahanian5e5998f2010-05-03 21:06:18 +0000930 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-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 McCalle9cccd82010-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 McCall1f82f242009-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 Gregorb2f8aa92011-01-26 17:47:49 +0000953 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-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 Gregorb2f8aa92011-01-26 17:47:49 +0000964 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-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 Takumif9cbcc42011-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 Gregorc83f98652011-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 Takumif9cbcc42011-01-27 07:10:08 +0000980
John McCall1f82f242009-11-18 22:49:29 +0000981 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
John McCall1f82f242009-11-18 22:49:29 +0000984 // The signatures match; this is not an overload.
985 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986}
987
Argyrios Kyrtzidisab72b672011-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 Redl6901c0d2011-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 Gregor8e1cf602008-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 Gregor5251f1b2008-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 Gregor2fe98832008-11-03 19:09:14 +00001095///
1096/// If @p SuppressUserConversions, then user-defined conversions are
1097/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001098/// If @p AllowExplicit, then explicit user-defined conversions are
1099/// permitted.
John McCall31168b02011-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 McCall5c32be02010-08-24 20:38:10 +00001104static ImplicitConversionSequence
1105TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1106 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001108 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001109 bool CStyle,
1110 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001112 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001113 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001114 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001115 return ICS;
1116 }
1117
David Blaikiebbafb8a2012-03-11 07:00:24 +00001118 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001119 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001120 return ICS;
1121 }
1122
Douglas Gregor836a7e82010-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 McCall5c32be02010-08-24 20:38:10 +00001132 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1133 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001134 ICS.setStandard();
1135 ICS.Standard.setAsIdentityConversion();
1136 ICS.Standard.setFromType(FromType);
1137 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
Douglas Gregor5ab11652010-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 Takumif9cbcc42011-01-27 07:10:08 +00001144
Douglas Gregor5ab11652010-04-17 22:01:05 +00001145 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001146 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001147 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148
Douglas Gregor836a7e82010-08-11 02:15:33 +00001149 return ICS;
1150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001152 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1153 AllowExplicit, InOverloadResolution, CStyle,
1154 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155}
1156
John McCall31168b02011-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 McCall5c32be02010-08-24 20:38:10 +00001168}
1169
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001170/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001171/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-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 Wiegley01296292011-04-08 18:41:53 +00001175ExprResult
1176Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001177 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001178 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001179 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001180}
1181
John Wiegley01296292011-04-08 18:41:53 +00001182ExprResult
1183Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001184 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001185 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001186 if (checkPlaceholderForOverload(*this, From))
1187 return ExprError();
1188
John McCall31168b02011-06-15 23:02:42 +00001189 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1190 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001192 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001193
John McCall5c32be02010-08-24 20:38:10 +00001194 ICS = clang::TryImplicitConversion(*this, From, ToType,
1195 /*SuppressUserConversions=*/false,
1196 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001197 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001198 /*CStyle=*/false,
1199 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001200 return PerformImplicitConversion(From, ToType, ICS, Action);
1201}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202
1203/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001204/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001205bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1206 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001207 if (Context.hasSameUnqualifiedType(FromType, ToType))
1208 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209
John McCall991eb4b2010-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 Gregor40cb9ad2009-12-09 00:47:37 +00001232
John McCall991eb4b2010-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 Gregor40cb9ad2009-12-09 00:47:37 +00001248 return true;
1249}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250
Douglas Gregor46188682010-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 Takumif9cbcc42011-01-27 07:10:08 +00001256static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1257 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-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 Takumif9cbcc42011-01-27 07:10:08 +00001273
Douglas Gregor46188682010-05-18 22:42:18 +00001274 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001275 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001276 ICK = ICK_Vector_Splat;
1277 return true;
1278 }
1279 }
Douglas Gregor59e8b3b2010-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 Blaikiebbafb8a2012-03-11 07:00:24 +00001287 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001288 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001289 ICK = ICK_Vector_Conversion;
1290 return true;
1291 }
Douglas Gregor46188682010-05-18 22:42:18 +00001292 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001293
Douglas Gregor46188682010-05-18 22:42:18 +00001294 return false;
1295}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001297static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1298 bool InOverloadResolution,
1299 StandardConversionSequence &SCS,
1300 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001301
Douglas Gregor26bee0b2008-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 McCall5c32be02010-08-24 20:38:10 +00001310static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1311 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001312 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001313 bool CStyle,
1314 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001315 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001316
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001317 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001318 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001319 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001320 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001321 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001322 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001323
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001324 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001325 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001326 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001327 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001328 return false;
1329
Mike Stump11289f42009-09-09 15:08:12 +00001330 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001331 }
1332
Douglas Gregor5251f1b2008-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 McCall5c32be02010-08-24 20:38:10 +00001337 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001338 DeclAccessPair AccessPair;
1339 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001341 AccessPair)) {
Douglas Gregor980fb162010-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 Gregorb491ed32011-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 Carruth53e61b02011-06-18 01:19:03 +00001352 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-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 Gregor980fb162010-04-29 18:24:40 +00001357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Chandler Carruthffce2452011-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 Carruth7750f762011-03-29 18:38:10 +00001373 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1374 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1375 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001376 "Non-address-of operator for overloaded function expression");
1377 FromType = S.Context.getPointerType(FromType);
1378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379
Douglas Gregor980fb162010-04-29 18:24:40 +00001380 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001381 assert(S.Context.hasSameType(
1382 FromType,
1383 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001384 } else {
1385 return false;
1386 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001387 }
John McCall154a2fd2011-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 McCall086a4642010-11-24 05:12:34 +00001392 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001393 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001394 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001395 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001396
Douglas Gregorc79862f2012-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 Gregor5251f1b2008-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 Gregor4e5cbdc2009-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 Gregor26bee0b2008-10-31 16:23:19 +00001407 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001408 } else if (FromType->isArrayType()) {
1409 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001410 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-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 McCall5c32be02010-08-24 20:38:10 +00001415 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001416
John McCall5c32be02010-08-24 20:38:10 +00001417 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001418 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001419 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-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 Gregor26bee0b2008-10-31 16:23:19 +00001425 SCS.Second = ICK_Identity;
1426 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001427 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001428 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001429 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001430 }
John McCall086a4642010-11-24 05:12:34 +00001431 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001432 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001433 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-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 McCall5c32be02010-08-24 20:38:10 +00001438 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001439 } else {
1440 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001441 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001443 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-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 Gregor4e5cbdc2009-02-11 23:02:49 +00001449 // For overloading in C, this can also be a "compatible-type"
1450 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001451 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001452 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001453 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001454 // The unqualified versions of the types are the same: there's no
1455 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001456 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001457 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001458 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001459 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001460 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001461 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001462 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001463 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001464 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001465 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001466 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001467 SCS.Second = ICK_Complex_Promotion;
1468 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-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 Gregor0bf31402010-10-08 23:50:27 +00001478 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001479 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001480 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001481 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001482 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001483 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001484 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001485 SCS.Second = ICK_Complex_Conversion;
1486 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001487 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1488 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-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 Gregor49b4d732010-06-22 23:07:26 +00001492 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001493 // Floating point conversions (C++ 4.8).
1494 SCS.Second = ICK_Floating_Conversion;
1495 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001497 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001498 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001499 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001500 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001501 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001502 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001503 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-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 McCall5c32be02010-08-24 20:38:10 +00001508 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1509 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001510 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001511 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001512 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001513 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001514 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001515 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001516 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001517 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001518 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001519 SCS.Second = SecondICK;
1520 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001521 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001522 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001523 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001524 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001525 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001526 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001527 // Treat a conversion that strips "noreturn" as an identity conversion.
1528 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-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 Gregorf9e36cc2012-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 Gregorc79862f2012-04-12 17:51:55 +00001537 // appropriately.
1538 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001539 } else {
1540 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001541 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001542 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001543 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001544
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001545 QualType CanonFrom;
1546 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001548 bool ObjCLifetimeConversion;
1549 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1550 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001551 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001552 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001554 CanonFrom = S.Context.getCanonicalType(FromType);
1555 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 } else {
1557 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 SCS.Third = ICK_Identity;
1559
Mike Stump11289f42009-09-09 15:08:12 +00001560 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-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 McCall5c32be02010-08-24 20:38:10 +00001564 CanonFrom = S.Context.getCanonicalType(FromType);
1565 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001567 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001568 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001569 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1570 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001571 FromType = ToType;
1572 CanonFrom = CanonTo;
1573 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001575 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-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 Gregor8e1cf602008-10-29 00:13:59 +00001579 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001580 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001582 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001583}
Fariborz Jahanian16f92ce2011-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 McCall31168b02011-06-15 23:02:42 +00001601 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1602 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001603 ToType = it->getType();
1604 return true;
1605 }
1606 }
1607 return false;
1608}
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +00001614bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001615 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001616 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001617 if (!To) {
1618 return false;
1619 }
Douglas Gregor5251f1b2008-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 Gregora71cc152010-02-02 20:10:50 +00001626 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1627 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +00001632 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001633 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001634 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001635 }
1636
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001637 return To->getKind() == BuiltinType::UInt;
1638 }
1639
NAKAMURA Takumif9cbcc42011-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 Gregorcd1d0b42010-10-21 18:04:08 +00001646 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001647 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001648 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-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 Gregorcd1d0b42010-10-21 18:04:08 +00001651 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-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 Gregorcd1d0b42010-10-21 18:04:08 +00001658 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001659 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001660 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001661 return Context.hasSameUnqualifiedType(ToType,
1662 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001663 }
John McCall56774992009-12-09 09:09:27 +00001664
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001665 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-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 Gregorcd1d0b42010-10-21 18:04:08 +00001669 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001670 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001671 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001673 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001675 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676 // Determine whether the type we're converting from is signed or
1677 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001678 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +00001683 QualType PromoteTypes[6] = {
1684 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001685 Context.LongTy, Context.UnsignedLongTy ,
1686 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001688 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001689 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1690 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001691 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-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 Gregor1b8fe5b72009-11-16 21:35:15 +00001696 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-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 Stump87c57ac2009-05-16 07:39:55 +00001708 // FIXME: We should delay checking of bit-fields until we actually perform the
1709 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001710 using llvm::APSInt;
1711 if (From)
1712 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001713 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001714 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001715 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1716 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1717 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001718
Douglas Gregor2eedc3a2008-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 Stump11289f42009-09-09 15:08:12 +00001724
Douglas Gregor2eedc3a2008-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 Stump11289f42009-09-09 15:08:12 +00001730
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001731 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001732 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001733 }
Mike Stump11289f42009-09-09 15:08:12 +00001734
Douglas Gregor5251f1b2008-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 Redl72b8aef2008-10-31 14:43:28 +00001737 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001738 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001739 }
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +00001747bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001748 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1749 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-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 Gregor5251f1b2008-10-21 16:13:35 +00001752 if (FromBuiltin->getKind() == BuiltinType::Float &&
1753 ToBuiltin->getKind() == BuiltinType::Double)
1754 return true;
1755
Douglas Gregor78ca74d2009-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 Blaikiebbafb8a2012-03-11 07:00:24 +00001759 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001760 (FromBuiltin->getKind() == BuiltinType::Float ||
1761 FromBuiltin->getKind() == BuiltinType::Double) &&
1762 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1763 return true;
Anton Korobeynikovf0c267e2011-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 Gregor78ca74d2009-02-12 00:15:05 +00001769 }
1770
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771 return false;
1772}
1773
Douglas Gregor78ca74d2009-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 Gregor67525022009-02-12 00:26:06 +00001778/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001779bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001780 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001781 if (!FromComplex)
1782 return false;
1783
John McCall9dd450b2009-09-21 23:43:11 +00001784 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001785 if (!ToComplex)
1786 return false;
1787
1788 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001789 ToComplex->getElementType()) ||
1790 IsIntegralPromotion(0, FromComplex->getElementType(),
1791 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001792}
1793
Douglas Gregor237f96c2008-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 McCall31168b02011-06-15 23:02:42 +00001799///
Mike Stump11289f42009-09-09 15:08:12 +00001800static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001801BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001802 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001803 ASTContext &Context,
1804 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001805 assert((FromPtr->getTypeClass() == Type::Pointer ||
1806 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1807 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001808
John McCall31168b02011-06-15 23:02:42 +00001809 /// Conversions to 'id' subsume cv-qualifier conversions.
1810 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001811 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001812
1813 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001814 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001815 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001816 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001817
John McCall31168b02011-06-15 23:02:42 +00001818 if (StripObjCLifetime)
1819 Quals.removeObjCLifetime();
1820
Mike Stump11289f42009-09-09 15:08:12 +00001821 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001822 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001823 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001824 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001825 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001826
1827 // Build a pointer to ToPointee. It has the right qualifiers
1828 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001829 if (isa<ObjCObjectPointerType>(ToType))
1830 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001831 return Context.getPointerType(ToPointee);
1832 }
1833
1834 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001835 QualType QualifiedCanonToPointee
1836 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001838 if (isa<ObjCObjectPointerType>(ToType))
1839 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1840 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001841}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842
Mike Stump11289f42009-09-09 15:08:12 +00001843static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-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 Gregorb90df602010-06-16 00:17:44 +00001849 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001850 return !InOverloadResolution;
1851
Douglas Gregor56751b52009-09-25 04:25:58 +00001852 return Expr->isNullPointerConstant(Context,
1853 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1854 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001855}
Mike Stump11289f42009-09-09 15:08:12 +00001856
Douglas Gregor5251f1b2008-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 Gregor231d1c62008-11-27 00:15:41 +00001863///
Douglas Gregora29dc052008-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 Gregor47d3f272008-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 Gregor5251f1b2008-10-21 16:13:35 +00001873bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001874 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001875 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001876 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001877 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001878 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1879 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001880 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001881
Mike Stump11289f42009-09-09 15:08:12 +00001882 // Conversion from a null pointer constant to any Objective-C pointer type.
1883 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001884 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001885 ConvertedType = ToType;
1886 return true;
1887 }
1888
Douglas Gregor231d1c62008-11-27 00:15:41 +00001889 // Blocks: Block pointers can be converted to void*.
1890 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001891 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-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 Stump11289f42009-09-09 15:08:12 +00001897 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001898 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001899 ConvertedType = ToType;
1900 return true;
1901 }
1902
Sebastian Redl576fd422009-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 Stump11289f42009-09-09 15:08:12 +00001905 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001906 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001907 ConvertedType = ToType;
1908 return true;
1909 }
1910
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001911 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-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 Carlsson759b7892009-08-28 15:55:56 +00001916 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001917 ConvertedType = ToType;
1918 return true;
1919 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001920
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001922 // , including objective-c pointers.
1923 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001924 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001925 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001926 ConvertedType = BuildSimilarlyQualifiedPointerType(
1927 FromType->getAs<ObjCObjectPointerType>(),
1928 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001929 ToType, Context);
1930 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001931 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001932 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001933 if (!FromTypePtr)
1934 return false;
1935
1936 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001937
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-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 Gregor5251f1b2008-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 Friedmana170cd62010-08-05 02:49:48 +00001946 if (FromPointeeType->isIncompleteOrObjectType() &&
1947 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001948 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001949 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001950 ToType, Context,
1951 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001952 return true;
1953 }
1954
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001955 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001956 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001957 ToPointeeType->isVoidType()) {
1958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1959 ToPointeeType,
1960 ToType, Context);
1961 return true;
1962 }
1963
Douglas Gregor4e5cbdc2009-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 Blaikiebbafb8a2012-03-11 07:00:24 +00001966 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001969 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001970 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001971 return true;
1972 }
1973
Douglas Gregor5c407d92008-10-23 00:40:37 +00001974 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001975 //
Douglas Gregor5c407d92008-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 Gregor39c16d42008-10-24 04:54:22 +00001985 // Note that we do not check for ambiguity or inaccessibility
1986 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001987 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001989 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001990 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001991 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001992 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001993 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001994 ToType, Context);
1995 return true;
1996 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001997
Fariborz Jahanianbc2ee932011-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 Gregora119f102008-12-19 19:13:09 +00002006 return false;
2007}
Douglas Gregoraec25842011-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 Gregora119f102008-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 Stump11289f42009-09-09 15:08:12 +00002026bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002027 QualType& ConvertedType,
2028 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002029 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002030 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031
Douglas Gregoraec25842011-04-26 23:16:46 +00002032 // The set of qualifiers on the type we're converting from.
2033 Qualifiers FromQualifiers = FromType.getQualifiers();
2034
Steve Naroff7cae42b2009-07-10 23:34:53 +00002035 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002036 const ObjCObjectPointerType* ToObjCPtr =
2037 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002038 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002039 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002040
Steve Naroff7cae42b2009-07-10 23:34:53 +00002041 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-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 Gregoraec25842011-04-26 23:16:46 +00002048 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002049 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002050 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002051 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002052 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002053 return true;
2054 }
2055 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002056 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002057 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002058 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002059 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002060 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-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 Jahanianb397e432010-03-15 18:36:00 +00002066 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2067 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002068 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002069 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2070 FromObjCPtr->getPointeeType()))
2071 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002073 ToObjCPtr->getPointeeType(),
2074 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002075 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-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 Takumif9cbcc42011-01-27 07:10:08 +00002084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002085 ToObjCPtr->getPointeeType(),
2086 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002087 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002088 return true;
2089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002091 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002092 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002093 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002094 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002096 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002097 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002098 // to a block pointer type.
2099 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002100 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002101 return true;
2102 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002103 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002106 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002108 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002109 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002110 return true;
2111 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002112 else
Douglas Gregora119f102008-12-19 19:13:09 +00002113 return false;
2114
Douglas Gregor033f56d2008-12-23 00:53:59 +00002115 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002116 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002117 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002118 else if (const BlockPointerType *FromBlockPtr =
2119 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002120 FromPointeeType = FromBlockPtr->getPointeeType();
2121 else
Douglas Gregora119f102008-12-19 19:13:09 +00002122 return false;
2123
Douglas Gregora119f102008-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 Gregor8d6d0672010-12-01 21:43:58 +00002131 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002132 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002133 return true;
2134 }
Fariborz Jahanian42ffdb32010-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 McCall31168b02011-06-15 23:02:42 +00002141
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002142 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002143 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002144 return true;
2145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146
Douglas Gregor033f56d2008-12-23 00:53:59 +00002147 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-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 Stump11289f42009-09-09 15:08:12 +00002151 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002152 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002153 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002154 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-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 Stump11289f42009-09-09 15:08:12 +00002182
Douglas Gregora119f102008-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 Gregoraec25842011-04-26 23:16:46 +00002204 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002205 IncompatibleObjC = true;
2206 return true;
2207 }
2208 }
2209
Sebastian Redl72b597d2009-01-25 19:43:20 +00002210 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002211}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002212
John McCall31168b02011-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 Blaikiebbafb8a2012-03-11 07:00:24 +00002224 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-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 McCall18ce25e2012-02-08 00:46:36 +00002238 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-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 Jahanian42455ea2011-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 Jahanian4de45dc2011-02-13 20:01:48 +00002304 if (!FromFunctionType || !ToFunctionType)
2305 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002306
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002307 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002308 return true;
Fariborz Jahanian4de45dc2011-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 Jahanian12834e12011-02-13 20:11:42 +00002322 if (Context.hasSameType(FromFunctionType->getResultType(),
2323 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-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 Blaikiebbafb8a2012-03-11 07:00:24 +00002328 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-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 Jahanian97676972011-09-28 21:52:05 +00002361 if (LangOpts.ObjCAutoRefCount &&
2362 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2363 ToFunctionType))
2364 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002365
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002366 ConvertedType = ToType;
2367 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002368}
2369
Richard Trieucaff2472011-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 Trieu96ed5b62011-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 Trieucaff2472011-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 Trieucaff2472011-11-23 22:32:32 +00002401 }
2402
Richard Trieu96ed5b62011-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 Trieucaff2472011-11-23 22:32:32 +00002409 FromType = FromType.getNonReferenceType();
2410 ToType = ToType.getNonReferenceType();
2411
Richard Trieucaff2472011-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 Trieu96ed5b62011-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 Trieucaff2472011-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 Jahanian5e5998f2010-05-03 21:06:18 +00002468/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002469/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-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 Trieucaff2472011-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 Takumif9cbcc42011-01-27 07:10:08 +00002474bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002475 const FunctionProtoType *NewType,
2476 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002477 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-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 Takumif9cbcc42011-01-27 07:10:08 +00002488
Fariborz Jahanian5e5998f2010-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 Trieucaff2472011-11-23 22:32:32 +00002494 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002495 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2496 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002497 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2498 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2499 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2500 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002501 continue;
2502 }
John McCall8b07ec22010-05-15 11:32:37 +00002503 else if (const ObjCObjectPointerType *PTTo =
2504 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002505 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002506 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002507 if (Context.hasSameUnqualifiedType(
2508 PTTo->getObjectType()->getBaseType(),
2509 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002510 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002511 }
Richard Trieucaff2472011-11-23 22:32:32 +00002512 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002513 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002514 }
2515 }
2516 return true;
2517}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002518
Douglas Gregor39c16d42008-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 Redl9f831db2009-07-25 15:41:38 +00002521/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-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 Carlsson7ec8ccd2009-09-12 04:46:44 +00002525bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002526 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002527 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002528 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002529 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002530 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002531
John McCall8cb679e2010-11-15 09:13:47 +00002532 Kind = CK_BitCast;
2533
Chandler Carruthffab8732011-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 Carruth66a7b042011-04-09 07:48:17 +00002538 PDiag(diag::warn_impcast_bool_to_null_pointer)
2539 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002540
John McCall9320b872011-09-09 05:25:32 +00002541 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2542 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002543 QualType FromPointeeType = FromPtrType->getPointeeType(),
2544 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002545
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002546 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2547 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002548 // We must have a derived-to-base conversion. Check an
2549 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002550 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2551 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002552 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002553 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002554 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002555
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002556 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002557 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002558 }
2559 }
John McCall9320b872011-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 Naroff7cae42b2009-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 Naroff1329fa02009-07-15 18:40:39 +00002567 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002568 return false;
John McCall9320b872011-09-09 05:25:32 +00002569 } else if (FromType->isBlockPointerType()) {
2570 Kind = CK_BlockPointerToObjCPointerCast;
2571 } else {
2572 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002573 }
John McCall9320b872011-09-09 05:25:32 +00002574 } else if (ToType->isBlockPointerType()) {
2575 if (!FromType->isBlockPointerType())
2576 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002577 }
John McCall8cb679e2010-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 Gregor39c16d42008-10-24 04:54:22 +00002584 return false;
2585}
2586
Sebastian Redl72b597d2009-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 Takumif9cbcc42011-01-27 07:10:08 +00002593 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002594 bool InOverloadResolution,
2595 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002596 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-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 Gregor56751b52009-09-25 04:25:58 +00002601 if (From->isNullPointerConstant(Context,
2602 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2603 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002604 ConvertedType = ToType;
2605 return true;
2606 }
2607
2608 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002609 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-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 Redl72b597d2009-01-25 19:43:20 +00002617
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002618 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002619 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002620 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002621 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2622 ToClass.getTypePtr());
2623 return true;
2624 }
2625
2626 return false;
2627}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002628
Sebastian Redl72b597d2009-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 McCall5b0829a2010-02-10 09:31:12 +00002631/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-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 Stump11289f42009-09-09 15:08:12 +00002635bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002636 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002637 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002638 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002639 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002640 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002641 if (!FromPtrType) {
2642 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002643 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002644 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002645 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002646 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002647 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002648 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002649
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002650 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002651 assert(ToPtrType && "No member pointer cast has a target type "
2652 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002653
Sebastian Redled8f2002009-01-28 18:33:18 +00002654 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2655 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002656
Sebastian Redled8f2002009-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 Redl72b597d2009-01-25 19:43:20 +00002660
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002661 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002662 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-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 Redl72b597d2009-01-25 19:43:20 +00002667
Sebastian Redled8f2002009-01-28 18:33:18 +00002668 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2669 getUnqualifiedType())) {
Sebastian Redled8f2002009-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 Redl72b597d2009-01-25 19:43:20 +00002674 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002675
Douglas Gregor89ee6822009-02-28 01:32:25 +00002676 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-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 McCall5b0829a2010-02-10 09:31:12 +00002683 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002684 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2685 Paths.front(),
2686 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002687
Anders Carlssond7923c62009-08-22 23:33:40 +00002688 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002689 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002690 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002691 return false;
2692}
2693
Douglas Gregor9a657932008-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 McCall31168b02011-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 Stump11289f42009-09-09 15:08:12 +00002701bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002703 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002704 FromType = Context.getCanonicalType(FromType);
2705 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002706 ObjCLifetimeConversion = false;
2707
Douglas Gregor9a657932008-10-21 23:43:52 +00002708 // If FromType and ToType are the same type, this is not a
2709 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002710 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002711 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002712
Douglas Gregor9a657932008-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 Gregor9a657932008-10-21 23:43:52 +00002717 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002718 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-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 Gregor29a92472008-10-22 17:49:05 +00002722 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002723 // until there are no more pointers or pointers-to-members left to
2724 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002725 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002726
Douglas Gregor90609aa2011-04-25 18:40:17 +00002727 Qualifiers FromQuals = FromType.getQualifiers();
2728 Qualifiers ToQuals = ToType.getQualifiers();
2729
John McCall31168b02011-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 Gregorf30053d2011-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 Gregor9a657932008-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 Gregor90609aa2011-04-25 18:40:17 +00002754 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002755 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002756
Douglas Gregor9a657932008-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 Gregor90609aa2011-04-25 18:40:17 +00002759 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002760 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002761 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002762
Douglas Gregor9a657932008-10-21 23:43:52 +00002763 // Keep track of whether all prior cv-qualifiers in the "to" type
2764 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002765 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002766 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002767 }
Douglas Gregor9a657932008-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 Gregor1b8fe5b72009-11-16 21:35:15 +00002774 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002775}
2776
Douglas Gregorc79862f2012-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 Gregorf9e36cc2012-04-12 20:48:09 +00002782static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2783 bool InOverloadResolution,
2784 StandardConversionSequence &SCS,
2785 bool CStyle) {
Douglas Gregorc79862f2012-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 Redle5417162012-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 Redl82ace982012-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 Redle5417162012-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 Redl82ace982012-02-11 23:51:08 +00002848 if (ConstructorTmpl)
2849 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2850 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002851 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002852 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002853 else
2854 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002855 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002856 SuppressUserConversions);
Sebastian Redl82ace982012-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 Gregor576e98c2009-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 Gregor576e98c2009-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 McCall5c32be02010-08-24 20:38:10 +00002902static OverloadingResult
2903IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002904 UserDefinedConversionSequence &User,
2905 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002906 bool AllowExplicit) {
Douglas Gregor5ab11652010-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 Kremenekc23c7e62009-07-29 21:53:49 +00002912 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-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 McCall5c32be02010-08-24 20:38:10 +00002921 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002922 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002923 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002924 ConstructorsOnly = true;
2925
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002926 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002927 // 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 Gregor3ec1bf22009-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 Redl6901c0d2011-12-22 18:58:38 +00002934
2935 Expr **Args = &From;
2936 unsigned NumArgs = 1;
2937 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002938 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-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 Redl6901c0d2011-12-22 18:58:38 +00002949 Args = InitList->getInits();
2950 NumArgs = InitList->getNumInits();
2951 ListInitializing = true;
2952 }
2953
Douglas Gregor89ee6822009-02-28 01:32:25 +00002954 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002955 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002956 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002957 NamedDecl *D = *Con;
2958 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2959
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002960 // Find the constructor (which may be a template).
2961 CXXConstructorDecl *Constructor = 0;
2962 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002963 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002964 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002965 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002966 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2967 else
John McCalla0296f72010-03-19 07:35:19 +00002968 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002969
Sebastian Redl6901c0d2011-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 Redld9170b02012-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 Redle5417162012-03-27 18:33:03 +00002982 SuppressUserConversions = isFirstArgumentCompatibleWithType(
2983 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00002984 }
2985 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002986 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002987 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2988 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002989 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002990 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002991 else
Fariborz Jahanianb3c44f92009-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 McCall5c32be02010-08-24 20:38:10 +00002994 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002995 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002996 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002997 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002998 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002999 }
3000 }
3001
Douglas Gregor5ab11652010-04-17 22:01:05 +00003002 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003003 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003004 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003005 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003006 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003007 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003008 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003009 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3010 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00003011 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003012 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003013 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003014 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003015 DeclAccessPair FoundDecl = I.getPair();
3016 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003017 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3018 if (isa<UsingShadowDecl>(D))
3019 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3020
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003021 CXXConversionDecl *Conv;
3022 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003023 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3024 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003025 else
John McCallda4458e2010-03-31 01:36:47 +00003026 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003027
3028 if (AllowExplicit || !Conv->isExplicit()) {
3029 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003030 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3031 ActingContext, From, ToType,
3032 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003033 else
John McCall5c32be02010-08-24 20:38:10 +00003034 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3035 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003036 }
3037 }
3038 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003039 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003040
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003041 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3042
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003043 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003044 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003045 case OR_Success:
3046 // Record the standard conversion we used and the conversion function.
3047 if (CXXConstructorDecl *Constructor
3048 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003049 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00003050
John McCall5c32be02010-08-24 20:38:10 +00003051 // C++ [over.ics.user]p1:
3052 // If the user-defined conversion is specified by a
3053 // constructor (12.3.1), the initial standard conversion
3054 // sequence converts the source type to the type required by
3055 // the argument of the constructor.
3056 //
3057 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003058 if (isa<InitListExpr>(From)) {
3059 // Initializer lists don't have conversions as such.
3060 User.Before.setAsIdentityConversion();
3061 } else {
3062 if (Best->Conversions[0].isEllipsis())
3063 User.EllipsisConversion = true;
3064 else {
3065 User.Before = Best->Conversions[0].Standard;
3066 User.EllipsisConversion = false;
3067 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003068 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003069 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003070 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003071 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003072 User.After.setAsIdentityConversion();
3073 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3074 User.After.setAllToTypes(ToType);
3075 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003076 }
3077 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003078 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003079 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003080
John McCall5c32be02010-08-24 20:38:10 +00003081 // C++ [over.ics.user]p1:
3082 //
3083 // [...] If the user-defined conversion is specified by a
3084 // conversion function (12.3.2), the initial standard
3085 // conversion sequence converts the source type to the
3086 // implicit object parameter of the conversion function.
3087 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003088 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003089 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003090 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003091 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003092
John McCall5c32be02010-08-24 20:38:10 +00003093 // C++ [over.ics.user]p2:
3094 // The second standard conversion sequence converts the
3095 // result of the user-defined conversion to the target type
3096 // for the sequence. Since an implicit conversion sequence
3097 // is an initialization, the special rules for
3098 // initialization by user-defined conversion apply when
3099 // selecting the best user-defined conversion for a
3100 // user-defined conversion sequence (see 13.3.3 and
3101 // 13.3.3.1).
3102 User.After = Best->FinalConversion;
3103 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003104 }
David Blaikie8a40f702012-01-17 06:56:22 +00003105 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003106
John McCall5c32be02010-08-24 20:38:10 +00003107 case OR_No_Viable_Function:
3108 return OR_No_Viable_Function;
3109 case OR_Deleted:
3110 // No conversion here! We're done.
3111 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112
John McCall5c32be02010-08-24 20:38:10 +00003113 case OR_Ambiguous:
3114 return OR_Ambiguous;
3115 }
3116
David Blaikie8a40f702012-01-17 06:56:22 +00003117 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003118}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003119
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003120bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003121Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003122 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003123 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003124 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003125 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003126 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003127 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003128 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003129 diag::err_typecheck_ambiguous_condition)
3130 << From->getType() << ToType << From->getSourceRange();
3131 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003132 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003133 diag::err_typecheck_nonviable_condition)
3134 << From->getType() << ToType << From->getSourceRange();
3135 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003136 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003137 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003138 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003139}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003140
Douglas Gregor2837aa22012-02-22 17:32:19 +00003141/// \brief Compare the user-defined conversion functions or constructors
3142/// of two user-defined conversion sequences to determine whether any ordering
3143/// is possible.
3144static ImplicitConversionSequence::CompareKind
3145compareConversionFunctions(Sema &S,
3146 FunctionDecl *Function1,
3147 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003148 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003149 return ImplicitConversionSequence::Indistinguishable;
3150
3151 // Objective-C++:
3152 // If both conversion functions are implicitly-declared conversions from
3153 // a lambda closure type to a function pointer and a block pointer,
3154 // respectively, always prefer the conversion to a function pointer,
3155 // because the function pointer is more lightweight and is more likely
3156 // to keep code working.
3157 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3158 if (!Conv1)
3159 return ImplicitConversionSequence::Indistinguishable;
3160
3161 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3162 if (!Conv2)
3163 return ImplicitConversionSequence::Indistinguishable;
3164
3165 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3166 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3167 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3168 if (Block1 != Block2)
3169 return Block1? ImplicitConversionSequence::Worse
3170 : ImplicitConversionSequence::Better;
3171 }
3172
3173 return ImplicitConversionSequence::Indistinguishable;
3174}
3175
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003176/// CompareImplicitConversionSequences - Compare two implicit
3177/// conversion sequences to determine whether one is better than the
3178/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003179static ImplicitConversionSequence::CompareKind
3180CompareImplicitConversionSequences(Sema &S,
3181 const ImplicitConversionSequence& ICS1,
3182 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003183{
3184 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3185 // conversion sequences (as defined in 13.3.3.1)
3186 // -- a standard conversion sequence (13.3.3.1.1) is a better
3187 // conversion sequence than a user-defined conversion sequence or
3188 // an ellipsis conversion sequence, and
3189 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3190 // conversion sequence than an ellipsis conversion sequence
3191 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003192 //
John McCall0d1da222010-01-12 00:44:57 +00003193 // C++0x [over.best.ics]p10:
3194 // For the purpose of ranking implicit conversion sequences as
3195 // described in 13.3.3.2, the ambiguous conversion sequence is
3196 // treated as a user-defined sequence that is indistinguishable
3197 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003198 if (ICS1.getKindRank() < ICS2.getKindRank())
3199 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003200 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003201 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003202
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003203 // The following checks require both conversion sequences to be of
3204 // the same kind.
3205 if (ICS1.getKind() != ICS2.getKind())
3206 return ImplicitConversionSequence::Indistinguishable;
3207
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003208 ImplicitConversionSequence::CompareKind Result =
3209 ImplicitConversionSequence::Indistinguishable;
3210
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003211 // Two implicit conversion sequences of the same form are
3212 // indistinguishable conversion sequences unless one of the
3213 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003214 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003215 Result = CompareStandardConversionSequences(S,
3216 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003217 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003218 // User-defined conversion sequence U1 is a better conversion
3219 // sequence than another user-defined conversion sequence U2 if
3220 // they contain the same user-defined conversion function or
3221 // constructor and if the second standard conversion sequence of
3222 // U1 is better than the second standard conversion sequence of
3223 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003224 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003225 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003226 Result = CompareStandardConversionSequences(S,
3227 ICS1.UserDefined.After,
3228 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003229 else
3230 Result = compareConversionFunctions(S,
3231 ICS1.UserDefined.ConversionFunction,
3232 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003233 }
3234
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003235 // List-initialization sequence L1 is a better conversion sequence than
3236 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3237 // for some X and L2 does not.
3238 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003239 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003240 ICS1.isListInitializationSequence() &&
3241 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003242 if (ICS1.isStdInitializerListElement() &&
3243 !ICS2.isStdInitializerListElement())
3244 return ImplicitConversionSequence::Better;
3245 if (!ICS1.isStdInitializerListElement() &&
3246 ICS2.isStdInitializerListElement())
3247 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003248 }
3249
3250 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003251}
3252
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003253static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3254 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3255 Qualifiers Quals;
3256 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003260 return Context.hasSameUnqualifiedType(T1, T2);
3261}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003263// Per 13.3.3.2p3, compare the given standard conversion sequences to
3264// determine if one is a proper subset of the other.
3265static ImplicitConversionSequence::CompareKind
3266compareStandardConversionSubsets(ASTContext &Context,
3267 const StandardConversionSequence& SCS1,
3268 const StandardConversionSequence& SCS2) {
3269 ImplicitConversionSequence::CompareKind Result
3270 = ImplicitConversionSequence::Indistinguishable;
3271
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003272 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003273 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003274 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3275 return ImplicitConversionSequence::Better;
3276 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3277 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003279 if (SCS1.Second != SCS2.Second) {
3280 if (SCS1.Second == ICK_Identity)
3281 Result = ImplicitConversionSequence::Better;
3282 else if (SCS2.Second == ICK_Identity)
3283 Result = ImplicitConversionSequence::Worse;
3284 else
3285 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003286 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003287 return ImplicitConversionSequence::Indistinguishable;
3288
3289 if (SCS1.Third == SCS2.Third) {
3290 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3291 : ImplicitConversionSequence::Indistinguishable;
3292 }
3293
3294 if (SCS1.Third == ICK_Identity)
3295 return Result == ImplicitConversionSequence::Worse
3296 ? ImplicitConversionSequence::Indistinguishable
3297 : ImplicitConversionSequence::Better;
3298
3299 if (SCS2.Third == ICK_Identity)
3300 return Result == ImplicitConversionSequence::Better
3301 ? ImplicitConversionSequence::Indistinguishable
3302 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003304 return ImplicitConversionSequence::Indistinguishable;
3305}
3306
Douglas Gregore696ebb2011-01-26 14:52:12 +00003307/// \brief Determine whether one of the given reference bindings is better
3308/// than the other based on what kind of bindings they are.
3309static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3310 const StandardConversionSequence &SCS2) {
3311 // C++0x [over.ics.rank]p3b4:
3312 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3313 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003315 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003317 // reference*.
3318 //
3319 // FIXME: Rvalue references. We're going rogue with the above edits,
3320 // because the semantics in the current C++0x working paper (N3225 at the
3321 // time of this writing) break the standard definition of std::forward
3322 // and std::reference_wrapper when dealing with references to functions.
3323 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003324 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3325 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3326 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327
Douglas Gregore696ebb2011-01-26 14:52:12 +00003328 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3329 SCS2.IsLvalueReference) ||
3330 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3331 !SCS2.IsLvalueReference);
3332}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003334/// CompareStandardConversionSequences - Compare two standard
3335/// conversion sequences to determine whether one is better than the
3336/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003337static ImplicitConversionSequence::CompareKind
3338CompareStandardConversionSequences(Sema &S,
3339 const StandardConversionSequence& SCS1,
3340 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003341{
3342 // Standard conversion sequence S1 is a better conversion sequence
3343 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3344
3345 // -- S1 is a proper subsequence of S2 (comparing the conversion
3346 // sequences in the canonical form defined by 13.3.3.1.1,
3347 // excluding any Lvalue Transformation; the identity conversion
3348 // sequence is considered to be a subsequence of any
3349 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003350 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003351 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003352 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003353
3354 // -- the rank of S1 is better than the rank of S2 (by the rules
3355 // defined below), or, if not that,
3356 ImplicitConversionRank Rank1 = SCS1.getRank();
3357 ImplicitConversionRank Rank2 = SCS2.getRank();
3358 if (Rank1 < Rank2)
3359 return ImplicitConversionSequence::Better;
3360 else if (Rank2 < Rank1)
3361 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003362
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003363 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3364 // are indistinguishable unless one of the following rules
3365 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003366
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003367 // A conversion that is not a conversion of a pointer, or
3368 // pointer to member, to bool is better than another conversion
3369 // that is such a conversion.
3370 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3371 return SCS2.isPointerConversionToBool()
3372 ? ImplicitConversionSequence::Better
3373 : ImplicitConversionSequence::Worse;
3374
Douglas Gregor5c407d92008-10-23 00:40:37 +00003375 // C++ [over.ics.rank]p4b2:
3376 //
3377 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003378 // conversion of B* to A* is better than conversion of B* to
3379 // void*, and conversion of A* to void* is better than conversion
3380 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003381 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003382 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003383 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003384 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003385 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3386 // Exactly one of the conversion sequences is a conversion to
3387 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003388 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3389 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003390 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3391 // Neither conversion sequence converts to a void pointer; compare
3392 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003393 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003394 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003395 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003396 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3397 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003398 // Both conversion sequences are conversions to void
3399 // pointers. Compare the source types to determine if there's an
3400 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003401 QualType FromType1 = SCS1.getFromType();
3402 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003403
3404 // Adjust the types we're converting from via the array-to-pointer
3405 // conversion, if we need to.
3406 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003407 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003408 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003409 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003410
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003411 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3412 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003413
John McCall5c32be02010-08-24 20:38:10 +00003414 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003415 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003416 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003417 return ImplicitConversionSequence::Worse;
3418
3419 // Objective-C++: If one interface is more specific than the
3420 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003421 const ObjCObjectPointerType* FromObjCPtr1
3422 = FromType1->getAs<ObjCObjectPointerType>();
3423 const ObjCObjectPointerType* FromObjCPtr2
3424 = FromType2->getAs<ObjCObjectPointerType>();
3425 if (FromObjCPtr1 && FromObjCPtr2) {
3426 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3427 FromObjCPtr2);
3428 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3429 FromObjCPtr1);
3430 if (AssignLeft != AssignRight) {
3431 return AssignLeft? ImplicitConversionSequence::Better
3432 : ImplicitConversionSequence::Worse;
3433 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003434 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003435 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003436
3437 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3438 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003439 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003440 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003441 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003442
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003443 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003444 // Check for a better reference binding based on the kind of bindings.
3445 if (isBetterReferenceBindingKind(SCS1, SCS2))
3446 return ImplicitConversionSequence::Better;
3447 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3448 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Sebastian Redlb28b4072009-03-22 23:49:27 +00003450 // C++ [over.ics.rank]p3b4:
3451 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3452 // which the references refer are the same type except for
3453 // top-level cv-qualifiers, and the type to which the reference
3454 // initialized by S2 refers is more cv-qualified than the type
3455 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003456 QualType T1 = SCS1.getToType(2);
3457 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003458 T1 = S.Context.getCanonicalType(T1);
3459 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003460 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003461 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3462 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003463 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003464 // Objective-C++ ARC: If the references refer to objects with different
3465 // lifetimes, prefer bindings that don't change lifetime.
3466 if (SCS1.ObjCLifetimeConversionBinding !=
3467 SCS2.ObjCLifetimeConversionBinding) {
3468 return SCS1.ObjCLifetimeConversionBinding
3469 ? ImplicitConversionSequence::Worse
3470 : ImplicitConversionSequence::Better;
3471 }
3472
Chandler Carruth8e543b32010-12-12 08:17:55 +00003473 // If the type is an array type, promote the element qualifiers to the
3474 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003475 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003476 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003477 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003478 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003479 if (T2.isMoreQualifiedThan(T1))
3480 return ImplicitConversionSequence::Better;
3481 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003482 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003483 }
3484 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003485
Francois Pichet08d2fa02011-09-18 21:37:37 +00003486 // In Microsoft mode, prefer an integral conversion to a
3487 // floating-to-integral conversion if the integral conversion
3488 // is between types of the same size.
3489 // For example:
3490 // void f(float);
3491 // void f(int);
3492 // int main {
3493 // long a;
3494 // f(a);
3495 // }
3496 // Here, MSVC will call f(int) instead of generating a compile error
3497 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003498 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003499 SCS1.Second == ICK_Integral_Conversion &&
3500 SCS2.Second == ICK_Floating_Integral &&
3501 S.Context.getTypeSize(SCS1.getFromType()) ==
3502 S.Context.getTypeSize(SCS1.getToType(2)))
3503 return ImplicitConversionSequence::Better;
3504
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003505 return ImplicitConversionSequence::Indistinguishable;
3506}
3507
3508/// CompareQualificationConversions - Compares two standard conversion
3509/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003510/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3511ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003512CompareQualificationConversions(Sema &S,
3513 const StandardConversionSequence& SCS1,
3514 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003515 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003516 // -- S1 and S2 differ only in their qualification conversion and
3517 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3518 // cv-qualification signature of type T1 is a proper subset of
3519 // the cv-qualification signature of type T2, and S1 is not the
3520 // deprecated string literal array-to-pointer conversion (4.2).
3521 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3522 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3523 return ImplicitConversionSequence::Indistinguishable;
3524
3525 // FIXME: the example in the standard doesn't use a qualification
3526 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003527 QualType T1 = SCS1.getToType(2);
3528 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003529 T1 = S.Context.getCanonicalType(T1);
3530 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003531 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003532 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3533 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003534
3535 // If the types are the same, we won't learn anything by unwrapped
3536 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003537 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003538 return ImplicitConversionSequence::Indistinguishable;
3539
Chandler Carruth607f38e2009-12-29 07:16:59 +00003540 // If the type is an array type, promote the element qualifiers to the type
3541 // for comparison.
3542 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003543 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003544 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003545 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003546
Mike Stump11289f42009-09-09 15:08:12 +00003547 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003548 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003549
3550 // Objective-C++ ARC:
3551 // Prefer qualification conversions not involving a change in lifetime
3552 // to qualification conversions that do not change lifetime.
3553 if (SCS1.QualificationIncludesObjCLifetime !=
3554 SCS2.QualificationIncludesObjCLifetime) {
3555 Result = SCS1.QualificationIncludesObjCLifetime
3556 ? ImplicitConversionSequence::Worse
3557 : ImplicitConversionSequence::Better;
3558 }
3559
John McCall5c32be02010-08-24 20:38:10 +00003560 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003561 // Within each iteration of the loop, we check the qualifiers to
3562 // determine if this still looks like a qualification
3563 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003564 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003565 // until there are no more pointers or pointers-to-members left
3566 // to unwrap. This essentially mimics what
3567 // IsQualificationConversion does, but here we're checking for a
3568 // strict subset of qualifiers.
3569 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3570 // The qualifiers are the same, so this doesn't tell us anything
3571 // about how the sequences rank.
3572 ;
3573 else if (T2.isMoreQualifiedThan(T1)) {
3574 // T1 has fewer qualifiers, so it could be the better sequence.
3575 if (Result == ImplicitConversionSequence::Worse)
3576 // Neither has qualifiers that are a subset of the other's
3577 // qualifiers.
3578 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003579
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003580 Result = ImplicitConversionSequence::Better;
3581 } else if (T1.isMoreQualifiedThan(T2)) {
3582 // T2 has fewer qualifiers, so it could be the better sequence.
3583 if (Result == ImplicitConversionSequence::Better)
3584 // Neither has qualifiers that are a subset of the other's
3585 // qualifiers.
3586 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003587
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003588 Result = ImplicitConversionSequence::Worse;
3589 } else {
3590 // Qualifiers are disjoint.
3591 return ImplicitConversionSequence::Indistinguishable;
3592 }
3593
3594 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003595 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003596 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003597 }
3598
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003599 // Check that the winning standard conversion sequence isn't using
3600 // the deprecated string literal array to pointer conversion.
3601 switch (Result) {
3602 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003603 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003604 Result = ImplicitConversionSequence::Indistinguishable;
3605 break;
3606
3607 case ImplicitConversionSequence::Indistinguishable:
3608 break;
3609
3610 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003611 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003612 Result = ImplicitConversionSequence::Indistinguishable;
3613 break;
3614 }
3615
3616 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003617}
3618
Douglas Gregor5c407d92008-10-23 00:40:37 +00003619/// CompareDerivedToBaseConversions - Compares two standard conversion
3620/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003621/// various kinds of derived-to-base conversions (C++
3622/// [over.ics.rank]p4b3). As part of these checks, we also look at
3623/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003624ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003625CompareDerivedToBaseConversions(Sema &S,
3626 const StandardConversionSequence& SCS1,
3627 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003628 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003629 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003630 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003631 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003632
3633 // Adjust the types we're converting from via the array-to-pointer
3634 // conversion, if we need to.
3635 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003636 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003637 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003638 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003639
3640 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003641 FromType1 = S.Context.getCanonicalType(FromType1);
3642 ToType1 = S.Context.getCanonicalType(ToType1);
3643 FromType2 = S.Context.getCanonicalType(FromType2);
3644 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003645
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003646 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003647 //
3648 // If class B is derived directly or indirectly from class A and
3649 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003650 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003651 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003652 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003653 SCS2.Second == ICK_Pointer_Conversion &&
3654 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3655 FromType1->isPointerType() && FromType2->isPointerType() &&
3656 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003657 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003658 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003659 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003660 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003661 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003662 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003663 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003664 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003665
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003666 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003667 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003668 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003669 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003670 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003671 return ImplicitConversionSequence::Worse;
3672 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003673
3674 // -- conversion of B* to A* is better than conversion of C* to A*,
3675 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003676 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003677 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003678 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003679 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003680 }
3681 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3682 SCS2.Second == ICK_Pointer_Conversion) {
3683 const ObjCObjectPointerType *FromPtr1
3684 = FromType1->getAs<ObjCObjectPointerType>();
3685 const ObjCObjectPointerType *FromPtr2
3686 = FromType2->getAs<ObjCObjectPointerType>();
3687 const ObjCObjectPointerType *ToPtr1
3688 = ToType1->getAs<ObjCObjectPointerType>();
3689 const ObjCObjectPointerType *ToPtr2
3690 = ToType2->getAs<ObjCObjectPointerType>();
3691
3692 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3693 // Apply the same conversion ranking rules for Objective-C pointer types
3694 // that we do for C++ pointers to class types. However, we employ the
3695 // Objective-C pseudo-subtyping relationship used for assignment of
3696 // Objective-C pointer types.
3697 bool FromAssignLeft
3698 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3699 bool FromAssignRight
3700 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3701 bool ToAssignLeft
3702 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3703 bool ToAssignRight
3704 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3705
3706 // A conversion to an a non-id object pointer type or qualified 'id'
3707 // type is better than a conversion to 'id'.
3708 if (ToPtr1->isObjCIdType() &&
3709 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3710 return ImplicitConversionSequence::Worse;
3711 if (ToPtr2->isObjCIdType() &&
3712 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3713 return ImplicitConversionSequence::Better;
3714
3715 // A conversion to a non-id object pointer type is better than a
3716 // conversion to a qualified 'id' type
3717 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3718 return ImplicitConversionSequence::Worse;
3719 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3720 return ImplicitConversionSequence::Better;
3721
3722 // A conversion to an a non-Class object pointer type or qualified 'Class'
3723 // type is better than a conversion to 'Class'.
3724 if (ToPtr1->isObjCClassType() &&
3725 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3726 return ImplicitConversionSequence::Worse;
3727 if (ToPtr2->isObjCClassType() &&
3728 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3729 return ImplicitConversionSequence::Better;
3730
3731 // A conversion to a non-Class object pointer type is better than a
3732 // conversion to a qualified 'Class' type.
3733 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3734 return ImplicitConversionSequence::Worse;
3735 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3736 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003737
Douglas Gregor058d3de2011-01-31 18:51:41 +00003738 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3739 if (S.Context.hasSameType(FromType1, FromType2) &&
3740 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3741 (ToAssignLeft != ToAssignRight))
3742 return ToAssignLeft? ImplicitConversionSequence::Worse
3743 : ImplicitConversionSequence::Better;
3744
3745 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3746 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3747 (FromAssignLeft != FromAssignRight))
3748 return FromAssignLeft? ImplicitConversionSequence::Better
3749 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003750 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003751 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003752
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003753 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003754 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3755 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3756 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003758 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003760 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003762 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003764 ToType2->getAs<MemberPointerType>();
3765 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3766 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3767 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3768 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3769 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3770 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3771 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3772 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003773 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003774 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003775 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003776 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003777 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003778 return ImplicitConversionSequence::Better;
3779 }
3780 // conversion of B::* to C::* is better than conversion of A::* to C::*
3781 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003782 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003783 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003784 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003785 return ImplicitConversionSequence::Worse;
3786 }
3787 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788
Douglas Gregor5ab11652010-04-17 22:01:05 +00003789 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003790 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003791 // -- binding of an expression of type C to a reference of type
3792 // B& is better than binding an expression of type C to a
3793 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003794 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3795 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3796 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003797 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003798 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003799 return ImplicitConversionSequence::Worse;
3800 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003801
Douglas Gregor2fe98832008-11-03 19:09:14 +00003802 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003803 // -- binding of an expression of type B to a reference of type
3804 // A& is better than binding an expression of type C to a
3805 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003806 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3807 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3808 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003809 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003810 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003811 return ImplicitConversionSequence::Worse;
3812 }
3813 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003814
Douglas Gregor5c407d92008-10-23 00:40:37 +00003815 return ImplicitConversionSequence::Indistinguishable;
3816}
3817
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003818/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3819/// determine whether they are reference-related,
3820/// reference-compatible, reference-compatible with added
3821/// qualification, or incompatible, for use in C++ initialization by
3822/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3823/// type, and the first type (T1) is the pointee type of the reference
3824/// type being initialized.
3825Sema::ReferenceCompareResult
3826Sema::CompareReferenceRelationship(SourceLocation Loc,
3827 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003828 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003829 bool &ObjCConversion,
3830 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003831 assert(!OrigT1->isReferenceType() &&
3832 "T1 must be the pointee type of the reference type");
3833 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3834
3835 QualType T1 = Context.getCanonicalType(OrigT1);
3836 QualType T2 = Context.getCanonicalType(OrigT2);
3837 Qualifiers T1Quals, T2Quals;
3838 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3839 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3840
3841 // C++ [dcl.init.ref]p4:
3842 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3843 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3844 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003845 DerivedToBase = false;
3846 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003847 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003848 if (UnqualT1 == UnqualT2) {
3849 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003850 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003851 IsDerivedFrom(UnqualT2, UnqualT1))
3852 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003853 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3854 UnqualT2->isObjCObjectOrInterfaceType() &&
3855 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3856 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003857 else
3858 return Ref_Incompatible;
3859
3860 // At this point, we know that T1 and T2 are reference-related (at
3861 // least).
3862
3863 // If the type is an array type, promote the element qualifiers to the type
3864 // for comparison.
3865 if (isa<ArrayType>(T1) && T1Quals)
3866 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3867 if (isa<ArrayType>(T2) && T2Quals)
3868 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3869
3870 // C++ [dcl.init.ref]p4:
3871 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3872 // reference-related to T2 and cv1 is the same cv-qualification
3873 // as, or greater cv-qualification than, cv2. For purposes of
3874 // overload resolution, cases for which cv1 is greater
3875 // cv-qualification than cv2 are identified as
3876 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003877 //
3878 // Note that we also require equivalence of Objective-C GC and address-space
3879 // qualifiers when performing these computations, so that e.g., an int in
3880 // address space 1 is not reference-compatible with an int in address
3881 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003882 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3883 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3884 T1Quals.removeObjCLifetime();
3885 T2Quals.removeObjCLifetime();
3886 ObjCLifetimeConversion = true;
3887 }
3888
Douglas Gregord517d552011-04-28 17:56:11 +00003889 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003890 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003891 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003892 return Ref_Compatible_With_Added_Qualification;
3893 else
3894 return Ref_Related;
3895}
3896
Douglas Gregor836a7e82010-08-11 02:15:33 +00003897/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003898/// with DeclType. Return true if something definite is found.
3899static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003900FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3901 QualType DeclType, SourceLocation DeclLoc,
3902 Expr *Init, QualType T2, bool AllowRvalues,
3903 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003904 assert(T2->isRecordType() && "Can only find conversions of record types.");
3905 CXXRecordDecl *T2RecordDecl
3906 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3907
3908 OverloadCandidateSet CandidateSet(DeclLoc);
3909 const UnresolvedSetImpl *Conversions
3910 = T2RecordDecl->getVisibleConversionFunctions();
3911 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3912 E = Conversions->end(); I != E; ++I) {
3913 NamedDecl *D = *I;
3914 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3915 if (isa<UsingShadowDecl>(D))
3916 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3917
3918 FunctionTemplateDecl *ConvTemplate
3919 = dyn_cast<FunctionTemplateDecl>(D);
3920 CXXConversionDecl *Conv;
3921 if (ConvTemplate)
3922 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3923 else
3924 Conv = cast<CXXConversionDecl>(D);
3925
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003927 // explicit conversions, skip it.
3928 if (!AllowExplicit && Conv->isExplicit())
3929 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930
Douglas Gregor836a7e82010-08-11 02:15:33 +00003931 if (AllowRvalues) {
3932 bool DerivedToBase = false;
3933 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003934 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003935
3936 // If we are initializing an rvalue reference, don't permit conversion
3937 // functions that return lvalues.
3938 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3939 const ReferenceType *RefType
3940 = Conv->getConversionType()->getAs<LValueReferenceType>();
3941 if (RefType && !RefType->getPointeeType()->isFunctionType())
3942 continue;
3943 }
3944
Douglas Gregor836a7e82010-08-11 02:15:33 +00003945 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003946 S.CompareReferenceRelationship(
3947 DeclLoc,
3948 Conv->getConversionType().getNonReferenceType()
3949 .getUnqualifiedType(),
3950 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003951 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003952 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003953 continue;
3954 } else {
3955 // If the conversion function doesn't return a reference type,
3956 // it can't be considered for this conversion. An rvalue reference
3957 // is only acceptable if its referencee is a function type.
3958
3959 const ReferenceType *RefType =
3960 Conv->getConversionType()->getAs<ReferenceType>();
3961 if (!RefType ||
3962 (!RefType->isLValueReferenceType() &&
3963 !RefType->getPointeeType()->isFunctionType()))
3964 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
Douglas Gregor836a7e82010-08-11 02:15:33 +00003967 if (ConvTemplate)
3968 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003969 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003970 else
3971 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003972 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003973 }
3974
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003975 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3976
Sebastian Redld92badf2010-06-30 18:13:39 +00003977 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003978 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003979 case OR_Success:
3980 // C++ [over.ics.ref]p1:
3981 //
3982 // [...] If the parameter binds directly to the result of
3983 // applying a conversion function to the argument
3984 // expression, the implicit conversion sequence is a
3985 // user-defined conversion sequence (13.3.3.1.2), with the
3986 // second standard conversion sequence either an identity
3987 // conversion or, if the conversion function returns an
3988 // entity of a type that is a derived class of the parameter
3989 // type, a derived-to-base Conversion.
3990 if (!Best->FinalConversion.DirectBinding)
3991 return false;
3992
Chandler Carruth30141632011-02-25 19:41:05 +00003993 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003994 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003995 ICS.setUserDefined();
3996 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3997 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003998 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003999 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004000 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004001 ICS.UserDefined.EllipsisConversion = false;
4002 assert(ICS.UserDefined.After.ReferenceBinding &&
4003 ICS.UserDefined.After.DirectBinding &&
4004 "Expected a direct reference binding!");
4005 return true;
4006
4007 case OR_Ambiguous:
4008 ICS.setAmbiguous();
4009 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4010 Cand != CandidateSet.end(); ++Cand)
4011 if (Cand->Viable)
4012 ICS.Ambiguous.addConversion(Cand->Function);
4013 return true;
4014
4015 case OR_No_Viable_Function:
4016 case OR_Deleted:
4017 // There was no suitable conversion, or we found a deleted
4018 // conversion; continue with other checks.
4019 return false;
4020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021
David Blaikie8a40f702012-01-17 06:56:22 +00004022 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004023}
4024
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004025/// \brief Compute an implicit conversion sequence for reference
4026/// initialization.
4027static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004028TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004029 SourceLocation DeclLoc,
4030 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004031 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004032 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4033
4034 // Most paths end in a failed conversion.
4035 ImplicitConversionSequence ICS;
4036 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4037
4038 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4039 QualType T2 = Init->getType();
4040
4041 // If the initializer is the address of an overloaded function, try
4042 // to resolve the overloaded function. If all goes well, T2 is the
4043 // type of the resulting function.
4044 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4045 DeclAccessPair Found;
4046 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4047 false, Found))
4048 T2 = Fn->getType();
4049 }
4050
4051 // Compute some basic properties of the types and the initializer.
4052 bool isRValRef = DeclType->isRValueReferenceType();
4053 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004054 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004055 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004056 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004057 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004058 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004059 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004060
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004061
Sebastian Redld92badf2010-06-30 18:13:39 +00004062 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004063 // A reference to type "cv1 T1" is initialized by an expression
4064 // of type "cv2 T2" as follows:
4065
Sebastian Redld92badf2010-06-30 18:13:39 +00004066 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004067 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004068 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4069 // reference-compatible with "cv2 T2," or
4070 //
4071 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4072 if (InitCategory.isLValue() &&
4073 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004074 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004075 // When a parameter of reference type binds directly (8.5.3)
4076 // to an argument expression, the implicit conversion sequence
4077 // is the identity conversion, unless the argument expression
4078 // has a type that is a derived class of the parameter type,
4079 // in which case the implicit conversion sequence is a
4080 // derived-to-base Conversion (13.3.3.1).
4081 ICS.setStandard();
4082 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004083 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4084 : ObjCConversion? ICK_Compatible_Conversion
4085 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004086 ICS.Standard.Third = ICK_Identity;
4087 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4088 ICS.Standard.setToType(0, T2);
4089 ICS.Standard.setToType(1, T1);
4090 ICS.Standard.setToType(2, T1);
4091 ICS.Standard.ReferenceBinding = true;
4092 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004093 ICS.Standard.IsLvalueReference = !isRValRef;
4094 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4095 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004096 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004097 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004098 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004099
Sebastian Redld92badf2010-06-30 18:13:39 +00004100 // Nothing more to do: the inaccessibility/ambiguity check for
4101 // derived-to-base conversions is suppressed when we're
4102 // computing the implicit conversion sequence (C++
4103 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004104 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004105 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004106
Sebastian Redld92badf2010-06-30 18:13:39 +00004107 // -- has a class type (i.e., T2 is a class type), where T1 is
4108 // not reference-related to T2, and can be implicitly
4109 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4110 // is reference-compatible with "cv3 T3" 92) (this
4111 // conversion is selected by enumerating the applicable
4112 // conversion functions (13.3.1.6) and choosing the best
4113 // one through overload resolution (13.3)),
4114 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004116 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004117 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4118 Init, T2, /*AllowRvalues=*/false,
4119 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004120 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004121 }
4122 }
4123
Sebastian Redld92badf2010-06-30 18:13:39 +00004124 // -- Otherwise, the reference shall be an lvalue reference to a
4125 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004126 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004128 // We actually handle one oddity of C++ [over.ics.ref] at this
4129 // point, which is that, due to p2 (which short-circuits reference
4130 // binding by only attempting a simple conversion for non-direct
4131 // bindings) and p3's strange wording, we allow a const volatile
4132 // reference to bind to an rvalue. Hence the check for the presence
4133 // of "const" rather than checking for "const" being the only
4134 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004135 // This is also the point where rvalue references and lvalue inits no longer
4136 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00004137 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004138 return ICS;
4139
Douglas Gregorf143cd52011-01-24 16:14:37 +00004140 // -- If the initializer expression
4141 //
4142 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004143 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004144 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4145 (InitCategory.isXValue() ||
4146 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4147 (InitCategory.isLValue() && T2->isFunctionType()))) {
4148 ICS.setStandard();
4149 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004151 : ObjCConversion? ICK_Compatible_Conversion
4152 : ICK_Identity;
4153 ICS.Standard.Third = ICK_Identity;
4154 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4155 ICS.Standard.setToType(0, T2);
4156 ICS.Standard.setToType(1, T1);
4157 ICS.Standard.setToType(2, T1);
4158 ICS.Standard.ReferenceBinding = true;
4159 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4160 // binding unless we're binding to a class prvalue.
4161 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4162 // allow the use of rvalue references in C++98/03 for the benefit of
4163 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004164 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004165 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004166 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004167 ICS.Standard.IsLvalueReference = !isRValRef;
4168 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004170 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004171 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004172 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175
Douglas Gregorf143cd52011-01-24 16:14:37 +00004176 // -- has a class type (i.e., T2 is a class type), where T1 is not
4177 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178 // an xvalue, class prvalue, or function lvalue of type
4179 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004180 // "cv3 T3",
4181 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004183 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004185 // class subobject).
4186 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004188 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4189 Init, T2, /*AllowRvalues=*/true,
4190 AllowExplicit)) {
4191 // In the second case, if the reference is an rvalue reference
4192 // and the second standard conversion sequence of the
4193 // user-defined conversion sequence includes an lvalue-to-rvalue
4194 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004195 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004196 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4197 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4198
Douglas Gregor95273c32011-01-21 16:36:05 +00004199 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004201
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004202 // -- Otherwise, a temporary of type "cv1 T1" is created and
4203 // initialized from the initializer expression using the
4204 // rules for a non-reference copy initialization (8.5). The
4205 // reference is then bound to the temporary. If T1 is
4206 // reference-related to T2, cv1 must be the same
4207 // cv-qualification as, or greater cv-qualification than,
4208 // cv2; otherwise, the program is ill-formed.
4209 if (RefRelationship == Sema::Ref_Related) {
4210 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4211 // we would be reference-compatible or reference-compatible with
4212 // added qualification. But that wasn't the case, so the reference
4213 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004214 //
4215 // Note that we only want to check address spaces and cvr-qualifiers here.
4216 // ObjC GC and lifetime qualifiers aren't important.
4217 Qualifiers T1Quals = T1.getQualifiers();
4218 Qualifiers T2Quals = T2.getQualifiers();
4219 T1Quals.removeObjCGCAttr();
4220 T1Quals.removeObjCLifetime();
4221 T2Quals.removeObjCGCAttr();
4222 T2Quals.removeObjCLifetime();
4223 if (!T1Quals.compatiblyIncludes(T2Quals))
4224 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004225 }
4226
4227 // If at least one of the types is a class type, the types are not
4228 // related, and we aren't allowed any user conversions, the
4229 // reference binding fails. This case is important for breaking
4230 // recursion, since TryImplicitConversion below will attempt to
4231 // create a temporary through the use of a copy constructor.
4232 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4233 (T1->isRecordType() || T2->isRecordType()))
4234 return ICS;
4235
Douglas Gregorcba72b12011-01-21 05:18:22 +00004236 // If T1 is reference-related to T2 and the reference is an rvalue
4237 // reference, the initializer expression shall not be an lvalue.
4238 if (RefRelationship >= Sema::Ref_Related &&
4239 isRValRef && Init->Classify(S.Context).isLValue())
4240 return ICS;
4241
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004242 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004243 // When a parameter of reference type is not bound directly to
4244 // an argument expression, the conversion sequence is the one
4245 // required to convert the argument expression to the
4246 // underlying type of the reference according to
4247 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4248 // to copy-initializing a temporary of the underlying type with
4249 // the argument expression. Any difference in top-level
4250 // cv-qualification is subsumed by the initialization itself
4251 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004252 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4253 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004254 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004255 /*CStyle=*/false,
4256 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004257
4258 // Of course, that's still a reference binding.
4259 if (ICS.isStandard()) {
4260 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004261 ICS.Standard.IsLvalueReference = !isRValRef;
4262 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4263 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004264 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004265 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004266 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004267 // Don't allow rvalue references to bind to lvalues.
4268 if (DeclType->isRValueReferenceType()) {
4269 if (const ReferenceType *RefType
4270 = ICS.UserDefined.ConversionFunction->getResultType()
4271 ->getAs<LValueReferenceType>()) {
4272 if (!RefType->getPointeeType()->isFunctionType()) {
4273 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4274 DeclType);
4275 return ICS;
4276 }
4277 }
4278 }
4279
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004280 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004281 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4282 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4283 ICS.UserDefined.After.BindsToRvalue = true;
4284 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4285 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004286 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004287
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004288 return ICS;
4289}
4290
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004291static ImplicitConversionSequence
4292TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4293 bool SuppressUserConversions,
4294 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004295 bool AllowObjCWritebackConversion,
4296 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004297
4298/// TryListConversion - Try to copy-initialize a value of type ToType from the
4299/// initializer list From.
4300static ImplicitConversionSequence
4301TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4302 bool SuppressUserConversions,
4303 bool InOverloadResolution,
4304 bool AllowObjCWritebackConversion) {
4305 // C++11 [over.ics.list]p1:
4306 // When an argument is an initializer list, it is not an expression and
4307 // special rules apply for converting it to a parameter type.
4308
4309 ImplicitConversionSequence Result;
4310 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004311 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004312
Sebastian Redl09edce02012-01-23 22:09:39 +00004313 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004314 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004315 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004316 return Result;
4317
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004318 // C++11 [over.ics.list]p2:
4319 // If the parameter type is std::initializer_list<X> or "array of X" and
4320 // all the elements can be implicitly converted to X, the implicit
4321 // conversion sequence is the worst conversion necessary to convert an
4322 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004323 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004324 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004325 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004326 X = S.Context.getBaseElementType(ToType);
4327 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004328 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004329 if (!X.isNull()) {
4330 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4331 Expr *Init = From->getInit(i);
4332 ImplicitConversionSequence ICS =
4333 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4334 InOverloadResolution,
4335 AllowObjCWritebackConversion);
4336 // If a single element isn't convertible, fail.
4337 if (ICS.isBad()) {
4338 Result = ICS;
4339 break;
4340 }
4341 // Otherwise, look for the worst conversion.
4342 if (Result.isBad() ||
4343 CompareImplicitConversionSequences(S, ICS, Result) ==
4344 ImplicitConversionSequence::Worse)
4345 Result = ICS;
4346 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004347
4348 // For an empty list, we won't have computed any conversion sequence.
4349 // Introduce the identity conversion sequence.
4350 if (From->getNumInits() == 0) {
4351 Result.setStandard();
4352 Result.Standard.setAsIdentityConversion();
4353 Result.Standard.setFromType(ToType);
4354 Result.Standard.setAllToTypes(ToType);
4355 }
4356
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004357 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004358 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004359 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004360 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004361
4362 // C++11 [over.ics.list]p3:
4363 // Otherwise, if the parameter is a non-aggregate class X and overload
4364 // resolution chooses a single best constructor [...] the implicit
4365 // conversion sequence is a user-defined conversion sequence. If multiple
4366 // constructors are viable but none is better than the others, the
4367 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004368 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4369 // This function can deal with initializer lists.
4370 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4371 /*AllowExplicit=*/false,
4372 InOverloadResolution, /*CStyle=*/false,
4373 AllowObjCWritebackConversion);
4374 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004375 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004376 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004377
4378 // C++11 [over.ics.list]p4:
4379 // Otherwise, if the parameter has an aggregate type which can be
4380 // initialized from the initializer list [...] the implicit conversion
4381 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004382 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004383 // Type is an aggregate, argument is an init list. At this point it comes
4384 // down to checking whether the initialization works.
4385 // FIXME: Find out whether this parameter is consumed or not.
4386 InitializedEntity Entity =
4387 InitializedEntity::InitializeParameter(S.Context, ToType,
4388 /*Consumed=*/false);
4389 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4390 Result.setUserDefined();
4391 Result.UserDefined.Before.setAsIdentityConversion();
4392 // Initializer lists don't have a type.
4393 Result.UserDefined.Before.setFromType(QualType());
4394 Result.UserDefined.Before.setAllToTypes(QualType());
4395
4396 Result.UserDefined.After.setAsIdentityConversion();
4397 Result.UserDefined.After.setFromType(ToType);
4398 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004399 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004400 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004401 return Result;
4402 }
4403
4404 // C++11 [over.ics.list]p5:
4405 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004406 if (ToType->isReferenceType()) {
4407 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4408 // mention initializer lists in any way. So we go by what list-
4409 // initialization would do and try to extrapolate from that.
4410
4411 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4412
4413 // If the initializer list has a single element that is reference-related
4414 // to the parameter type, we initialize the reference from that.
4415 if (From->getNumInits() == 1) {
4416 Expr *Init = From->getInit(0);
4417
4418 QualType T2 = Init->getType();
4419
4420 // If the initializer is the address of an overloaded function, try
4421 // to resolve the overloaded function. If all goes well, T2 is the
4422 // type of the resulting function.
4423 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4424 DeclAccessPair Found;
4425 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4426 Init, ToType, false, Found))
4427 T2 = Fn->getType();
4428 }
4429
4430 // Compute some basic properties of the types and the initializer.
4431 bool dummy1 = false;
4432 bool dummy2 = false;
4433 bool dummy3 = false;
4434 Sema::ReferenceCompareResult RefRelationship
4435 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4436 dummy2, dummy3);
4437
4438 if (RefRelationship >= Sema::Ref_Related)
4439 return TryReferenceInit(S, Init, ToType,
4440 /*FIXME:*/From->getLocStart(),
4441 SuppressUserConversions,
4442 /*AllowExplicit=*/false);
4443 }
4444
4445 // Otherwise, we bind the reference to a temporary created from the
4446 // initializer list.
4447 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4448 InOverloadResolution,
4449 AllowObjCWritebackConversion);
4450 if (Result.isFailure())
4451 return Result;
4452 assert(!Result.isEllipsis() &&
4453 "Sub-initialization cannot result in ellipsis conversion.");
4454
4455 // Can we even bind to a temporary?
4456 if (ToType->isRValueReferenceType() ||
4457 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4458 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4459 Result.UserDefined.After;
4460 SCS.ReferenceBinding = true;
4461 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4462 SCS.BindsToRvalue = true;
4463 SCS.BindsToFunctionLvalue = false;
4464 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4465 SCS.ObjCLifetimeConversionBinding = false;
4466 } else
4467 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4468 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004469 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004470 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004471
4472 // C++11 [over.ics.list]p6:
4473 // Otherwise, if the parameter type is not a class:
4474 if (!ToType->isRecordType()) {
4475 // - if the initializer list has one element, the implicit conversion
4476 // sequence is the one required to convert the element to the
4477 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004478 unsigned NumInits = From->getNumInits();
4479 if (NumInits == 1)
4480 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4481 SuppressUserConversions,
4482 InOverloadResolution,
4483 AllowObjCWritebackConversion);
4484 // - if the initializer list has no elements, the implicit conversion
4485 // sequence is the identity conversion.
4486 else if (NumInits == 0) {
4487 Result.setStandard();
4488 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004489 Result.Standard.setFromType(ToType);
4490 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004491 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004492 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004493 return Result;
4494 }
4495
4496 // C++11 [over.ics.list]p7:
4497 // In all cases other than those enumerated above, no conversion is possible
4498 return Result;
4499}
4500
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004501/// TryCopyInitialization - Try to copy-initialize a value of type
4502/// ToType from the expression From. Return the implicit conversion
4503/// sequence required to pass this argument, which may be a bad
4504/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004505/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004506/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004507static ImplicitConversionSequence
4508TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004510 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004511 bool AllowObjCWritebackConversion,
4512 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004513 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4514 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4515 InOverloadResolution,AllowObjCWritebackConversion);
4516
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004517 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004518 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004519 /*FIXME:*/From->getLocStart(),
4520 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004521 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004522
John McCall5c32be02010-08-24 20:38:10 +00004523 return TryImplicitConversion(S, From, ToType,
4524 SuppressUserConversions,
4525 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004526 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004527 /*CStyle=*/false,
4528 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004529}
4530
Anna Zaks1b068122011-07-28 19:46:48 +00004531static bool TryCopyInitialization(const CanQualType FromQTy,
4532 const CanQualType ToQTy,
4533 Sema &S,
4534 SourceLocation Loc,
4535 ExprValueKind FromVK) {
4536 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4537 ImplicitConversionSequence ICS =
4538 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4539
4540 return !ICS.isBad();
4541}
4542
Douglas Gregor436424c2008-11-18 23:14:02 +00004543/// TryObjectArgumentInitialization - Try to initialize the object
4544/// parameter of the given member function (@c Method) from the
4545/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004546static ImplicitConversionSequence
4547TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004548 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004549 CXXMethodDecl *Method,
4550 CXXRecordDecl *ActingContext) {
4551 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004552 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4553 // const volatile object.
4554 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4555 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004556 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004557
4558 // Set up the conversion sequence as a "bad" conversion, to allow us
4559 // to exit early.
4560 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004561
4562 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004563 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004564 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004565 FromType = PT->getPointeeType();
4566
Douglas Gregor02824322011-01-26 19:30:28 +00004567 // When we had a pointer, it's implicitly dereferenced, so we
4568 // better have an lvalue.
4569 assert(FromClassification.isLValue());
4570 }
4571
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004572 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004573
Douglas Gregor02824322011-01-26 19:30:28 +00004574 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004576 // parameter is
4577 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004578 // - "lvalue reference to cv X" for functions declared without a
4579 // ref-qualifier or with the & ref-qualifier
4580 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004581 // ref-qualifier
4582 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004584 // cv-qualification on the member function declaration.
4585 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004586 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004587 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004588 // (C++ [over.match.funcs]p5). We perform a simplified version of
4589 // reference binding here, that allows class rvalues to bind to
4590 // non-constant references.
4591
Douglas Gregor02824322011-01-26 19:30:28 +00004592 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004593 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004595 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004596 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004597 ICS.setBad(BadConversionSequence::bad_qualifiers,
4598 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004599 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004600 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004601
4602 // Check that we have either the same type or a derived type. It
4603 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004604 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004605 ImplicitConversionKind SecondKind;
4606 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4607 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004608 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004609 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004610 else {
John McCall65eb8792010-02-25 01:37:24 +00004611 ICS.setBad(BadConversionSequence::unrelated_class,
4612 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004613 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004614 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004615
Douglas Gregor02824322011-01-26 19:30:28 +00004616 // Check the ref-qualifier.
4617 switch (Method->getRefQualifier()) {
4618 case RQ_None:
4619 // Do nothing; we don't care about lvalueness or rvalueness.
4620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621
Douglas Gregor02824322011-01-26 19:30:28 +00004622 case RQ_LValue:
4623 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4624 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004625 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004626 ImplicitParamType);
4627 return ICS;
4628 }
4629 break;
4630
4631 case RQ_RValue:
4632 if (!FromClassification.isRValue()) {
4633 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004635 ImplicitParamType);
4636 return ICS;
4637 }
4638 break;
4639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor436424c2008-11-18 23:14:02 +00004641 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004642 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004643 ICS.Standard.setAsIdentityConversion();
4644 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004645 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004646 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004647 ICS.Standard.ReferenceBinding = true;
4648 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004650 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004651 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4652 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4653 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004654 return ICS;
4655}
4656
4657/// PerformObjectArgumentInitialization - Perform initialization of
4658/// the implicit object parameter for the given Method with the given
4659/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004660ExprResult
4661Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004663 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004664 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004665 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004666 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004667 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004668
Douglas Gregor02824322011-01-26 19:30:28 +00004669 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004670 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004671 FromRecordType = PT->getPointeeType();
4672 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004673 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004674 } else {
4675 FromRecordType = From->getType();
4676 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004677 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004678 }
4679
John McCall6e9f8f62009-12-03 04:06:58 +00004680 // Note that we always use the true parent context when performing
4681 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004682 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004683 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4684 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004685 if (ICS.isBad()) {
4686 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4687 Qualifiers FromQs = FromRecordType.getQualifiers();
4688 Qualifiers ToQs = DestType.getQualifiers();
4689 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4690 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004691 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004692 diag::err_member_function_call_bad_cvr)
4693 << Method->getDeclName() << FromRecordType << (CVR - 1)
4694 << From->getSourceRange();
4695 Diag(Method->getLocation(), diag::note_previous_decl)
4696 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004697 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004698 }
4699 }
4700
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004701 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004702 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004703 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004704 }
Mike Stump11289f42009-09-09 15:08:12 +00004705
John Wiegley01296292011-04-08 18:41:53 +00004706 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4707 ExprResult FromRes =
4708 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4709 if (FromRes.isInvalid())
4710 return ExprError();
4711 From = FromRes.take();
4712 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004713
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004714 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004715 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004716 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004717 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004718}
4719
Douglas Gregor5fb53972009-01-14 15:45:31 +00004720/// TryContextuallyConvertToBool - Attempt to contextually convert the
4721/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004722static ImplicitConversionSequence
4723TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004724 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004725 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004726 // FIXME: Are these flags correct?
4727 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004728 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004729 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004730 /*CStyle=*/false,
4731 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004732}
4733
4734/// PerformContextuallyConvertToBool - Perform a contextual conversion
4735/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004736ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004737 if (checkPlaceholderForOverload(*this, From))
4738 return ExprError();
4739
John McCall5c32be02010-08-24 20:38:10 +00004740 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004741 if (!ICS.isBad())
4742 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Fariborz Jahanian76197412009-11-18 18:26:29 +00004744 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004745 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004746 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004747 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004748 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004749}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750
Richard Smithf8379a02012-01-18 23:55:52 +00004751/// Check that the specified conversion is permitted in a converted constant
4752/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4753/// is acceptable.
4754static bool CheckConvertedConstantConversions(Sema &S,
4755 StandardConversionSequence &SCS) {
4756 // Since we know that the target type is an integral or unscoped enumeration
4757 // type, most conversion kinds are impossible. All possible First and Third
4758 // conversions are fine.
4759 switch (SCS.Second) {
4760 case ICK_Identity:
4761 case ICK_Integral_Promotion:
4762 case ICK_Integral_Conversion:
4763 return true;
4764
4765 case ICK_Boolean_Conversion:
4766 // Conversion from an integral or unscoped enumeration type to bool is
4767 // classified as ICK_Boolean_Conversion, but it's also an integral
4768 // conversion, so it's permitted in a converted constant expression.
4769 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4770 SCS.getToType(2)->isBooleanType();
4771
4772 case ICK_Floating_Integral:
4773 case ICK_Complex_Real:
4774 return false;
4775
4776 case ICK_Lvalue_To_Rvalue:
4777 case ICK_Array_To_Pointer:
4778 case ICK_Function_To_Pointer:
4779 case ICK_NoReturn_Adjustment:
4780 case ICK_Qualification:
4781 case ICK_Compatible_Conversion:
4782 case ICK_Vector_Conversion:
4783 case ICK_Vector_Splat:
4784 case ICK_Derived_To_Base:
4785 case ICK_Pointer_Conversion:
4786 case ICK_Pointer_Member:
4787 case ICK_Block_Pointer_Conversion:
4788 case ICK_Writeback_Conversion:
4789 case ICK_Floating_Promotion:
4790 case ICK_Complex_Promotion:
4791 case ICK_Complex_Conversion:
4792 case ICK_Floating_Conversion:
4793 case ICK_TransparentUnionConversion:
4794 llvm_unreachable("unexpected second conversion kind");
4795
4796 case ICK_Num_Conversion_Kinds:
4797 break;
4798 }
4799
4800 llvm_unreachable("unknown conversion kind");
4801}
4802
4803/// CheckConvertedConstantExpression - Check that the expression From is a
4804/// converted constant expression of type T, perform the conversion and produce
4805/// the converted expression, per C++11 [expr.const]p3.
4806ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4807 llvm::APSInt &Value,
4808 CCEKind CCE) {
4809 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4810 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4811
4812 if (checkPlaceholderForOverload(*this, From))
4813 return ExprError();
4814
4815 // C++11 [expr.const]p3 with proposed wording fixes:
4816 // A converted constant expression of type T is a core constant expression,
4817 // implicitly converted to a prvalue of type T, where the converted
4818 // expression is a literal constant expression and the implicit conversion
4819 // sequence contains only user-defined conversions, lvalue-to-rvalue
4820 // conversions, integral promotions, and integral conversions other than
4821 // narrowing conversions.
4822 ImplicitConversionSequence ICS =
4823 TryImplicitConversion(From, T,
4824 /*SuppressUserConversions=*/false,
4825 /*AllowExplicit=*/false,
4826 /*InOverloadResolution=*/false,
4827 /*CStyle=*/false,
4828 /*AllowObjcWritebackConversion=*/false);
4829 StandardConversionSequence *SCS = 0;
4830 switch (ICS.getKind()) {
4831 case ImplicitConversionSequence::StandardConversion:
4832 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004833 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004834 diag::err_typecheck_converted_constant_expression_disallowed)
4835 << From->getType() << From->getSourceRange() << T;
4836 SCS = &ICS.Standard;
4837 break;
4838 case ImplicitConversionSequence::UserDefinedConversion:
4839 // We are converting from class type to an integral or enumeration type, so
4840 // the Before sequence must be trivial.
4841 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004842 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004843 diag::err_typecheck_converted_constant_expression_disallowed)
4844 << From->getType() << From->getSourceRange() << T;
4845 SCS = &ICS.UserDefined.After;
4846 break;
4847 case ImplicitConversionSequence::AmbiguousConversion:
4848 case ImplicitConversionSequence::BadConversion:
4849 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004850 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004851 diag::err_typecheck_converted_constant_expression)
4852 << From->getType() << From->getSourceRange() << T;
4853 return ExprError();
4854
4855 case ImplicitConversionSequence::EllipsisConversion:
4856 llvm_unreachable("ellipsis conversion in converted constant expression");
4857 }
4858
4859 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4860 if (Result.isInvalid())
4861 return Result;
4862
4863 // Check for a narrowing implicit conversion.
4864 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004865 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004866 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4867 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004868 case NK_Variable_Narrowing:
4869 // Implicit conversion to a narrower type, and the value is not a constant
4870 // expression. We'll diagnose this in a moment.
4871 case NK_Not_Narrowing:
4872 break;
4873
4874 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004875 Diag(From->getLocStart(),
4876 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4877 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004878 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004879 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004880 break;
4881
4882 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004883 Diag(From->getLocStart(),
4884 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4885 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004886 << CCE << /*Constant*/0 << From->getType() << T;
4887 break;
4888 }
4889
4890 // Check the expression is a constant expression.
4891 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4892 Expr::EvalResult Eval;
4893 Eval.Diag = &Notes;
4894
4895 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4896 // The expression can't be folded, so we can't keep it at this position in
4897 // the AST.
4898 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004899 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004900 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004901
4902 if (Notes.empty()) {
4903 // It's a constant expression.
4904 return Result;
4905 }
Richard Smithf8379a02012-01-18 23:55:52 +00004906 }
4907
4908 // It's not a constant expression. Produce an appropriate diagnostic.
4909 if (Notes.size() == 1 &&
4910 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4911 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4912 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004913 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004914 << CCE << From->getSourceRange();
4915 for (unsigned I = 0; I < Notes.size(); ++I)
4916 Diag(Notes[I].first, Notes[I].second);
4917 }
Richard Smith911e1422012-01-30 22:27:01 +00004918 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004919}
4920
John McCallfec112d2011-09-09 06:11:02 +00004921/// dropPointerConversions - If the given standard conversion sequence
4922/// involves any pointer conversions, remove them. This may change
4923/// the result type of the conversion sequence.
4924static void dropPointerConversion(StandardConversionSequence &SCS) {
4925 if (SCS.Second == ICK_Pointer_Conversion) {
4926 SCS.Second = ICK_Identity;
4927 SCS.Third = ICK_Identity;
4928 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4929 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004930}
John McCall5c32be02010-08-24 20:38:10 +00004931
John McCallfec112d2011-09-09 06:11:02 +00004932/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4933/// convert the expression From to an Objective-C pointer type.
4934static ImplicitConversionSequence
4935TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4936 // Do an implicit conversion to 'id'.
4937 QualType Ty = S.Context.getObjCIdType();
4938 ImplicitConversionSequence ICS
4939 = TryImplicitConversion(S, From, Ty,
4940 // FIXME: Are these flags correct?
4941 /*SuppressUserConversions=*/false,
4942 /*AllowExplicit=*/true,
4943 /*InOverloadResolution=*/false,
4944 /*CStyle=*/false,
4945 /*AllowObjCWritebackConversion=*/false);
4946
4947 // Strip off any final conversions to 'id'.
4948 switch (ICS.getKind()) {
4949 case ImplicitConversionSequence::BadConversion:
4950 case ImplicitConversionSequence::AmbiguousConversion:
4951 case ImplicitConversionSequence::EllipsisConversion:
4952 break;
4953
4954 case ImplicitConversionSequence::UserDefinedConversion:
4955 dropPointerConversion(ICS.UserDefined.After);
4956 break;
4957
4958 case ImplicitConversionSequence::StandardConversion:
4959 dropPointerConversion(ICS.Standard);
4960 break;
4961 }
4962
4963 return ICS;
4964}
4965
4966/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4967/// conversion of the expression From to an Objective-C pointer type.
4968ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004969 if (checkPlaceholderForOverload(*this, From))
4970 return ExprError();
4971
John McCall8b07ec22010-05-15 11:32:37 +00004972 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004973 ImplicitConversionSequence ICS =
4974 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004975 if (!ICS.isBad())
4976 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004977 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004978}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004979
Richard Smith8dd34252012-02-04 07:07:42 +00004980/// Determine whether the provided type is an integral type, or an enumeration
4981/// type of a permitted flavor.
4982static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4983 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4984 : T->isIntegralOrUnscopedEnumerationType();
4985}
4986
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004988/// enumeration type.
4989///
4990/// This routine will attempt to convert an expression of class type to an
4991/// integral or enumeration type, if that class type only has a single
4992/// conversion to an integral or enumeration type.
4993///
Douglas Gregor4799d032010-06-30 00:20:43 +00004994/// \param Loc The source location of the construct that requires the
4995/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004996///
Douglas Gregor4799d032010-06-30 00:20:43 +00004997/// \param FromE The expression we're converting from.
4998///
4999/// \param NotIntDiag The diagnostic to be emitted if the expression does not
5000/// have integral or enumeration type.
5001///
5002/// \param IncompleteDiag The diagnostic to be emitted if the expression has
5003/// incomplete class type.
5004///
5005/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5006/// explicit conversion function (because no implicit conversion functions
5007/// were available). This is a recovery mode.
5008///
5009/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5010/// showing which conversion was picked.
5011///
5012/// \param AmbigDiag The diagnostic to be emitted if there is more than one
5013/// conversion function that could convert to integral or enumeration type.
5014///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00005016/// usable conversion function.
5017///
5018/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5019/// function, which may be an extension in this case.
5020///
Richard Smith8dd34252012-02-04 07:07:42 +00005021/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5022/// enumerations should be considered.
5023///
Douglas Gregor4799d032010-06-30 00:20:43 +00005024/// \returns The expression, converted to an integral or enumeration type if
5025/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026ExprResult
John McCallb268a282010-08-23 23:25:46 +00005027Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005028 const PartialDiagnostic &NotIntDiag,
5029 const PartialDiagnostic &IncompleteDiag,
5030 const PartialDiagnostic &ExplicitConvDiag,
5031 const PartialDiagnostic &ExplicitConvNote,
5032 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00005033 const PartialDiagnostic &AmbigNote,
Richard Smith8dd34252012-02-04 07:07:42 +00005034 const PartialDiagnostic &ConvDiag,
5035 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005036 // We can't perform any more checking for type-dependent expressions.
5037 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005038 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039
Eli Friedman1da70392012-01-26 00:26:18 +00005040 // Process placeholders immediately.
5041 if (From->hasPlaceholderType()) {
5042 ExprResult result = CheckPlaceholderExpr(From);
5043 if (result.isInvalid()) return result;
5044 From = result.take();
5045 }
5046
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005047 // If the expression already has integral or enumeration type, we're golden.
5048 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005049 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005050 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005051
5052 // FIXME: Check for missing '()' if T is a function type?
5053
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005055 // expression of integral or enumeration type.
5056 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005057 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithf4c51d92012-02-04 09:53:13 +00005058 if (NotIntDiag.getDiagID())
5059 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005060 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063 // We must have a complete class type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005064 struct IncompleteTypeDiagnoserPartialDiag : IncompleteTypeDiagnoser {
5065 const PartialDiagnostic &PD;
5066
5067 IncompleteTypeDiagnoserPartialDiag(const PartialDiagnostic &PD)
5068 : IncompleteTypeDiagnoser(PD.getDiagID() == 0), PD(PD) {}
5069
5070 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5071 S.Diag(Loc, PD) << T;
5072 }
5073 } IncompleteDiagnoser(IncompleteDiag);
5074
5075 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005076 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005078 // Look for a conversion to an integral or enumeration type.
5079 UnresolvedSet<4> ViableConversions;
5080 UnresolvedSet<4> ExplicitConversions;
5081 const UnresolvedSetImpl *Conversions
5082 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005084 bool HadMultipleCandidates = (Conversions->size() > 1);
5085
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005086 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087 E = Conversions->end();
5088 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005089 ++I) {
5090 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005091 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5092 if (isIntegralOrEnumerationType(
5093 Conversion->getConversionType().getNonReferenceType(),
5094 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005095 if (Conversion->isExplicit())
5096 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5097 else
5098 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5099 }
Richard Smith8dd34252012-02-04 07:07:42 +00005100 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005103 switch (ViableConversions.size()) {
5104 case 0:
Richard Smithf4c51d92012-02-04 09:53:13 +00005105 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005106 DeclAccessPair Found = ExplicitConversions[0];
5107 CXXConversionDecl *Conversion
5108 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005110 // The user probably meant to invoke the given explicit
5111 // conversion; use it.
5112 QualType ConvTy
5113 = Conversion->getConversionType().getNonReferenceType();
5114 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005115 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005117 Diag(Loc, ExplicitConvDiag)
5118 << T << ConvTy
5119 << FixItHint::CreateInsertion(From->getLocStart(),
5120 "static_cast<" + TypeStr + ">(")
5121 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5122 ")");
5123 Diag(Conversion->getLocation(), ExplicitConvNote)
5124 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
5126 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005127 // explicit conversion function.
5128 if (isSFINAEContext())
5129 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005131 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005132 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5133 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005134 if (Result.isInvalid())
5135 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005136 // Record usage of conversion in an implicit cast.
5137 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5138 CK_UserDefinedConversion,
5139 Result.get(), 0,
5140 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005142
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005143 // We'll complain below about a non-integral condition type.
5144 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005145
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005146 case 1: {
5147 // Apply this conversion.
5148 DeclAccessPair Found = ViableConversions[0];
5149 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005150
Douglas Gregor4799d032010-06-30 00:20:43 +00005151 CXXConversionDecl *Conversion
5152 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5153 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005154 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00005155 if (ConvDiag.getDiagID()) {
5156 if (isSFINAEContext())
5157 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158
Douglas Gregor4799d032010-06-30 00:20:43 +00005159 Diag(Loc, ConvDiag)
5160 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005162
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005163 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5164 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005165 if (Result.isInvalid())
5166 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005167 // Record usage of conversion in an implicit cast.
5168 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5169 CK_UserDefinedConversion,
5170 Result.get(), 0,
5171 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005172 break;
5173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005174
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005175 default:
Richard Smithf4c51d92012-02-04 09:53:13 +00005176 if (!AmbigDiag.getDiagID())
5177 return Owned(From);
5178
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005179 Diag(Loc, AmbigDiag)
5180 << T << From->getSourceRange();
5181 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5182 CXXConversionDecl *Conv
5183 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5184 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5185 Diag(Conv->getLocation(), AmbigNote)
5186 << ConvTy->isEnumeralType() << ConvTy;
5187 }
John McCallb268a282010-08-23 23:25:46 +00005188 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005190
Richard Smithf4c51d92012-02-04 09:53:13 +00005191 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5192 NotIntDiag.getDiagID())
5193 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005194
Eli Friedman1da70392012-01-26 00:26:18 +00005195 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005196}
5197
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005198/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005199/// candidate functions, using the given function call arguments. If
5200/// @p SuppressUserConversions, then don't allow user-defined
5201/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005202///
5203/// \para PartialOverloading true if we are performing "partial" overloading
5204/// based on an incomplete set of function arguments. This feature is used by
5205/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005206void
5207Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005208 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005209 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005210 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005211 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005212 bool PartialOverloading,
5213 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005214 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005215 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005216 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005217 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005218 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005219
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005220 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005221 if (!isa<CXXConstructorDecl>(Method)) {
5222 // If we get here, it's because we're calling a member function
5223 // that is named without a member access expression (e.g.,
5224 // "this->f") that was either written explicitly or created
5225 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005226 // function, e.g., X::f(). We use an empty type for the implied
5227 // object argument (C++ [over.call.func]p3), and the acting context
5228 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005229 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005231 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005232 return;
5233 }
5234 // We treat a constructor like a non-member function, since its object
5235 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005236 }
5237
Douglas Gregorff7028a2009-11-13 23:59:09 +00005238 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005239 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005240
Douglas Gregor27381f32009-11-23 12:27:39 +00005241 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005242 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005243
Douglas Gregorffe14e32009-11-14 01:20:54 +00005244 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5245 // C++ [class.copy]p3:
5246 // A member function template is never instantiated to perform the copy
5247 // of a class object to an object of its class type.
5248 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005249 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005250 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005251 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5252 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005253 return;
5254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005256 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005257 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005258 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005259 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005260 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005261 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005262 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005263 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005264
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005265 unsigned NumArgsInProto = Proto->getNumArgs();
5266
5267 // (C++ 13.3.2p2): A candidate function having fewer than m
5268 // parameters is viable only if it has an ellipsis in its parameter
5269 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005270 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005271 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005272 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005273 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005274 return;
5275 }
5276
5277 // (C++ 13.3.2p2): A candidate function having more than m parameters
5278 // is viable only if the (m+1)st parameter has a default argument
5279 // (8.3.6). For the purposes of overload resolution, the
5280 // parameter list is truncated on the right, so that there are
5281 // exactly m parameters.
5282 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005283 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005284 // Not enough arguments.
5285 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005286 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005287 return;
5288 }
5289
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005290 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005291 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005292 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5293 if (CheckCUDATarget(Caller, Function)) {
5294 Candidate.Viable = false;
5295 Candidate.FailureKind = ovl_fail_bad_target;
5296 return;
5297 }
5298
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005299 // Determine the implicit conversion sequences for each of the
5300 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005301 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005302 if (ArgIdx < NumArgsInProto) {
5303 // (C++ 13.3.2p3): for F to be a viable function, there shall
5304 // exist for each argument an implicit conversion sequence
5305 // (13.3.3.1) that converts that argument to the corresponding
5306 // parameter of F.
5307 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005308 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005309 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005310 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005311 /*InOverloadResolution=*/true,
5312 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005313 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005314 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005315 if (Candidate.Conversions[ArgIdx].isBad()) {
5316 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005317 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005318 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005319 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005320 } else {
5321 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5322 // argument for which there is no corresponding parameter is
5323 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005324 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005325 }
5326 }
5327}
5328
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005329/// \brief Add all of the function declarations in the given function set to
5330/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005331void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005332 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005333 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005334 bool SuppressUserConversions,
5335 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005336 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005337 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5338 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005339 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005340 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005341 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005342 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005343 Args.slice(1), CandidateSet,
5344 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005345 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005346 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005347 SuppressUserConversions);
5348 } else {
John McCalla0296f72010-03-19 07:35:19 +00005349 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005350 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5351 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005352 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005353 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005354 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005355 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005356 Args[0]->Classify(Context), Args.slice(1),
5357 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005358 else
John McCalla0296f72010-03-19 07:35:19 +00005359 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005360 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005361 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005362 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005363 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005364}
5365
John McCallf0f1cf02009-11-17 07:50:12 +00005366/// AddMethodCandidate - Adds a named decl (which is some kind of
5367/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005368void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005369 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005370 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005371 Expr **Args, unsigned NumArgs,
5372 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005373 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005374 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005375 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005376
5377 if (isa<UsingShadowDecl>(Decl))
5378 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005379
John McCallf0f1cf02009-11-17 07:50:12 +00005380 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5381 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5382 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005383 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5384 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005385 ObjectType, ObjectClassification,
5386 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005387 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005388 } else {
John McCalla0296f72010-03-19 07:35:19 +00005389 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005390 ObjectType, ObjectClassification,
5391 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005392 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005393 }
5394}
5395
Douglas Gregor436424c2008-11-18 23:14:02 +00005396/// AddMethodCandidate - Adds the given C++ member function to the set
5397/// of candidate functions, using the given function call arguments
5398/// and the object argument (@c Object). For example, in a call
5399/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5400/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5401/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005402/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005403void
John McCalla0296f72010-03-19 07:35:19 +00005404Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005405 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005406 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005407 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005408 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005409 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005410 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005411 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005412 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005413 assert(!isa<CXXConstructorDecl>(Method) &&
5414 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005415
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005416 if (!CandidateSet.isNewCandidate(Method))
5417 return;
5418
Douglas Gregor27381f32009-11-23 12:27:39 +00005419 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005420 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005421
Douglas Gregor436424c2008-11-18 23:14:02 +00005422 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005423 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005424 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005425 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005426 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005427 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005428 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005429
5430 unsigned NumArgsInProto = Proto->getNumArgs();
5431
5432 // (C++ 13.3.2p2): A candidate function having fewer than m
5433 // parameters is viable only if it has an ellipsis in its parameter
5434 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005435 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005436 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005437 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005438 return;
5439 }
5440
5441 // (C++ 13.3.2p2): A candidate function having more than m parameters
5442 // is viable only if the (m+1)st parameter has a default argument
5443 // (8.3.6). For the purposes of overload resolution, the
5444 // parameter list is truncated on the right, so that there are
5445 // exactly m parameters.
5446 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005447 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005448 // Not enough arguments.
5449 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005450 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005451 return;
5452 }
5453
5454 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005455
John McCall6e9f8f62009-12-03 04:06:58 +00005456 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005457 // The implicit object argument is ignored.
5458 Candidate.IgnoreObjectArgument = true;
5459 else {
5460 // Determine the implicit conversion sequence for the object
5461 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005462 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005463 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5464 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005465 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005466 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005467 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005468 return;
5469 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005470 }
5471
5472 // Determine the implicit conversion sequences for each of the
5473 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005474 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005475 if (ArgIdx < NumArgsInProto) {
5476 // (C++ 13.3.2p3): for F to be a viable function, there shall
5477 // exist for each argument an implicit conversion sequence
5478 // (13.3.3.1) that converts that argument to the corresponding
5479 // parameter of F.
5480 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005481 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005482 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005483 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005484 /*InOverloadResolution=*/true,
5485 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005486 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005487 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005488 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005489 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005490 break;
5491 }
5492 } else {
5493 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5494 // argument for which there is no corresponding parameter is
5495 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005496 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005497 }
5498 }
5499}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Douglas Gregor97628d62009-08-21 00:16:32 +00005501/// \brief Add a C++ member function template as a candidate to the candidate
5502/// set, using template argument deduction to produce an appropriate member
5503/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005504void
Douglas Gregor97628d62009-08-21 00:16:32 +00005505Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005506 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005507 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005508 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005509 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005510 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005511 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005512 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005513 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005514 if (!CandidateSet.isNewCandidate(MethodTmpl))
5515 return;
5516
Douglas Gregor97628d62009-08-21 00:16:32 +00005517 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005518 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005519 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005520 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005521 // candidate functions in the usual way.113) A given name can refer to one
5522 // or more function templates and also to a set of overloaded non-template
5523 // functions. In such a case, the candidate functions generated from each
5524 // function template are combined with the set of non-template candidate
5525 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005526 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005527 FunctionDecl *Specialization = 0;
5528 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005529 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5530 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005531 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005532 Candidate.FoundDecl = FoundDecl;
5533 Candidate.Function = MethodTmpl->getTemplatedDecl();
5534 Candidate.Viable = false;
5535 Candidate.FailureKind = ovl_fail_bad_deduction;
5536 Candidate.IsSurrogate = false;
5537 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005538 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005539 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005540 Info);
5541 return;
5542 }
Mike Stump11289f42009-09-09 15:08:12 +00005543
Douglas Gregor97628d62009-08-21 00:16:32 +00005544 // Add the function template specialization produced by template argument
5545 // deduction as a candidate.
5546 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005547 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005548 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005549 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005550 ActingContext, ObjectType, ObjectClassification, Args,
5551 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005552}
5553
Douglas Gregor05155d82009-08-21 23:19:43 +00005554/// \brief Add a C++ function template specialization as a candidate
5555/// in the candidate set, using template argument deduction to produce
5556/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005557void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005558Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005559 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005560 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005561 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005562 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005563 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005564 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5565 return;
5566
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005567 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005568 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005569 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005570 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005571 // candidate functions in the usual way.113) A given name can refer to one
5572 // or more function templates and also to a set of overloaded non-template
5573 // functions. In such a case, the candidate functions generated from each
5574 // function template are combined with the set of non-template candidate
5575 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005576 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005577 FunctionDecl *Specialization = 0;
5578 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005579 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5580 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005581 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005582 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005583 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5584 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005585 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005586 Candidate.IsSurrogate = false;
5587 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005588 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005589 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005590 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005591 return;
5592 }
Mike Stump11289f42009-09-09 15:08:12 +00005593
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005594 // Add the function template specialization produced by template argument
5595 // deduction as a candidate.
5596 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005597 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005598 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005599}
Mike Stump11289f42009-09-09 15:08:12 +00005600
Douglas Gregora1f013e2008-11-07 22:36:19 +00005601/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005602/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005603/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005604/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005605/// (which may or may not be the same type as the type that the
5606/// conversion function produces).
5607void
5608Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005609 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005610 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005611 Expr *From, QualType ToType,
5612 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005613 assert(!Conversion->getDescribedFunctionTemplate() &&
5614 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005615 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005616 if (!CandidateSet.isNewCandidate(Conversion))
5617 return;
5618
Douglas Gregor27381f32009-11-23 12:27:39 +00005619 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005620 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005621
Douglas Gregora1f013e2008-11-07 22:36:19 +00005622 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005623 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005624 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005625 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005626 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005627 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005628 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005629 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005630 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005631 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005632 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005633
Douglas Gregor6affc782010-08-19 15:37:02 +00005634 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005635 // For conversion functions, the function is considered to be a member of
5636 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005637 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005638 //
5639 // Determine the implicit conversion sequence for the implicit
5640 // object parameter.
5641 QualType ImplicitParamType = From->getType();
5642 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5643 ImplicitParamType = FromPtrType->getPointeeType();
5644 CXXRecordDecl *ConversionContext
5645 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005647 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648 = TryObjectArgumentInitialization(*this, From->getType(),
5649 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005650 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005651
John McCall0d1da222010-01-12 00:44:57 +00005652 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005653 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005654 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005655 return;
5656 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005657
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005659 // derived to base as such conversions are given Conversion Rank. They only
5660 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5661 QualType FromCanon
5662 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5663 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5664 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5665 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005666 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005667 return;
5668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669
Douglas Gregora1f013e2008-11-07 22:36:19 +00005670 // To determine what the conversion from the result of calling the
5671 // conversion function to the type we're eventually trying to
5672 // convert to (ToType), we need to synthesize a call to the
5673 // conversion function and attempt copy initialization from it. This
5674 // makes sure that we get the right semantics with respect to
5675 // lvalues/rvalues and the type. Fortunately, we can allocate this
5676 // call on the stack and we don't need its arguments to be
5677 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005678 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005679 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005680 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5681 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005682 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005683 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005684
Richard Smith48d24642011-07-13 22:53:21 +00005685 QualType ConversionType = Conversion->getConversionType();
5686 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005687 Candidate.Viable = false;
5688 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5689 return;
5690 }
5691
Richard Smith48d24642011-07-13 22:53:21 +00005692 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005693
Mike Stump11289f42009-09-09 15:08:12 +00005694 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005695 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5696 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005697 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005698 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005699 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005700 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005701 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005702 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005703 /*InOverloadResolution=*/false,
5704 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005705
John McCall0d1da222010-01-12 00:44:57 +00005706 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005707 case ImplicitConversionSequence::StandardConversion:
5708 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005710 // C++ [over.ics.user]p3:
5711 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005713 // shall have exact match rank.
5714 if (Conversion->getPrimaryTemplate() &&
5715 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5716 Candidate.Viable = false;
5717 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Douglas Gregorcba72b12011-01-21 05:18:22 +00005720 // C++0x [dcl.init.ref]p5:
5721 // In the second case, if the reference is an rvalue reference and
5722 // the second standard conversion sequence of the user-defined
5723 // conversion sequence includes an lvalue-to-rvalue conversion, the
5724 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005726 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5727 Candidate.Viable = false;
5728 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5729 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005730 break;
5731
5732 case ImplicitConversionSequence::BadConversion:
5733 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005734 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005735 break;
5736
5737 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005738 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005739 "Can only end up with a standard conversion sequence or failure");
5740 }
5741}
5742
Douglas Gregor05155d82009-08-21 23:19:43 +00005743/// \brief Adds a conversion function template specialization
5744/// candidate to the overload set, using template argument deduction
5745/// to deduce the template arguments of the conversion function
5746/// template from the type that we are converting to (C++
5747/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005748void
Douglas Gregor05155d82009-08-21 23:19:43 +00005749Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005750 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005751 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005752 Expr *From, QualType ToType,
5753 OverloadCandidateSet &CandidateSet) {
5754 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5755 "Only conversion function templates permitted here");
5756
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005757 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5758 return;
5759
John McCallbc077cf2010-02-08 23:07:23 +00005760 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005761 CXXConversionDecl *Specialization = 0;
5762 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005763 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005764 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005765 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005766 Candidate.FoundDecl = FoundDecl;
5767 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5768 Candidate.Viable = false;
5769 Candidate.FailureKind = ovl_fail_bad_deduction;
5770 Candidate.IsSurrogate = false;
5771 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005772 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005774 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005775 return;
5776 }
Mike Stump11289f42009-09-09 15:08:12 +00005777
Douglas Gregor05155d82009-08-21 23:19:43 +00005778 // Add the conversion function template specialization produced by
5779 // template argument deduction as a candidate.
5780 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005781 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005782 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005783}
5784
Douglas Gregorab7897a2008-11-19 22:57:39 +00005785/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5786/// converts the given @c Object to a function pointer via the
5787/// conversion function @c Conversion, and then attempts to call it
5788/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5789/// the type of function that we'll eventually be calling.
5790void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005791 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005792 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005793 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005794 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005795 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005796 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005797 if (!CandidateSet.isNewCandidate(Conversion))
5798 return;
5799
Douglas Gregor27381f32009-11-23 12:27:39 +00005800 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005801 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005802
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005803 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005804 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005805 Candidate.Function = 0;
5806 Candidate.Surrogate = Conversion;
5807 Candidate.Viable = true;
5808 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005809 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005810 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005811
5812 // Determine the implicit conversion sequence for the implicit
5813 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005814 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005815 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005816 Object->Classify(Context),
5817 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005818 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005819 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005820 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005821 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005822 return;
5823 }
5824
5825 // The first conversion is actually a user-defined conversion whose
5826 // first conversion is ObjectInit's standard conversion (which is
5827 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005828 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005829 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005830 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005831 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005832 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005833 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005834 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005835 = Candidate.Conversions[0].UserDefined.Before;
5836 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5837
Mike Stump11289f42009-09-09 15:08:12 +00005838 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005839 unsigned NumArgsInProto = Proto->getNumArgs();
5840
5841 // (C++ 13.3.2p2): A candidate function having fewer than m
5842 // parameters is viable only if it has an ellipsis in its parameter
5843 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005844 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005845 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005846 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005847 return;
5848 }
5849
5850 // Function types don't have any default arguments, so just check if
5851 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005852 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005853 // Not enough arguments.
5854 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005855 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005856 return;
5857 }
5858
5859 // Determine the implicit conversion sequences for each of the
5860 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005861 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005862 if (ArgIdx < NumArgsInProto) {
5863 // (C++ 13.3.2p3): for F to be a viable function, there shall
5864 // exist for each argument an implicit conversion sequence
5865 // (13.3.3.1) that converts that argument to the corresponding
5866 // parameter of F.
5867 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005868 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005869 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005870 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005871 /*InOverloadResolution=*/false,
5872 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005873 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005874 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005875 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005876 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005877 break;
5878 }
5879 } else {
5880 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5881 // argument for which there is no corresponding parameter is
5882 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005883 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005884 }
5885 }
5886}
5887
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005888/// \brief Add overload candidates for overloaded operators that are
5889/// member functions.
5890///
5891/// Add the overloaded operator candidates that are member functions
5892/// for the operator Op that was used in an operator expression such
5893/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5894/// CandidateSet will store the added overload candidates. (C++
5895/// [over.match.oper]).
5896void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5897 SourceLocation OpLoc,
5898 Expr **Args, unsigned NumArgs,
5899 OverloadCandidateSet& CandidateSet,
5900 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005901 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5902
5903 // C++ [over.match.oper]p3:
5904 // For a unary operator @ with an operand of a type whose
5905 // cv-unqualified version is T1, and for a binary operator @ with
5906 // a left operand of a type whose cv-unqualified version is T1 and
5907 // a right operand of a type whose cv-unqualified version is T2,
5908 // three sets of candidate functions, designated member
5909 // candidates, non-member candidates and built-in candidates, are
5910 // constructed as follows:
5911 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005912
5913 // -- If T1 is a class type, the set of member candidates is the
5914 // result of the qualified lookup of T1::operator@
5915 // (13.3.1.1.1); otherwise, the set of member candidates is
5916 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005917 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005918 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005919 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005920 return;
Mike Stump11289f42009-09-09 15:08:12 +00005921
John McCall27b18f82009-11-17 02:14:36 +00005922 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5923 LookupQualifiedName(Operators, T1Rec->getDecl());
5924 Operators.suppressDiagnostics();
5925
Mike Stump11289f42009-09-09 15:08:12 +00005926 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005927 OperEnd = Operators.end();
5928 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005929 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005930 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005931 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005932 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005933 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005934 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005935}
5936
Douglas Gregora11693b2008-11-12 17:17:38 +00005937/// AddBuiltinCandidate - Add a candidate for a built-in
5938/// operator. ResultTy and ParamTys are the result and parameter types
5939/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005940/// arguments being passed to the candidate. IsAssignmentOperator
5941/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005942/// operator. NumContextualBoolArguments is the number of arguments
5943/// (at the beginning of the argument list) that will be contextually
5944/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005945void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005946 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005947 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005948 bool IsAssignmentOperator,
5949 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005950 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005951 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005952
Douglas Gregora11693b2008-11-12 17:17:38 +00005953 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005954 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005955 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005956 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005957 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005958 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005959 Candidate.BuiltinTypes.ResultTy = ResultTy;
5960 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5961 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5962
5963 // Determine the implicit conversion sequences for each of the
5964 // arguments.
5965 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005966 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005967 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005968 // C++ [over.match.oper]p4:
5969 // For the built-in assignment operators, conversions of the
5970 // left operand are restricted as follows:
5971 // -- no temporaries are introduced to hold the left operand, and
5972 // -- no user-defined conversions are applied to the left
5973 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005974 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005975 //
5976 // We block these conversions by turning off user-defined
5977 // conversions, since that is the only way that initialization of
5978 // a reference to a non-class type can occur from something that
5979 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005980 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005981 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005982 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005983 Candidate.Conversions[ArgIdx]
5984 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005985 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005986 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005987 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005988 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005989 /*InOverloadResolution=*/false,
5990 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005991 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005992 }
John McCall0d1da222010-01-12 00:44:57 +00005993 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005994 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005995 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005996 break;
5997 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005998 }
5999}
6000
6001/// BuiltinCandidateTypeSet - A set of types that will be used for the
6002/// candidate operator functions for built-in operators (C++
6003/// [over.built]). The types are separated into pointer types and
6004/// enumeration types.
6005class BuiltinCandidateTypeSet {
6006 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006007 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006008
6009 /// PointerTypes - The set of pointer types that will be used in the
6010 /// built-in candidates.
6011 TypeSet PointerTypes;
6012
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006013 /// MemberPointerTypes - The set of member pointer types that will be
6014 /// used in the built-in candidates.
6015 TypeSet MemberPointerTypes;
6016
Douglas Gregora11693b2008-11-12 17:17:38 +00006017 /// EnumerationTypes - The set of enumeration types that will be
6018 /// used in the built-in candidates.
6019 TypeSet EnumerationTypes;
6020
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006022 /// candidates.
6023 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006024
6025 /// \brief A flag indicating non-record types are viable candidates
6026 bool HasNonRecordTypes;
6027
6028 /// \brief A flag indicating whether either arithmetic or enumeration types
6029 /// were present in the candidate set.
6030 bool HasArithmeticOrEnumeralTypes;
6031
Douglas Gregor80af3132011-05-21 23:15:46 +00006032 /// \brief A flag indicating whether the nullptr type was present in the
6033 /// candidate set.
6034 bool HasNullPtrType;
6035
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006036 /// Sema - The semantic analysis instance where we are building the
6037 /// candidate type set.
6038 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006039
Douglas Gregora11693b2008-11-12 17:17:38 +00006040 /// Context - The AST context in which we will build the type sets.
6041 ASTContext &Context;
6042
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006043 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6044 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006045 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006046
6047public:
6048 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006049 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006050
Mike Stump11289f42009-09-09 15:08:12 +00006051 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006052 : HasNonRecordTypes(false),
6053 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006054 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006055 SemaRef(SemaRef),
6056 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006057
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006058 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006059 SourceLocation Loc,
6060 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006061 bool AllowExplicitConversions,
6062 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006063
6064 /// pointer_begin - First pointer type found;
6065 iterator pointer_begin() { return PointerTypes.begin(); }
6066
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006067 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006068 iterator pointer_end() { return PointerTypes.end(); }
6069
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006070 /// member_pointer_begin - First member pointer type found;
6071 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6072
6073 /// member_pointer_end - Past the last member pointer type found;
6074 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6075
Douglas Gregora11693b2008-11-12 17:17:38 +00006076 /// enumeration_begin - First enumeration type found;
6077 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6078
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006079 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006080 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006081
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006082 iterator vector_begin() { return VectorTypes.begin(); }
6083 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006084
6085 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6086 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006087 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006088};
6089
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006090/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006091/// the set of pointer types along with any more-qualified variants of
6092/// that type. For example, if @p Ty is "int const *", this routine
6093/// will add "int const *", "int const volatile *", "int const
6094/// restrict *", and "int const volatile restrict *" to the set of
6095/// pointer types. Returns true if the add of @p Ty itself succeeded,
6096/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006097///
6098/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006099bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006100BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6101 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006102
Douglas Gregora11693b2008-11-12 17:17:38 +00006103 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006104 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006105 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006106
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006107 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006108 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006109 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006110 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006111 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006112 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006113 buildObjCPtr = true;
6114 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006115 else
David Blaikie83d382b2011-09-23 05:06:16 +00006116 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006117 }
6118 else
6119 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006120
Sebastian Redl4990a632009-11-18 20:39:26 +00006121 // Don't add qualified variants of arrays. For one, they're not allowed
6122 // (the qualifier would sink to the element type), and for another, the
6123 // only overload situation where it matters is subscript or pointer +- int,
6124 // and those shouldn't have qualifier variants anyway.
6125 if (PointeeTy->isArrayType())
6126 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006127 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00006128 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00006129 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006130 bool hasVolatile = VisibleQuals.hasVolatile();
6131 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006132
John McCall8ccfcb52009-09-24 19:53:00 +00006133 // Iterate through all strict supersets of BaseCVR.
6134 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6135 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006136 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6137 // in the types.
6138 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6139 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00006140 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006141 if (!buildObjCPtr)
6142 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6143 else
6144 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00006145 }
6146
6147 return true;
6148}
6149
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006150/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6151/// to the set of pointer types along with any more-qualified variants of
6152/// that type. For example, if @p Ty is "int const *", this routine
6153/// will add "int const *", "int const volatile *", "int const
6154/// restrict *", and "int const volatile restrict *" to the set of
6155/// pointer types. Returns true if the add of @p Ty itself succeeded,
6156/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006157///
6158/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006159bool
6160BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6161 QualType Ty) {
6162 // Insert this type.
6163 if (!MemberPointerTypes.insert(Ty))
6164 return false;
6165
John McCall8ccfcb52009-09-24 19:53:00 +00006166 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6167 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006168
John McCall8ccfcb52009-09-24 19:53:00 +00006169 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006170 // Don't add qualified variants of arrays. For one, they're not allowed
6171 // (the qualifier would sink to the element type), and for another, the
6172 // only overload situation where it matters is subscript or pointer +- int,
6173 // and those shouldn't have qualifier variants anyway.
6174 if (PointeeTy->isArrayType())
6175 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006176 const Type *ClassTy = PointerTy->getClass();
6177
6178 // Iterate through all strict supersets of the pointee type's CVR
6179 // qualifiers.
6180 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6181 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6182 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006183
John McCall8ccfcb52009-09-24 19:53:00 +00006184 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006185 MemberPointerTypes.insert(
6186 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006187 }
6188
6189 return true;
6190}
6191
Douglas Gregora11693b2008-11-12 17:17:38 +00006192/// AddTypesConvertedFrom - Add each of the types to which the type @p
6193/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006194/// primarily interested in pointer types and enumeration types. We also
6195/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006196/// AllowUserConversions is true if we should look at the conversion
6197/// functions of a class type, and AllowExplicitConversions if we
6198/// should also include the explicit conversion functions of a class
6199/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006200void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006201BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006202 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006203 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006204 bool AllowExplicitConversions,
6205 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006206 // Only deal with canonical types.
6207 Ty = Context.getCanonicalType(Ty);
6208
6209 // Look through reference types; they aren't part of the type of an
6210 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006211 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006212 Ty = RefTy->getPointeeType();
6213
John McCall33ddac02011-01-19 10:06:00 +00006214 // If we're dealing with an array type, decay to the pointer.
6215 if (Ty->isArrayType())
6216 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6217
6218 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006219 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006220
Chandler Carruth00a38332010-12-13 01:44:01 +00006221 // Flag if we ever add a non-record type.
6222 const RecordType *TyRec = Ty->getAs<RecordType>();
6223 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6224
Chandler Carruth00a38332010-12-13 01:44:01 +00006225 // Flag if we encounter an arithmetic type.
6226 HasArithmeticOrEnumeralTypes =
6227 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6228
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006229 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6230 PointerTypes.insert(Ty);
6231 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006232 // Insert our type, and its more-qualified variants, into the set
6233 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006234 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006235 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006236 } else if (Ty->isMemberPointerType()) {
6237 // Member pointers are far easier, since the pointee can't be converted.
6238 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6239 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006240 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006241 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006242 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006243 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006244 // We treat vector types as arithmetic types in many contexts as an
6245 // extension.
6246 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006247 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006248 } else if (Ty->isNullPtrType()) {
6249 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006250 } else if (AllowUserConversions && TyRec) {
6251 // No conversion functions in incomplete types.
6252 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6253 return;
Mike Stump11289f42009-09-09 15:08:12 +00006254
Chandler Carruth00a38332010-12-13 01:44:01 +00006255 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6256 const UnresolvedSetImpl *Conversions
6257 = ClassDecl->getVisibleConversionFunctions();
6258 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6259 E = Conversions->end(); I != E; ++I) {
6260 NamedDecl *D = I.getDecl();
6261 if (isa<UsingShadowDecl>(D))
6262 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006263
Chandler Carruth00a38332010-12-13 01:44:01 +00006264 // Skip conversion function templates; they don't tell us anything
6265 // about which builtin types we can convert to.
6266 if (isa<FunctionTemplateDecl>(D))
6267 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006268
Chandler Carruth00a38332010-12-13 01:44:01 +00006269 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6270 if (AllowExplicitConversions || !Conv->isExplicit()) {
6271 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6272 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006273 }
6274 }
6275 }
6276}
6277
Douglas Gregor84605ae2009-08-24 13:43:27 +00006278/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6279/// the volatile- and non-volatile-qualified assignment operators for the
6280/// given type to the candidate set.
6281static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6282 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006283 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006284 unsigned NumArgs,
6285 OverloadCandidateSet &CandidateSet) {
6286 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006287
Douglas Gregor84605ae2009-08-24 13:43:27 +00006288 // T& operator=(T&, T)
6289 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6290 ParamTypes[1] = T;
6291 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6292 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006293
Douglas Gregor84605ae2009-08-24 13:43:27 +00006294 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6295 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006296 ParamTypes[0]
6297 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006298 ParamTypes[1] = T;
6299 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006300 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006301 }
6302}
Mike Stump11289f42009-09-09 15:08:12 +00006303
Sebastian Redl1054fae2009-10-25 17:03:50 +00006304/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6305/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006306static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6307 Qualifiers VRQuals;
6308 const RecordType *TyRec;
6309 if (const MemberPointerType *RHSMPType =
6310 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006311 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006312 else
6313 TyRec = ArgExpr->getType()->getAs<RecordType>();
6314 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006315 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006316 VRQuals.addVolatile();
6317 VRQuals.addRestrict();
6318 return VRQuals;
6319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006320
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006321 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006322 if (!ClassDecl->hasDefinition())
6323 return VRQuals;
6324
John McCallad371252010-01-20 00:46:10 +00006325 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006326 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006327
John McCallad371252010-01-20 00:46:10 +00006328 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006329 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006330 NamedDecl *D = I.getDecl();
6331 if (isa<UsingShadowDecl>(D))
6332 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6333 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006334 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6335 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6336 CanTy = ResTypeRef->getPointeeType();
6337 // Need to go down the pointer/mempointer chain and add qualifiers
6338 // as see them.
6339 bool done = false;
6340 while (!done) {
6341 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6342 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006343 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006344 CanTy->getAs<MemberPointerType>())
6345 CanTy = ResTypeMPtr->getPointeeType();
6346 else
6347 done = true;
6348 if (CanTy.isVolatileQualified())
6349 VRQuals.addVolatile();
6350 if (CanTy.isRestrictQualified())
6351 VRQuals.addRestrict();
6352 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6353 return VRQuals;
6354 }
6355 }
6356 }
6357 return VRQuals;
6358}
John McCall52872982010-11-13 05:51:15 +00006359
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006360namespace {
John McCall52872982010-11-13 05:51:15 +00006361
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006362/// \brief Helper class to manage the addition of builtin operator overload
6363/// candidates. It provides shared state and utility methods used throughout
6364/// the process, as well as a helper method to add each group of builtin
6365/// operator overloads from the standard to a candidate set.
6366class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006367 // Common instance state available to all overload candidate addition methods.
6368 Sema &S;
6369 Expr **Args;
6370 unsigned NumArgs;
6371 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006372 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006373 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006374 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006375
Chandler Carruthc6586e52010-12-12 10:35:00 +00006376 // Define some constants used to index and iterate over the arithemetic types
6377 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006378 // The "promoted arithmetic types" are the arithmetic
6379 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006380 static const unsigned FirstIntegralType = 3;
6381 static const unsigned LastIntegralType = 18;
6382 static const unsigned FirstPromotedIntegralType = 3,
6383 LastPromotedIntegralType = 9;
6384 static const unsigned FirstPromotedArithmeticType = 0,
6385 LastPromotedArithmeticType = 9;
6386 static const unsigned NumArithmeticTypes = 18;
6387
Chandler Carruthc6586e52010-12-12 10:35:00 +00006388 /// \brief Get the canonical type for a given arithmetic type index.
6389 CanQualType getArithmeticType(unsigned index) {
6390 assert(index < NumArithmeticTypes);
6391 static CanQualType ASTContext::* const
6392 ArithmeticTypes[NumArithmeticTypes] = {
6393 // Start of promoted types.
6394 &ASTContext::FloatTy,
6395 &ASTContext::DoubleTy,
6396 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006397
Chandler Carruthc6586e52010-12-12 10:35:00 +00006398 // Start of integral types.
6399 &ASTContext::IntTy,
6400 &ASTContext::LongTy,
6401 &ASTContext::LongLongTy,
6402 &ASTContext::UnsignedIntTy,
6403 &ASTContext::UnsignedLongTy,
6404 &ASTContext::UnsignedLongLongTy,
6405 // End of promoted types.
6406
6407 &ASTContext::BoolTy,
6408 &ASTContext::CharTy,
6409 &ASTContext::WCharTy,
6410 &ASTContext::Char16Ty,
6411 &ASTContext::Char32Ty,
6412 &ASTContext::SignedCharTy,
6413 &ASTContext::ShortTy,
6414 &ASTContext::UnsignedCharTy,
6415 &ASTContext::UnsignedShortTy,
6416 // End of integral types.
6417 // FIXME: What about complex?
6418 };
6419 return S.Context.*ArithmeticTypes[index];
6420 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006421
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006422 /// \brief Gets the canonical type resulting from the usual arithemetic
6423 /// converions for the given arithmetic types.
6424 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6425 // Accelerator table for performing the usual arithmetic conversions.
6426 // The rules are basically:
6427 // - if either is floating-point, use the wider floating-point
6428 // - if same signedness, use the higher rank
6429 // - if same size, use unsigned of the higher rank
6430 // - use the larger type
6431 // These rules, together with the axiom that higher ranks are
6432 // never smaller, are sufficient to precompute all of these results
6433 // *except* when dealing with signed types of higher rank.
6434 // (we could precompute SLL x UI for all known platforms, but it's
6435 // better not to make any assumptions).
6436 enum PromotedType {
6437 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6438 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006439 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006440 [LastPromotedArithmeticType] = {
6441 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6442 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6443 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6444 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6445 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6446 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6447 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6448 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6449 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6450 };
6451
6452 assert(L < LastPromotedArithmeticType);
6453 assert(R < LastPromotedArithmeticType);
6454 int Idx = ConversionsTable[L][R];
6455
6456 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006457 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006458
6459 // Slow path: we need to compare widths.
6460 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006461 CanQualType LT = getArithmeticType(L),
6462 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006463 unsigned LW = S.Context.getIntWidth(LT),
6464 RW = S.Context.getIntWidth(RT);
6465
6466 // If they're different widths, use the signed type.
6467 if (LW > RW) return LT;
6468 else if (LW < RW) return RT;
6469
6470 // Otherwise, use the unsigned type of the signed type's rank.
6471 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6472 assert(L == SLL || R == SLL);
6473 return S.Context.UnsignedLongLongTy;
6474 }
6475
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006476 /// \brief Helper method to factor out the common pattern of adding overloads
6477 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006478 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6479 bool HasVolatile) {
6480 QualType ParamTypes[2] = {
6481 S.Context.getLValueReferenceType(CandidateTy),
6482 S.Context.IntTy
6483 };
6484
6485 // Non-volatile version.
6486 if (NumArgs == 1)
6487 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6488 else
6489 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6490
6491 // Use a heuristic to reduce number of builtin candidates in the set:
6492 // add volatile version only if there are conversions to a volatile type.
6493 if (HasVolatile) {
6494 ParamTypes[0] =
6495 S.Context.getLValueReferenceType(
6496 S.Context.getVolatileType(CandidateTy));
6497 if (NumArgs == 1)
6498 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6499 else
6500 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6501 }
6502 }
6503
6504public:
6505 BuiltinOperatorOverloadBuilder(
6506 Sema &S, Expr **Args, unsigned NumArgs,
6507 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006508 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006509 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006510 OverloadCandidateSet &CandidateSet)
6511 : S(S), Args(Args), NumArgs(NumArgs),
6512 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006513 HasArithmeticOrEnumeralCandidateType(
6514 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006515 CandidateTypes(CandidateTypes),
6516 CandidateSet(CandidateSet) {
6517 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006518 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006519 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006520 assert(getArithmeticType(LastPromotedIntegralType - 1)
6521 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006522 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006523 assert(getArithmeticType(FirstPromotedArithmeticType)
6524 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006525 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006526 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6527 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006528 "Invalid last promoted arithmetic type");
6529 }
6530
6531 // C++ [over.built]p3:
6532 //
6533 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6534 // is either volatile or empty, there exist candidate operator
6535 // functions of the form
6536 //
6537 // VQ T& operator++(VQ T&);
6538 // T operator++(VQ T&, int);
6539 //
6540 // C++ [over.built]p4:
6541 //
6542 // For every pair (T, VQ), where T is an arithmetic type other
6543 // than bool, and VQ is either volatile or empty, there exist
6544 // candidate operator functions of the form
6545 //
6546 // VQ T& operator--(VQ T&);
6547 // T operator--(VQ T&, int);
6548 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006549 if (!HasArithmeticOrEnumeralCandidateType)
6550 return;
6551
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006552 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6553 Arith < NumArithmeticTypes; ++Arith) {
6554 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006555 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006556 VisibleTypeConversionsQuals.hasVolatile());
6557 }
6558 }
6559
6560 // C++ [over.built]p5:
6561 //
6562 // For every pair (T, VQ), where T is a cv-qualified or
6563 // cv-unqualified object type, and VQ is either volatile or
6564 // empty, there exist candidate operator functions of the form
6565 //
6566 // T*VQ& operator++(T*VQ&);
6567 // T*VQ& operator--(T*VQ&);
6568 // T* operator++(T*VQ&, int);
6569 // T* operator--(T*VQ&, int);
6570 void addPlusPlusMinusMinusPointerOverloads() {
6571 for (BuiltinCandidateTypeSet::iterator
6572 Ptr = CandidateTypes[0].pointer_begin(),
6573 PtrEnd = CandidateTypes[0].pointer_end();
6574 Ptr != PtrEnd; ++Ptr) {
6575 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006576 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006577 continue;
6578
6579 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6580 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6581 VisibleTypeConversionsQuals.hasVolatile()));
6582 }
6583 }
6584
6585 // C++ [over.built]p6:
6586 // For every cv-qualified or cv-unqualified object type T, there
6587 // exist candidate operator functions of the form
6588 //
6589 // T& operator*(T*);
6590 //
6591 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006592 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006593 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006594 // T& operator*(T*);
6595 void addUnaryStarPointerOverloads() {
6596 for (BuiltinCandidateTypeSet::iterator
6597 Ptr = CandidateTypes[0].pointer_begin(),
6598 PtrEnd = CandidateTypes[0].pointer_end();
6599 Ptr != PtrEnd; ++Ptr) {
6600 QualType ParamTy = *Ptr;
6601 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006602 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6603 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604
Douglas Gregor02824322011-01-26 19:30:28 +00006605 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6606 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6607 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006608
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006609 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6610 &ParamTy, Args, 1, CandidateSet);
6611 }
6612 }
6613
6614 // C++ [over.built]p9:
6615 // For every promoted arithmetic type T, there exist candidate
6616 // operator functions of the form
6617 //
6618 // T operator+(T);
6619 // T operator-(T);
6620 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006621 if (!HasArithmeticOrEnumeralCandidateType)
6622 return;
6623
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006624 for (unsigned Arith = FirstPromotedArithmeticType;
6625 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006626 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006627 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6628 }
6629
6630 // Extension: We also add these operators for vector types.
6631 for (BuiltinCandidateTypeSet::iterator
6632 Vec = CandidateTypes[0].vector_begin(),
6633 VecEnd = CandidateTypes[0].vector_end();
6634 Vec != VecEnd; ++Vec) {
6635 QualType VecTy = *Vec;
6636 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6637 }
6638 }
6639
6640 // C++ [over.built]p8:
6641 // For every type T, there exist candidate operator functions of
6642 // the form
6643 //
6644 // T* operator+(T*);
6645 void addUnaryPlusPointerOverloads() {
6646 for (BuiltinCandidateTypeSet::iterator
6647 Ptr = CandidateTypes[0].pointer_begin(),
6648 PtrEnd = CandidateTypes[0].pointer_end();
6649 Ptr != PtrEnd; ++Ptr) {
6650 QualType ParamTy = *Ptr;
6651 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6652 }
6653 }
6654
6655 // C++ [over.built]p10:
6656 // For every promoted integral type T, there exist candidate
6657 // operator functions of the form
6658 //
6659 // T operator~(T);
6660 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006661 if (!HasArithmeticOrEnumeralCandidateType)
6662 return;
6663
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006664 for (unsigned Int = FirstPromotedIntegralType;
6665 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006666 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006667 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6668 }
6669
6670 // Extension: We also add this operator for vector types.
6671 for (BuiltinCandidateTypeSet::iterator
6672 Vec = CandidateTypes[0].vector_begin(),
6673 VecEnd = CandidateTypes[0].vector_end();
6674 Vec != VecEnd; ++Vec) {
6675 QualType VecTy = *Vec;
6676 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6677 }
6678 }
6679
6680 // C++ [over.match.oper]p16:
6681 // For every pointer to member type T, there exist candidate operator
6682 // functions of the form
6683 //
6684 // bool operator==(T,T);
6685 // bool operator!=(T,T);
6686 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6687 /// Set of (canonical) types that we've already handled.
6688 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6689
6690 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6691 for (BuiltinCandidateTypeSet::iterator
6692 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6693 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6694 MemPtr != MemPtrEnd;
6695 ++MemPtr) {
6696 // Don't add the same builtin candidate twice.
6697 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6698 continue;
6699
6700 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6701 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6702 CandidateSet);
6703 }
6704 }
6705 }
6706
6707 // C++ [over.built]p15:
6708 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006709 // For every T, where T is an enumeration type, a pointer type, or
6710 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006711 //
6712 // bool operator<(T, T);
6713 // bool operator>(T, T);
6714 // bool operator<=(T, T);
6715 // bool operator>=(T, T);
6716 // bool operator==(T, T);
6717 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006718 void addRelationalPointerOrEnumeralOverloads() {
6719 // C++ [over.built]p1:
6720 // If there is a user-written candidate with the same name and parameter
6721 // types as a built-in candidate operator function, the built-in operator
6722 // function is hidden and is not included in the set of candidate
6723 // functions.
6724 //
6725 // The text is actually in a note, but if we don't implement it then we end
6726 // up with ambiguities when the user provides an overloaded operator for
6727 // an enumeration type. Note that only enumeration types have this problem,
6728 // so we track which enumeration types we've seen operators for. Also, the
6729 // only other overloaded operator with enumeration argumenst, operator=,
6730 // cannot be overloaded for enumeration types, so this is the only place
6731 // where we must suppress candidates like this.
6732 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6733 UserDefinedBinaryOperators;
6734
6735 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6736 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6737 CandidateTypes[ArgIdx].enumeration_end()) {
6738 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6739 CEnd = CandidateSet.end();
6740 C != CEnd; ++C) {
6741 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6742 continue;
6743
6744 QualType FirstParamType =
6745 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6746 QualType SecondParamType =
6747 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6748
6749 // Skip if either parameter isn't of enumeral type.
6750 if (!FirstParamType->isEnumeralType() ||
6751 !SecondParamType->isEnumeralType())
6752 continue;
6753
6754 // Add this operator to the set of known user-defined operators.
6755 UserDefinedBinaryOperators.insert(
6756 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6757 S.Context.getCanonicalType(SecondParamType)));
6758 }
6759 }
6760 }
6761
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006762 /// Set of (canonical) types that we've already handled.
6763 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6764
6765 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6766 for (BuiltinCandidateTypeSet::iterator
6767 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6768 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6769 Ptr != PtrEnd; ++Ptr) {
6770 // Don't add the same builtin candidate twice.
6771 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6772 continue;
6773
6774 QualType ParamTypes[2] = { *Ptr, *Ptr };
6775 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6776 CandidateSet);
6777 }
6778 for (BuiltinCandidateTypeSet::iterator
6779 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6780 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6781 Enum != EnumEnd; ++Enum) {
6782 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6783
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006784 // Don't add the same builtin candidate twice, or if a user defined
6785 // candidate exists.
6786 if (!AddedTypes.insert(CanonType) ||
6787 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6788 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006789 continue;
6790
6791 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006792 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6793 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006794 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006795
6796 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6797 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6798 if (AddedTypes.insert(NullPtrTy) &&
6799 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6800 NullPtrTy))) {
6801 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6802 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6803 CandidateSet);
6804 }
6805 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006806 }
6807 }
6808
6809 // C++ [over.built]p13:
6810 //
6811 // For every cv-qualified or cv-unqualified object type T
6812 // there exist candidate operator functions of the form
6813 //
6814 // T* operator+(T*, ptrdiff_t);
6815 // T& operator[](T*, ptrdiff_t); [BELOW]
6816 // T* operator-(T*, ptrdiff_t);
6817 // T* operator+(ptrdiff_t, T*);
6818 // T& operator[](ptrdiff_t, T*); [BELOW]
6819 //
6820 // C++ [over.built]p14:
6821 //
6822 // For every T, where T is a pointer to object type, there
6823 // exist candidate operator functions of the form
6824 //
6825 // ptrdiff_t operator-(T, T);
6826 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6827 /// Set of (canonical) types that we've already handled.
6828 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6829
6830 for (int Arg = 0; Arg < 2; ++Arg) {
6831 QualType AsymetricParamTypes[2] = {
6832 S.Context.getPointerDiffType(),
6833 S.Context.getPointerDiffType(),
6834 };
6835 for (BuiltinCandidateTypeSet::iterator
6836 Ptr = CandidateTypes[Arg].pointer_begin(),
6837 PtrEnd = CandidateTypes[Arg].pointer_end();
6838 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006839 QualType PointeeTy = (*Ptr)->getPointeeType();
6840 if (!PointeeTy->isObjectType())
6841 continue;
6842
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006843 AsymetricParamTypes[Arg] = *Ptr;
6844 if (Arg == 0 || Op == OO_Plus) {
6845 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6846 // T* operator+(ptrdiff_t, T*);
6847 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6848 CandidateSet);
6849 }
6850 if (Op == OO_Minus) {
6851 // ptrdiff_t operator-(T, T);
6852 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6853 continue;
6854
6855 QualType ParamTypes[2] = { *Ptr, *Ptr };
6856 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6857 Args, 2, CandidateSet);
6858 }
6859 }
6860 }
6861 }
6862
6863 // C++ [over.built]p12:
6864 //
6865 // For every pair of promoted arithmetic types L and R, there
6866 // exist candidate operator functions of the form
6867 //
6868 // LR operator*(L, R);
6869 // LR operator/(L, R);
6870 // LR operator+(L, R);
6871 // LR operator-(L, R);
6872 // bool operator<(L, R);
6873 // bool operator>(L, R);
6874 // bool operator<=(L, R);
6875 // bool operator>=(L, R);
6876 // bool operator==(L, R);
6877 // bool operator!=(L, R);
6878 //
6879 // where LR is the result of the usual arithmetic conversions
6880 // between types L and R.
6881 //
6882 // C++ [over.built]p24:
6883 //
6884 // For every pair of promoted arithmetic types L and R, there exist
6885 // candidate operator functions of the form
6886 //
6887 // LR operator?(bool, L, R);
6888 //
6889 // where LR is the result of the usual arithmetic conversions
6890 // between types L and R.
6891 // Our candidates ignore the first parameter.
6892 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006893 if (!HasArithmeticOrEnumeralCandidateType)
6894 return;
6895
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006896 for (unsigned Left = FirstPromotedArithmeticType;
6897 Left < LastPromotedArithmeticType; ++Left) {
6898 for (unsigned Right = FirstPromotedArithmeticType;
6899 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006900 QualType LandR[2] = { getArithmeticType(Left),
6901 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006902 QualType Result =
6903 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006904 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006905 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6906 }
6907 }
6908
6909 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6910 // conditional operator for vector types.
6911 for (BuiltinCandidateTypeSet::iterator
6912 Vec1 = CandidateTypes[0].vector_begin(),
6913 Vec1End = CandidateTypes[0].vector_end();
6914 Vec1 != Vec1End; ++Vec1) {
6915 for (BuiltinCandidateTypeSet::iterator
6916 Vec2 = CandidateTypes[1].vector_begin(),
6917 Vec2End = CandidateTypes[1].vector_end();
6918 Vec2 != Vec2End; ++Vec2) {
6919 QualType LandR[2] = { *Vec1, *Vec2 };
6920 QualType Result = S.Context.BoolTy;
6921 if (!isComparison) {
6922 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6923 Result = *Vec1;
6924 else
6925 Result = *Vec2;
6926 }
6927
6928 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6929 }
6930 }
6931 }
6932
6933 // C++ [over.built]p17:
6934 //
6935 // For every pair of promoted integral types L and R, there
6936 // exist candidate operator functions of the form
6937 //
6938 // LR operator%(L, R);
6939 // LR operator&(L, R);
6940 // LR operator^(L, R);
6941 // LR operator|(L, R);
6942 // L operator<<(L, R);
6943 // L operator>>(L, R);
6944 //
6945 // where LR is the result of the usual arithmetic conversions
6946 // between types L and R.
6947 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006948 if (!HasArithmeticOrEnumeralCandidateType)
6949 return;
6950
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006951 for (unsigned Left = FirstPromotedIntegralType;
6952 Left < LastPromotedIntegralType; ++Left) {
6953 for (unsigned Right = FirstPromotedIntegralType;
6954 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006955 QualType LandR[2] = { getArithmeticType(Left),
6956 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006957 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6958 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006959 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006960 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6961 }
6962 }
6963 }
6964
6965 // C++ [over.built]p20:
6966 //
6967 // For every pair (T, VQ), where T is an enumeration or
6968 // pointer to member type and VQ is either volatile or
6969 // empty, there exist candidate operator functions of the form
6970 //
6971 // VQ T& operator=(VQ T&, T);
6972 void addAssignmentMemberPointerOrEnumeralOverloads() {
6973 /// Set of (canonical) types that we've already handled.
6974 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6975
6976 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6977 for (BuiltinCandidateTypeSet::iterator
6978 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6979 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6980 Enum != EnumEnd; ++Enum) {
6981 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6982 continue;
6983
6984 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6985 CandidateSet);
6986 }
6987
6988 for (BuiltinCandidateTypeSet::iterator
6989 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6990 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6991 MemPtr != MemPtrEnd; ++MemPtr) {
6992 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6993 continue;
6994
6995 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6996 CandidateSet);
6997 }
6998 }
6999 }
7000
7001 // C++ [over.built]p19:
7002 //
7003 // For every pair (T, VQ), where T is any type and VQ is either
7004 // volatile or empty, there exist candidate operator functions
7005 // of the form
7006 //
7007 // T*VQ& operator=(T*VQ&, T*);
7008 //
7009 // C++ [over.built]p21:
7010 //
7011 // For every pair (T, VQ), where T is a cv-qualified or
7012 // cv-unqualified object type and VQ is either volatile or
7013 // empty, there exist candidate operator functions of the form
7014 //
7015 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7016 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7017 void addAssignmentPointerOverloads(bool isEqualOp) {
7018 /// Set of (canonical) types that we've already handled.
7019 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7020
7021 for (BuiltinCandidateTypeSet::iterator
7022 Ptr = CandidateTypes[0].pointer_begin(),
7023 PtrEnd = CandidateTypes[0].pointer_end();
7024 Ptr != PtrEnd; ++Ptr) {
7025 // If this is operator=, keep track of the builtin candidates we added.
7026 if (isEqualOp)
7027 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007028 else if (!(*Ptr)->getPointeeType()->isObjectType())
7029 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007030
7031 // non-volatile version
7032 QualType ParamTypes[2] = {
7033 S.Context.getLValueReferenceType(*Ptr),
7034 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7035 };
7036 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7037 /*IsAssigmentOperator=*/ isEqualOp);
7038
7039 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7040 VisibleTypeConversionsQuals.hasVolatile()) {
7041 // volatile version
7042 ParamTypes[0] =
7043 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7044 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7045 /*IsAssigmentOperator=*/isEqualOp);
7046 }
7047 }
7048
7049 if (isEqualOp) {
7050 for (BuiltinCandidateTypeSet::iterator
7051 Ptr = CandidateTypes[1].pointer_begin(),
7052 PtrEnd = CandidateTypes[1].pointer_end();
7053 Ptr != PtrEnd; ++Ptr) {
7054 // Make sure we don't add the same candidate twice.
7055 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7056 continue;
7057
Chandler Carruth8e543b32010-12-12 08:17:55 +00007058 QualType ParamTypes[2] = {
7059 S.Context.getLValueReferenceType(*Ptr),
7060 *Ptr,
7061 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007062
7063 // non-volatile version
7064 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7065 /*IsAssigmentOperator=*/true);
7066
7067 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7068 VisibleTypeConversionsQuals.hasVolatile()) {
7069 // volatile version
7070 ParamTypes[0] =
7071 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007072 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7073 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007074 }
7075 }
7076 }
7077 }
7078
7079 // C++ [over.built]p18:
7080 //
7081 // For every triple (L, VQ, R), where L is an arithmetic type,
7082 // VQ is either volatile or empty, and R is a promoted
7083 // arithmetic type, there exist candidate operator functions of
7084 // the form
7085 //
7086 // VQ L& operator=(VQ L&, R);
7087 // VQ L& operator*=(VQ L&, R);
7088 // VQ L& operator/=(VQ L&, R);
7089 // VQ L& operator+=(VQ L&, R);
7090 // VQ L& operator-=(VQ L&, R);
7091 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007092 if (!HasArithmeticOrEnumeralCandidateType)
7093 return;
7094
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007095 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7096 for (unsigned Right = FirstPromotedArithmeticType;
7097 Right < LastPromotedArithmeticType; ++Right) {
7098 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007099 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007100
7101 // Add this built-in operator as a candidate (VQ is empty).
7102 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007103 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007104 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7105 /*IsAssigmentOperator=*/isEqualOp);
7106
7107 // Add this built-in operator as a candidate (VQ is 'volatile').
7108 if (VisibleTypeConversionsQuals.hasVolatile()) {
7109 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007110 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007111 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7113 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007114 /*IsAssigmentOperator=*/isEqualOp);
7115 }
7116 }
7117 }
7118
7119 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7120 for (BuiltinCandidateTypeSet::iterator
7121 Vec1 = CandidateTypes[0].vector_begin(),
7122 Vec1End = CandidateTypes[0].vector_end();
7123 Vec1 != Vec1End; ++Vec1) {
7124 for (BuiltinCandidateTypeSet::iterator
7125 Vec2 = CandidateTypes[1].vector_begin(),
7126 Vec2End = CandidateTypes[1].vector_end();
7127 Vec2 != Vec2End; ++Vec2) {
7128 QualType ParamTypes[2];
7129 ParamTypes[1] = *Vec2;
7130 // Add this built-in operator as a candidate (VQ is empty).
7131 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7132 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7133 /*IsAssigmentOperator=*/isEqualOp);
7134
7135 // Add this built-in operator as a candidate (VQ is 'volatile').
7136 if (VisibleTypeConversionsQuals.hasVolatile()) {
7137 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7138 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007139 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7140 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007141 /*IsAssigmentOperator=*/isEqualOp);
7142 }
7143 }
7144 }
7145 }
7146
7147 // C++ [over.built]p22:
7148 //
7149 // For every triple (L, VQ, R), where L is an integral type, VQ
7150 // is either volatile or empty, and R is a promoted integral
7151 // type, there exist candidate operator functions of the form
7152 //
7153 // VQ L& operator%=(VQ L&, R);
7154 // VQ L& operator<<=(VQ L&, R);
7155 // VQ L& operator>>=(VQ L&, R);
7156 // VQ L& operator&=(VQ L&, R);
7157 // VQ L& operator^=(VQ L&, R);
7158 // VQ L& operator|=(VQ L&, R);
7159 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007160 if (!HasArithmeticOrEnumeralCandidateType)
7161 return;
7162
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007163 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7164 for (unsigned Right = FirstPromotedIntegralType;
7165 Right < LastPromotedIntegralType; ++Right) {
7166 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007167 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007168
7169 // Add this built-in operator as a candidate (VQ is empty).
7170 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007171 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7173 if (VisibleTypeConversionsQuals.hasVolatile()) {
7174 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007175 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007176 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7177 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7178 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7179 CandidateSet);
7180 }
7181 }
7182 }
7183 }
7184
7185 // C++ [over.operator]p23:
7186 //
7187 // There also exist candidate operator functions of the form
7188 //
7189 // bool operator!(bool);
7190 // bool operator&&(bool, bool);
7191 // bool operator||(bool, bool);
7192 void addExclaimOverload() {
7193 QualType ParamTy = S.Context.BoolTy;
7194 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7195 /*IsAssignmentOperator=*/false,
7196 /*NumContextualBoolArguments=*/1);
7197 }
7198 void addAmpAmpOrPipePipeOverload() {
7199 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7200 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7201 /*IsAssignmentOperator=*/false,
7202 /*NumContextualBoolArguments=*/2);
7203 }
7204
7205 // C++ [over.built]p13:
7206 //
7207 // For every cv-qualified or cv-unqualified object type T there
7208 // exist candidate operator functions of the form
7209 //
7210 // T* operator+(T*, ptrdiff_t); [ABOVE]
7211 // T& operator[](T*, ptrdiff_t);
7212 // T* operator-(T*, ptrdiff_t); [ABOVE]
7213 // T* operator+(ptrdiff_t, T*); [ABOVE]
7214 // T& operator[](ptrdiff_t, T*);
7215 void addSubscriptOverloads() {
7216 for (BuiltinCandidateTypeSet::iterator
7217 Ptr = CandidateTypes[0].pointer_begin(),
7218 PtrEnd = CandidateTypes[0].pointer_end();
7219 Ptr != PtrEnd; ++Ptr) {
7220 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7221 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007222 if (!PointeeType->isObjectType())
7223 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007224
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007225 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7226
7227 // T& operator[](T*, ptrdiff_t)
7228 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7229 }
7230
7231 for (BuiltinCandidateTypeSet::iterator
7232 Ptr = CandidateTypes[1].pointer_begin(),
7233 PtrEnd = CandidateTypes[1].pointer_end();
7234 Ptr != PtrEnd; ++Ptr) {
7235 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7236 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007237 if (!PointeeType->isObjectType())
7238 continue;
7239
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007240 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7241
7242 // T& operator[](ptrdiff_t, T*)
7243 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7244 }
7245 }
7246
7247 // C++ [over.built]p11:
7248 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7249 // C1 is the same type as C2 or is a derived class of C2, T is an object
7250 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7251 // there exist candidate operator functions of the form
7252 //
7253 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7254 //
7255 // where CV12 is the union of CV1 and CV2.
7256 void addArrowStarOverloads() {
7257 for (BuiltinCandidateTypeSet::iterator
7258 Ptr = CandidateTypes[0].pointer_begin(),
7259 PtrEnd = CandidateTypes[0].pointer_end();
7260 Ptr != PtrEnd; ++Ptr) {
7261 QualType C1Ty = (*Ptr);
7262 QualType C1;
7263 QualifierCollector Q1;
7264 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7265 if (!isa<RecordType>(C1))
7266 continue;
7267 // heuristic to reduce number of builtin candidates in the set.
7268 // Add volatile/restrict version only if there are conversions to a
7269 // volatile/restrict type.
7270 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7271 continue;
7272 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7273 continue;
7274 for (BuiltinCandidateTypeSet::iterator
7275 MemPtr = CandidateTypes[1].member_pointer_begin(),
7276 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7277 MemPtr != MemPtrEnd; ++MemPtr) {
7278 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7279 QualType C2 = QualType(mptr->getClass(), 0);
7280 C2 = C2.getUnqualifiedType();
7281 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7282 break;
7283 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7284 // build CV12 T&
7285 QualType T = mptr->getPointeeType();
7286 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7287 T.isVolatileQualified())
7288 continue;
7289 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7290 T.isRestrictQualified())
7291 continue;
7292 T = Q1.apply(S.Context, T);
7293 QualType ResultTy = S.Context.getLValueReferenceType(T);
7294 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7295 }
7296 }
7297 }
7298
7299 // Note that we don't consider the first argument, since it has been
7300 // contextually converted to bool long ago. The candidates below are
7301 // therefore added as binary.
7302 //
7303 // C++ [over.built]p25:
7304 // For every type T, where T is a pointer, pointer-to-member, or scoped
7305 // enumeration type, there exist candidate operator functions of the form
7306 //
7307 // T operator?(bool, T, T);
7308 //
7309 void addConditionalOperatorOverloads() {
7310 /// Set of (canonical) types that we've already handled.
7311 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7312
7313 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7314 for (BuiltinCandidateTypeSet::iterator
7315 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7316 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7317 Ptr != PtrEnd; ++Ptr) {
7318 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7319 continue;
7320
7321 QualType ParamTypes[2] = { *Ptr, *Ptr };
7322 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7323 }
7324
7325 for (BuiltinCandidateTypeSet::iterator
7326 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7327 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7328 MemPtr != MemPtrEnd; ++MemPtr) {
7329 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7330 continue;
7331
7332 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7333 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7334 }
7335
David Blaikiebbafb8a2012-03-11 07:00:24 +00007336 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007337 for (BuiltinCandidateTypeSet::iterator
7338 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7339 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7340 Enum != EnumEnd; ++Enum) {
7341 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7342 continue;
7343
7344 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7345 continue;
7346
7347 QualType ParamTypes[2] = { *Enum, *Enum };
7348 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7349 }
7350 }
7351 }
7352 }
7353};
7354
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007355} // end anonymous namespace
7356
7357/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7358/// operator overloads to the candidate set (C++ [over.built]), based
7359/// on the operator @p Op and the arguments given. For example, if the
7360/// operator is a binary '+', this routine might add "int
7361/// operator+(int, int)" to cover integer addition.
7362void
7363Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7364 SourceLocation OpLoc,
7365 Expr **Args, unsigned NumArgs,
7366 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007367 // Find all of the types that the arguments can convert to, but only
7368 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007369 // that make use of these types. Also record whether we encounter non-record
7370 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007371 Qualifiers VisibleTypeConversionsQuals;
7372 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007373 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7374 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007375
7376 bool HasNonRecordCandidateType = false;
7377 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007378 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007379 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7380 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7381 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7382 OpLoc,
7383 true,
7384 (Op == OO_Exclaim ||
7385 Op == OO_AmpAmp ||
7386 Op == OO_PipePipe),
7387 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007388 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7389 CandidateTypes[ArgIdx].hasNonRecordTypes();
7390 HasArithmeticOrEnumeralCandidateType =
7391 HasArithmeticOrEnumeralCandidateType ||
7392 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007393 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007394
Chandler Carruth00a38332010-12-13 01:44:01 +00007395 // Exit early when no non-record types have been added to the candidate set
7396 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007397 //
7398 // We can't exit early for !, ||, or &&, since there we have always have
7399 // 'bool' overloads.
7400 if (!HasNonRecordCandidateType &&
7401 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007402 return;
7403
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007404 // Setup an object to manage the common state for building overloads.
7405 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7406 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007407 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007408 CandidateTypes, CandidateSet);
7409
7410 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007411 switch (Op) {
7412 case OO_None:
7413 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007414 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007415
Chandler Carruth5184de02010-12-12 08:51:33 +00007416 case OO_New:
7417 case OO_Delete:
7418 case OO_Array_New:
7419 case OO_Array_Delete:
7420 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007421 llvm_unreachable(
7422 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007423
7424 case OO_Comma:
7425 case OO_Arrow:
7426 // C++ [over.match.oper]p3:
7427 // -- For the operator ',', the unary operator '&', or the
7428 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007429 break;
7430
7431 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007432 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007433 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007434 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007435
7436 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007437 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007438 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007439 } else {
7440 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7441 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7442 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007443 break;
7444
Chandler Carruth5184de02010-12-12 08:51:33 +00007445 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007446 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007447 OpBuilder.addUnaryStarPointerOverloads();
7448 else
7449 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7450 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007451
Chandler Carruth5184de02010-12-12 08:51:33 +00007452 case OO_Slash:
7453 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007454 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007455
7456 case OO_PlusPlus:
7457 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007458 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7459 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007460 break;
7461
Douglas Gregor84605ae2009-08-24 13:43:27 +00007462 case OO_EqualEqual:
7463 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007464 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007465 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007466
Douglas Gregora11693b2008-11-12 17:17:38 +00007467 case OO_Less:
7468 case OO_Greater:
7469 case OO_LessEqual:
7470 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007471 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007472 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7473 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007474
Douglas Gregora11693b2008-11-12 17:17:38 +00007475 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007476 case OO_Caret:
7477 case OO_Pipe:
7478 case OO_LessLess:
7479 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007480 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007481 break;
7482
Chandler Carruth5184de02010-12-12 08:51:33 +00007483 case OO_Amp: // '&' is either unary or binary
7484 if (NumArgs == 1)
7485 // C++ [over.match.oper]p3:
7486 // -- For the operator ',', the unary operator '&', or the
7487 // operator '->', the built-in candidates set is empty.
7488 break;
7489
7490 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7491 break;
7492
7493 case OO_Tilde:
7494 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7495 break;
7496
Douglas Gregora11693b2008-11-12 17:17:38 +00007497 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007498 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007499 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007500
7501 case OO_PlusEqual:
7502 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007503 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007504 // Fall through.
7505
7506 case OO_StarEqual:
7507 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007508 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007509 break;
7510
7511 case OO_PercentEqual:
7512 case OO_LessLessEqual:
7513 case OO_GreaterGreaterEqual:
7514 case OO_AmpEqual:
7515 case OO_CaretEqual:
7516 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007517 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007518 break;
7519
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 case OO_Exclaim:
7521 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007522 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007523
Douglas Gregora11693b2008-11-12 17:17:38 +00007524 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007525 case OO_PipePipe:
7526 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007527 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007528
7529 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007530 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007531 break;
7532
7533 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007534 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007535 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007536
7537 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007538 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007539 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7540 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007541 }
7542}
7543
Douglas Gregore254f902009-02-04 00:32:51 +00007544/// \brief Add function candidates found via argument-dependent lookup
7545/// to the set of overloading candidates.
7546///
7547/// This routine performs argument-dependent name lookup based on the
7548/// given function name (which may also be an operator name) and adds
7549/// all of the overload candidates found by ADL to the overload
7550/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007551void
Douglas Gregore254f902009-02-04 00:32:51 +00007552Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007553 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007554 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007555 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007556 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007557 bool PartialOverloading,
7558 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007559 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007560
John McCall91f61fc2010-01-26 06:04:06 +00007561 // FIXME: This approach for uniquing ADL results (and removing
7562 // redundant candidates from the set) relies on pointer-equality,
7563 // which means we need to key off the canonical decl. However,
7564 // always going back to the canonical decl might not get us the
7565 // right set of default arguments. What default arguments are
7566 // we supposed to consider on ADL candidates, anyway?
7567
Douglas Gregorcabea402009-09-22 15:41:20 +00007568 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007569 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007570 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007571
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007572 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007573 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7574 CandEnd = CandidateSet.end();
7575 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007576 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007577 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007578 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007579 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007580 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007581
7582 // For each of the ADL candidates we found, add it to the overload
7583 // set.
John McCall8fe68082010-01-26 07:16:45 +00007584 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007585 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007586 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007587 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007588 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007589
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007590 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7591 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007592 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007593 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007594 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007595 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007596 }
Douglas Gregore254f902009-02-04 00:32:51 +00007597}
7598
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007599/// isBetterOverloadCandidate - Determines whether the first overload
7600/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007601bool
John McCall5c32be02010-08-24 20:38:10 +00007602isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007603 const OverloadCandidate &Cand1,
7604 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007605 SourceLocation Loc,
7606 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007607 // Define viable functions to be better candidates than non-viable
7608 // functions.
7609 if (!Cand2.Viable)
7610 return Cand1.Viable;
7611 else if (!Cand1.Viable)
7612 return false;
7613
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007614 // C++ [over.match.best]p1:
7615 //
7616 // -- if F is a static member function, ICS1(F) is defined such
7617 // that ICS1(F) is neither better nor worse than ICS1(G) for
7618 // any function G, and, symmetrically, ICS1(G) is neither
7619 // better nor worse than ICS1(F).
7620 unsigned StartArg = 0;
7621 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7622 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007623
Douglas Gregord3cb3562009-07-07 23:38:56 +00007624 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007625 // A viable function F1 is defined to be a better function than another
7626 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007627 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007628 unsigned NumArgs = Cand1.NumConversions;
7629 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007630 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007631 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007632 switch (CompareImplicitConversionSequences(S,
7633 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007634 Cand2.Conversions[ArgIdx])) {
7635 case ImplicitConversionSequence::Better:
7636 // Cand1 has a better conversion sequence.
7637 HasBetterConversion = true;
7638 break;
7639
7640 case ImplicitConversionSequence::Worse:
7641 // Cand1 can't be better than Cand2.
7642 return false;
7643
7644 case ImplicitConversionSequence::Indistinguishable:
7645 // Do nothing.
7646 break;
7647 }
7648 }
7649
Mike Stump11289f42009-09-09 15:08:12 +00007650 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007651 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007652 if (HasBetterConversion)
7653 return true;
7654
Mike Stump11289f42009-09-09 15:08:12 +00007655 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007656 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007657 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007658 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7659 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007660
7661 // -- F1 and F2 are function template specializations, and the function
7662 // template for F1 is more specialized than the template for F2
7663 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007664 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007665 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007666 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007667 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007668 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7669 Cand2.Function->getPrimaryTemplate(),
7670 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007671 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007672 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007673 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007674 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676
Douglas Gregora1f013e2008-11-07 22:36:19 +00007677 // -- the context is an initialization by user-defined conversion
7678 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7679 // from the return type of F1 to the destination type (i.e.,
7680 // the type of the entity being initialized) is a better
7681 // conversion sequence than the standard conversion sequence
7682 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007683 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007684 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007685 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007686 // First check whether we prefer one of the conversion functions over the
7687 // other. This only distinguishes the results in non-standard, extension
7688 // cases such as the conversion from a lambda closure type to a function
7689 // pointer or block.
7690 ImplicitConversionSequence::CompareKind FuncResult
7691 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7692 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7693 return FuncResult;
7694
John McCall5c32be02010-08-24 20:38:10 +00007695 switch (CompareStandardConversionSequences(S,
7696 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007697 Cand2.FinalConversion)) {
7698 case ImplicitConversionSequence::Better:
7699 // Cand1 has a better conversion sequence.
7700 return true;
7701
7702 case ImplicitConversionSequence::Worse:
7703 // Cand1 can't be better than Cand2.
7704 return false;
7705
7706 case ImplicitConversionSequence::Indistinguishable:
7707 // Do nothing
7708 break;
7709 }
7710 }
7711
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007712 return false;
7713}
7714
Mike Stump11289f42009-09-09 15:08:12 +00007715/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007716/// within an overload candidate set.
7717///
7718/// \param CandidateSet the set of candidate functions.
7719///
7720/// \param Loc the location of the function name (or operator symbol) for
7721/// which overload resolution occurs.
7722///
Mike Stump11289f42009-09-09 15:08:12 +00007723/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007724/// function, Best points to the candidate function found.
7725///
7726/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007727OverloadingResult
7728OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007729 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007730 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007731 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007732 Best = end();
7733 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7734 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007735 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007736 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007737 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007738 }
7739
7740 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007741 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007742 return OR_No_Viable_Function;
7743
7744 // Make sure that this function is better than every other viable
7745 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007746 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007747 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007748 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007749 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007750 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007751 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007752 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007753 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007754 }
Mike Stump11289f42009-09-09 15:08:12 +00007755
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007756 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007757 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007758 (Best->Function->isDeleted() ||
7759 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007760 return OR_Deleted;
7761
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007762 return OR_Success;
7763}
7764
John McCall53262c92010-01-12 02:15:36 +00007765namespace {
7766
7767enum OverloadCandidateKind {
7768 oc_function,
7769 oc_method,
7770 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007771 oc_function_template,
7772 oc_method_template,
7773 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007774 oc_implicit_default_constructor,
7775 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007776 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007777 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007778 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007779 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007780};
7781
John McCalle1ac8d12010-01-13 00:25:19 +00007782OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7783 FunctionDecl *Fn,
7784 std::string &Description) {
7785 bool isTemplate = false;
7786
7787 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7788 isTemplate = true;
7789 Description = S.getTemplateArgumentBindingsText(
7790 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7791 }
John McCallfd0b2f82010-01-06 09:43:14 +00007792
7793 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007794 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007795 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007796
Sebastian Redl08905022011-02-05 19:23:19 +00007797 if (Ctor->getInheritedConstructor())
7798 return oc_implicit_inherited_constructor;
7799
Alexis Hunt119c10e2011-05-25 23:16:36 +00007800 if (Ctor->isDefaultConstructor())
7801 return oc_implicit_default_constructor;
7802
7803 if (Ctor->isMoveConstructor())
7804 return oc_implicit_move_constructor;
7805
7806 assert(Ctor->isCopyConstructor() &&
7807 "unexpected sort of implicit constructor");
7808 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007809 }
7810
7811 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7812 // This actually gets spelled 'candidate function' for now, but
7813 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007814 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007815 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007816
Alexis Hunt119c10e2011-05-25 23:16:36 +00007817 if (Meth->isMoveAssignmentOperator())
7818 return oc_implicit_move_assignment;
7819
Douglas Gregor12695102012-02-10 08:36:38 +00007820 if (Meth->isCopyAssignmentOperator())
7821 return oc_implicit_copy_assignment;
7822
7823 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7824 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007825 }
7826
John McCalle1ac8d12010-01-13 00:25:19 +00007827 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007828}
7829
Sebastian Redl08905022011-02-05 19:23:19 +00007830void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7831 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7832 if (!Ctor) return;
7833
7834 Ctor = Ctor->getInheritedConstructor();
7835 if (!Ctor) return;
7836
7837 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7838}
7839
John McCall53262c92010-01-12 02:15:36 +00007840} // end anonymous namespace
7841
7842// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007843void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007844 std::string FnDesc;
7845 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007846 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7847 << (unsigned) K << FnDesc;
7848 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7849 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007850 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007851}
7852
Douglas Gregorb491ed32011-02-19 21:32:49 +00007853//Notes the location of all overload candidates designated through
7854// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007855void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007856 assert(OverloadedExpr->getType() == Context.OverloadTy);
7857
7858 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7859 OverloadExpr *OvlExpr = Ovl.Expression;
7860
7861 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7862 IEnd = OvlExpr->decls_end();
7863 I != IEnd; ++I) {
7864 if (FunctionTemplateDecl *FunTmpl =
7865 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007866 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007867 } else if (FunctionDecl *Fun
7868 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007869 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007870 }
7871 }
7872}
7873
John McCall0d1da222010-01-12 00:44:57 +00007874/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7875/// "lead" diagnostic; it will be given two arguments, the source and
7876/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007877void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7878 Sema &S,
7879 SourceLocation CaretLoc,
7880 const PartialDiagnostic &PDiag) const {
7881 S.Diag(CaretLoc, PDiag)
7882 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007883 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007884 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7885 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007886 }
John McCall12f97bc2010-01-08 04:41:39 +00007887}
7888
John McCall0d1da222010-01-12 00:44:57 +00007889namespace {
7890
John McCall6a61b522010-01-13 09:16:55 +00007891void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7892 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7893 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007894 assert(Cand->Function && "for now, candidate must be a function");
7895 FunctionDecl *Fn = Cand->Function;
7896
7897 // There's a conversion slot for the object argument if this is a
7898 // non-constructor method. Note that 'I' corresponds the
7899 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007900 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007901 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007902 if (I == 0)
7903 isObjectArgument = true;
7904 else
7905 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007906 }
7907
John McCalle1ac8d12010-01-13 00:25:19 +00007908 std::string FnDesc;
7909 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7910
John McCall6a61b522010-01-13 09:16:55 +00007911 Expr *FromExpr = Conv.Bad.FromExpr;
7912 QualType FromTy = Conv.Bad.getFromType();
7913 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007914
John McCallfb7ad0f2010-02-02 02:42:52 +00007915 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007916 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007917 Expr *E = FromExpr->IgnoreParens();
7918 if (isa<UnaryOperator>(E))
7919 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007920 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007921
7922 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7923 << (unsigned) FnKind << FnDesc
7924 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7925 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007926 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007927 return;
7928 }
7929
John McCall6d174642010-01-23 08:10:49 +00007930 // Do some hand-waving analysis to see if the non-viability is due
7931 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007932 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7933 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7934 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7935 CToTy = RT->getPointeeType();
7936 else {
7937 // TODO: detect and diagnose the full richness of const mismatches.
7938 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7939 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7940 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7941 }
7942
7943 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7944 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00007945 Qualifiers FromQs = CFromTy.getQualifiers();
7946 Qualifiers ToQs = CToTy.getQualifiers();
7947
7948 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7949 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7950 << (unsigned) FnKind << FnDesc
7951 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7952 << FromTy
7953 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7954 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007955 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007956 return;
7957 }
7958
John McCall31168b02011-06-15 23:02:42 +00007959 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007960 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007961 << (unsigned) FnKind << FnDesc
7962 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7963 << FromTy
7964 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7965 << (unsigned) isObjectArgument << I+1;
7966 MaybeEmitInheritedConstructorNote(S, Fn);
7967 return;
7968 }
7969
Douglas Gregoraec25842011-04-26 23:16:46 +00007970 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7972 << (unsigned) FnKind << FnDesc
7973 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7974 << FromTy
7975 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7976 << (unsigned) isObjectArgument << I+1;
7977 MaybeEmitInheritedConstructorNote(S, Fn);
7978 return;
7979 }
7980
John McCall47000992010-01-14 03:28:57 +00007981 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7982 assert(CVR && "unexpected qualifiers mismatch");
7983
7984 if (isObjectArgument) {
7985 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7986 << (unsigned) FnKind << FnDesc
7987 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7988 << FromTy << (CVR - 1);
7989 } else {
7990 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7991 << (unsigned) FnKind << FnDesc
7992 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7993 << FromTy << (CVR - 1) << I+1;
7994 }
Sebastian Redl08905022011-02-05 19:23:19 +00007995 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007996 return;
7997 }
7998
Sebastian Redla72462c2011-09-24 17:48:32 +00007999 // Special diagnostic for failure to convert an initializer list, since
8000 // telling the user that it has type void is not useful.
8001 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8002 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8003 << (unsigned) FnKind << FnDesc
8004 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8005 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8006 MaybeEmitInheritedConstructorNote(S, Fn);
8007 return;
8008 }
8009
John McCall6d174642010-01-23 08:10:49 +00008010 // Diagnose references or pointers to incomplete types differently,
8011 // since it's far from impossible that the incompleteness triggered
8012 // the failure.
8013 QualType TempFromTy = FromTy.getNonReferenceType();
8014 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8015 TempFromTy = PTy->getPointeeType();
8016 if (TempFromTy->isIncompleteType()) {
8017 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8018 << (unsigned) FnKind << FnDesc
8019 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8020 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008021 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008022 return;
8023 }
8024
Douglas Gregor56f2e342010-06-30 23:01:39 +00008025 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008026 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008027 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8028 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8029 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8030 FromPtrTy->getPointeeType()) &&
8031 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8032 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008033 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008034 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008035 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008036 }
8037 } else if (const ObjCObjectPointerType *FromPtrTy
8038 = FromTy->getAs<ObjCObjectPointerType>()) {
8039 if (const ObjCObjectPointerType *ToPtrTy
8040 = ToTy->getAs<ObjCObjectPointerType>())
8041 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8042 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8043 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8044 FromPtrTy->getPointeeType()) &&
8045 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008046 BaseToDerivedConversion = 2;
8047 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8048 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8049 !FromTy->isIncompleteType() &&
8050 !ToRefTy->getPointeeType()->isIncompleteType() &&
8051 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
8052 BaseToDerivedConversion = 3;
8053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008054
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008055 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008056 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008057 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008058 << (unsigned) FnKind << FnDesc
8059 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008060 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008061 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008062 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008063 return;
8064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008066 if (isa<ObjCObjectPointerType>(CFromTy) &&
8067 isa<PointerType>(CToTy)) {
8068 Qualifiers FromQs = CFromTy.getQualifiers();
8069 Qualifiers ToQs = CToTy.getQualifiers();
8070 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8072 << (unsigned) FnKind << FnDesc
8073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8074 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8075 MaybeEmitInheritedConstructorNote(S, Fn);
8076 return;
8077 }
8078 }
8079
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008080 // Emit the generic diagnostic and, optionally, add the hints to it.
8081 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8082 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008084 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8085 << (unsigned) (Cand->Fix.Kind);
8086
8087 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008088 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8089 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008090 FDiag << *HI;
8091 S.Diag(Fn->getLocation(), FDiag);
8092
Sebastian Redl08905022011-02-05 19:23:19 +00008093 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008094}
8095
8096void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8097 unsigned NumFormalArgs) {
8098 // TODO: treat calls to a missing default constructor as a special case
8099
8100 FunctionDecl *Fn = Cand->Function;
8101 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8102
8103 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008104
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008105 // With invalid overloaded operators, it's possible that we think we
8106 // have an arity mismatch when it fact it looks like we have the
8107 // right number of arguments, because only overloaded operators have
8108 // the weird behavior of overloading member and non-member functions.
8109 // Just don't report anything.
8110 if (Fn->isInvalidDecl() &&
8111 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8112 return;
8113
John McCall6a61b522010-01-13 09:16:55 +00008114 // at least / at most / exactly
8115 unsigned mode, modeCount;
8116 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008117 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8118 (Cand->FailureKind == ovl_fail_bad_deduction &&
8119 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008120 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008121 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008122 mode = 0; // "at least"
8123 else
8124 mode = 2; // "exactly"
8125 modeCount = MinParams;
8126 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008127 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8128 (Cand->FailureKind == ovl_fail_bad_deduction &&
8129 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008130 if (MinParams != FnTy->getNumArgs())
8131 mode = 1; // "at most"
8132 else
8133 mode = 2; // "exactly"
8134 modeCount = FnTy->getNumArgs();
8135 }
8136
8137 std::string Description;
8138 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8139
8140 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008141 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00008142 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008143 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008144}
8145
John McCall8b9ed552010-02-01 18:53:26 +00008146/// Diagnose a failed template-argument deduction.
8147void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008148 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008149 FunctionDecl *Fn = Cand->Function; // pattern
8150
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008151 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008152 NamedDecl *ParamD;
8153 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8154 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8155 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008156 switch (Cand->DeductionFailure.Result) {
8157 case Sema::TDK_Success:
8158 llvm_unreachable("TDK_success while diagnosing bad deduction");
8159
8160 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008161 assert(ParamD && "no parameter found for incomplete deduction result");
8162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8163 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008164 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008165 return;
8166 }
8167
John McCall42d7d192010-08-05 09:05:08 +00008168 case Sema::TDK_Underqualified: {
8169 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8170 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8171
8172 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8173
8174 // Param will have been canonicalized, but it should just be a
8175 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008176 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008177 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008178 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008179 assert(S.Context.hasSameType(Param, NonCanonParam));
8180
8181 // Arg has also been canonicalized, but there's nothing we can do
8182 // about that. It also doesn't matter as much, because it won't
8183 // have any template parameters in it (because deduction isn't
8184 // done on dependent types).
8185 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8186
8187 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8188 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008189 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008190 return;
8191 }
8192
8193 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008194 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008195 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008196 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008197 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008198 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008199 which = 1;
8200 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008201 which = 2;
8202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008203
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008204 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008205 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008206 << *Cand->DeductionFailure.getFirstArg()
8207 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008208 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008209 return;
8210 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008211
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008212 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008213 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008214 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008215 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008216 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8217 << ParamD->getDeclName();
8218 else {
8219 int index = 0;
8220 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8221 index = TTP->getIndex();
8222 else if (NonTypeTemplateParmDecl *NTTP
8223 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8224 index = NTTP->getIndex();
8225 else
8226 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008227 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008228 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8229 << (index + 1);
8230 }
Sebastian Redl08905022011-02-05 19:23:19 +00008231 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008232 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008233
Douglas Gregor02eb4832010-05-08 18:13:28 +00008234 case Sema::TDK_TooManyArguments:
8235 case Sema::TDK_TooFewArguments:
8236 DiagnoseArityMismatch(S, Cand, NumArgs);
8237 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008238
8239 case Sema::TDK_InstantiationDepth:
8240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008241 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008242 return;
8243
8244 case Sema::TDK_SubstitutionFailure: {
8245 std::string ArgString;
8246 if (TemplateArgumentList *Args
8247 = Cand->DeductionFailure.getTemplateArgumentList())
8248 ArgString = S.getTemplateArgumentBindingsText(
8249 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8250 *Args);
8251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8252 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00008253 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008254 return;
8255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008256
John McCall8b9ed552010-02-01 18:53:26 +00008257 // TODO: diagnose these individually, then kill off
8258 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008259 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008260 case Sema::TDK_FailedOverloadResolution:
8261 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008262 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008263 return;
8264 }
8265}
8266
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008267/// CUDA: diagnose an invalid call across targets.
8268void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8269 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8270 FunctionDecl *Callee = Cand->Function;
8271
8272 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8273 CalleeTarget = S.IdentifyCUDATarget(Callee);
8274
8275 std::string FnDesc;
8276 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8277
8278 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8279 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8280}
8281
John McCall8b9ed552010-02-01 18:53:26 +00008282/// Generates a 'note' diagnostic for an overload candidate. We've
8283/// already generated a primary error at the call site.
8284///
8285/// It really does need to be a single diagnostic with its caret
8286/// pointed at the candidate declaration. Yes, this creates some
8287/// major challenges of technical writing. Yes, this makes pointing
8288/// out problems with specific arguments quite awkward. It's still
8289/// better than generating twenty screens of text for every failed
8290/// overload.
8291///
8292/// It would be great to be able to express per-candidate problems
8293/// more richly for those diagnostic clients that cared, but we'd
8294/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008295void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008296 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008297 FunctionDecl *Fn = Cand->Function;
8298
John McCall12f97bc2010-01-08 04:41:39 +00008299 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008300 if (Cand->Viable && (Fn->isDeleted() ||
8301 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008302 std::string FnDesc;
8303 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008304
8305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008306 << FnKind << FnDesc
8307 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008308 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008309 return;
John McCall12f97bc2010-01-08 04:41:39 +00008310 }
8311
John McCalle1ac8d12010-01-13 00:25:19 +00008312 // We don't really have anything else to say about viable candidates.
8313 if (Cand->Viable) {
8314 S.NoteOverloadCandidate(Fn);
8315 return;
8316 }
John McCall0d1da222010-01-12 00:44:57 +00008317
John McCall6a61b522010-01-13 09:16:55 +00008318 switch (Cand->FailureKind) {
8319 case ovl_fail_too_many_arguments:
8320 case ovl_fail_too_few_arguments:
8321 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008322
John McCall6a61b522010-01-13 09:16:55 +00008323 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008324 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008325
John McCallfe796dd2010-01-23 05:17:32 +00008326 case ovl_fail_trivial_conversion:
8327 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008328 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008329 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008330
John McCall65eb8792010-02-25 01:37:24 +00008331 case ovl_fail_bad_conversion: {
8332 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008333 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008334 if (Cand->Conversions[I].isBad())
8335 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008336
John McCall6a61b522010-01-13 09:16:55 +00008337 // FIXME: this currently happens when we're called from SemaInit
8338 // when user-conversion overload fails. Figure out how to handle
8339 // those conditions and diagnose them well.
8340 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008341 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008342
8343 case ovl_fail_bad_target:
8344 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008345 }
John McCalld3224162010-01-08 00:58:21 +00008346}
8347
8348void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8349 // Desugar the type of the surrogate down to a function type,
8350 // retaining as many typedefs as possible while still showing
8351 // the function type (and, therefore, its parameter types).
8352 QualType FnType = Cand->Surrogate->getConversionType();
8353 bool isLValueReference = false;
8354 bool isRValueReference = false;
8355 bool isPointer = false;
8356 if (const LValueReferenceType *FnTypeRef =
8357 FnType->getAs<LValueReferenceType>()) {
8358 FnType = FnTypeRef->getPointeeType();
8359 isLValueReference = true;
8360 } else if (const RValueReferenceType *FnTypeRef =
8361 FnType->getAs<RValueReferenceType>()) {
8362 FnType = FnTypeRef->getPointeeType();
8363 isRValueReference = true;
8364 }
8365 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8366 FnType = FnTypePtr->getPointeeType();
8367 isPointer = true;
8368 }
8369 // Desugar down to a function type.
8370 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8371 // Reconstruct the pointer/reference as appropriate.
8372 if (isPointer) FnType = S.Context.getPointerType(FnType);
8373 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8374 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8375
8376 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8377 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008378 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008379}
8380
8381void NoteBuiltinOperatorCandidate(Sema &S,
8382 const char *Opc,
8383 SourceLocation OpLoc,
8384 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008385 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008386 std::string TypeStr("operator");
8387 TypeStr += Opc;
8388 TypeStr += "(";
8389 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008390 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008391 TypeStr += ")";
8392 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8393 } else {
8394 TypeStr += ", ";
8395 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8396 TypeStr += ")";
8397 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8398 }
8399}
8400
8401void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8402 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008403 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008404 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8405 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008406 if (ICS.isBad()) break; // all meaningless after first invalid
8407 if (!ICS.isAmbiguous()) continue;
8408
John McCall5c32be02010-08-24 20:38:10 +00008409 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008410 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008411 }
8412}
8413
John McCall3712d9e2010-01-15 23:32:50 +00008414SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8415 if (Cand->Function)
8416 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008417 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008418 return Cand->Surrogate->getLocation();
8419 return SourceLocation();
8420}
8421
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008422static unsigned
8423RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008424 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008425 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008426 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008427
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008428 case Sema::TDK_Incomplete:
8429 return 1;
8430
8431 case Sema::TDK_Underqualified:
8432 case Sema::TDK_Inconsistent:
8433 return 2;
8434
8435 case Sema::TDK_SubstitutionFailure:
8436 case Sema::TDK_NonDeducedMismatch:
8437 return 3;
8438
8439 case Sema::TDK_InstantiationDepth:
8440 case Sema::TDK_FailedOverloadResolution:
8441 return 4;
8442
8443 case Sema::TDK_InvalidExplicitArguments:
8444 return 5;
8445
8446 case Sema::TDK_TooManyArguments:
8447 case Sema::TDK_TooFewArguments:
8448 return 6;
8449 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008450 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008451}
8452
John McCallad2587a2010-01-12 00:48:53 +00008453struct CompareOverloadCandidatesForDisplay {
8454 Sema &S;
8455 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008456
8457 bool operator()(const OverloadCandidate *L,
8458 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008459 // Fast-path this check.
8460 if (L == R) return false;
8461
John McCall12f97bc2010-01-08 04:41:39 +00008462 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008463 if (L->Viable) {
8464 if (!R->Viable) return true;
8465
8466 // TODO: introduce a tri-valued comparison for overload
8467 // candidates. Would be more worthwhile if we had a sort
8468 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008469 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8470 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008471 } else if (R->Viable)
8472 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008473
John McCall3712d9e2010-01-15 23:32:50 +00008474 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008475
John McCall3712d9e2010-01-15 23:32:50 +00008476 // Criteria by which we can sort non-viable candidates:
8477 if (!L->Viable) {
8478 // 1. Arity mismatches come after other candidates.
8479 if (L->FailureKind == ovl_fail_too_many_arguments ||
8480 L->FailureKind == ovl_fail_too_few_arguments)
8481 return false;
8482 if (R->FailureKind == ovl_fail_too_many_arguments ||
8483 R->FailureKind == ovl_fail_too_few_arguments)
8484 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008485
John McCallfe796dd2010-01-23 05:17:32 +00008486 // 2. Bad conversions come first and are ordered by the number
8487 // of bad conversions and quality of good conversions.
8488 if (L->FailureKind == ovl_fail_bad_conversion) {
8489 if (R->FailureKind != ovl_fail_bad_conversion)
8490 return true;
8491
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008492 // The conversion that can be fixed with a smaller number of changes,
8493 // comes first.
8494 unsigned numLFixes = L->Fix.NumConversionsFixed;
8495 unsigned numRFixes = R->Fix.NumConversionsFixed;
8496 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8497 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008498 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008499 if (numLFixes < numRFixes)
8500 return true;
8501 else
8502 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008503 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008504
John McCallfe796dd2010-01-23 05:17:32 +00008505 // If there's any ordering between the defined conversions...
8506 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008507 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008508
8509 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008510 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008511 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008512 switch (CompareImplicitConversionSequences(S,
8513 L->Conversions[I],
8514 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008515 case ImplicitConversionSequence::Better:
8516 leftBetter++;
8517 break;
8518
8519 case ImplicitConversionSequence::Worse:
8520 leftBetter--;
8521 break;
8522
8523 case ImplicitConversionSequence::Indistinguishable:
8524 break;
8525 }
8526 }
8527 if (leftBetter > 0) return true;
8528 if (leftBetter < 0) return false;
8529
8530 } else if (R->FailureKind == ovl_fail_bad_conversion)
8531 return false;
8532
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008533 if (L->FailureKind == ovl_fail_bad_deduction) {
8534 if (R->FailureKind != ovl_fail_bad_deduction)
8535 return true;
8536
8537 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8538 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008539 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008540 } else if (R->FailureKind == ovl_fail_bad_deduction)
8541 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008542
John McCall3712d9e2010-01-15 23:32:50 +00008543 // TODO: others?
8544 }
8545
8546 // Sort everything else by location.
8547 SourceLocation LLoc = GetLocationForCandidate(L);
8548 SourceLocation RLoc = GetLocationForCandidate(R);
8549
8550 // Put candidates without locations (e.g. builtins) at the end.
8551 if (LLoc.isInvalid()) return false;
8552 if (RLoc.isInvalid()) return true;
8553
8554 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008555 }
8556};
8557
John McCallfe796dd2010-01-23 05:17:32 +00008558/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008559/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008560void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008561 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008562 assert(!Cand->Viable);
8563
8564 // Don't do anything on failures other than bad conversion.
8565 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8566
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008567 // We only want the FixIts if all the arguments can be corrected.
8568 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008569 // Use a implicit copy initialization to check conversion fixes.
8570 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008571
John McCallfe796dd2010-01-23 05:17:32 +00008572 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008573 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008574 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008575 while (true) {
8576 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8577 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008578 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008579 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008580 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008581 }
John McCallfe796dd2010-01-23 05:17:32 +00008582 }
8583
8584 if (ConvIdx == ConvCount)
8585 return;
8586
John McCall65eb8792010-02-25 01:37:24 +00008587 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8588 "remaining conversion is initialized?");
8589
Douglas Gregoradc7a702010-04-16 17:45:54 +00008590 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008591 // operation somehow.
8592 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008593
8594 const FunctionProtoType* Proto;
8595 unsigned ArgIdx = ConvIdx;
8596
8597 if (Cand->IsSurrogate) {
8598 QualType ConvType
8599 = Cand->Surrogate->getConversionType().getNonReferenceType();
8600 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8601 ConvType = ConvPtrType->getPointeeType();
8602 Proto = ConvType->getAs<FunctionProtoType>();
8603 ArgIdx--;
8604 } else if (Cand->Function) {
8605 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8606 if (isa<CXXMethodDecl>(Cand->Function) &&
8607 !isa<CXXConstructorDecl>(Cand->Function))
8608 ArgIdx--;
8609 } else {
8610 // Builtin binary operator with a bad first conversion.
8611 assert(ConvCount <= 3);
8612 for (; ConvIdx != ConvCount; ++ConvIdx)
8613 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008614 = TryCopyInitialization(S, Args[ConvIdx],
8615 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008616 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008617 /*InOverloadResolution*/ true,
8618 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008619 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008620 return;
8621 }
8622
8623 // Fill in the rest of the conversions.
8624 unsigned NumArgsInProto = Proto->getNumArgs();
8625 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008626 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008627 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008628 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008629 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008630 /*InOverloadResolution=*/true,
8631 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008632 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008633 // Store the FixIt in the candidate if it exists.
8634 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008635 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008636 }
John McCallfe796dd2010-01-23 05:17:32 +00008637 else
8638 Cand->Conversions[ConvIdx].setEllipsis();
8639 }
8640}
8641
John McCalld3224162010-01-08 00:58:21 +00008642} // end anonymous namespace
8643
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008644/// PrintOverloadCandidates - When overload resolution fails, prints
8645/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008646/// set.
John McCall5c32be02010-08-24 20:38:10 +00008647void OverloadCandidateSet::NoteCandidates(Sema &S,
8648 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008649 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008650 const char *Opc,
8651 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008652 // Sort the candidates by viability and position. Sorting directly would
8653 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008654 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008655 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8656 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008657 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008658 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008659 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008660 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008661 if (Cand->Function || Cand->IsSurrogate)
8662 Cands.push_back(Cand);
8663 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8664 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008665 }
8666 }
8667
John McCallad2587a2010-01-12 00:48:53 +00008668 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008669 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008670
John McCall0d1da222010-01-12 00:44:57 +00008671 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008672
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008673 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008674 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8675 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008676 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008677 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8678 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008679
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008680 // Set an arbitrary limit on the number of candidate functions we'll spam
8681 // the user with. FIXME: This limit should depend on details of the
8682 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008683 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008684 break;
8685 }
8686 ++CandsShown;
8687
John McCalld3224162010-01-08 00:58:21 +00008688 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008689 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008690 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008691 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008692 else {
8693 assert(Cand->Viable &&
8694 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008695 // Generally we only see ambiguities including viable builtin
8696 // operators if overload resolution got screwed up by an
8697 // ambiguous user-defined conversion.
8698 //
8699 // FIXME: It's quite possible for different conversions to see
8700 // different ambiguities, though.
8701 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008702 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008703 ReportedAmbiguousConversions = true;
8704 }
John McCalld3224162010-01-08 00:58:21 +00008705
John McCall0d1da222010-01-12 00:44:57 +00008706 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008707 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008709 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008710
8711 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008712 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008713}
8714
Douglas Gregorb491ed32011-02-19 21:32:49 +00008715// [PossiblyAFunctionType] --> [Return]
8716// NonFunctionType --> NonFunctionType
8717// R (A) --> R(A)
8718// R (*)(A) --> R (A)
8719// R (&)(A) --> R (A)
8720// R (S::*)(A) --> R (A)
8721QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8722 QualType Ret = PossiblyAFunctionType;
8723 if (const PointerType *ToTypePtr =
8724 PossiblyAFunctionType->getAs<PointerType>())
8725 Ret = ToTypePtr->getPointeeType();
8726 else if (const ReferenceType *ToTypeRef =
8727 PossiblyAFunctionType->getAs<ReferenceType>())
8728 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008729 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008730 PossiblyAFunctionType->getAs<MemberPointerType>())
8731 Ret = MemTypePtr->getPointeeType();
8732 Ret =
8733 Context.getCanonicalType(Ret).getUnqualifiedType();
8734 return Ret;
8735}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008736
Douglas Gregorb491ed32011-02-19 21:32:49 +00008737// A helper class to help with address of function resolution
8738// - allows us to avoid passing around all those ugly parameters
8739class AddressOfFunctionResolver
8740{
8741 Sema& S;
8742 Expr* SourceExpr;
8743 const QualType& TargetType;
8744 QualType TargetFunctionType; // Extracted function type from target type
8745
8746 bool Complain;
8747 //DeclAccessPair& ResultFunctionAccessPair;
8748 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008749
Douglas Gregorb491ed32011-02-19 21:32:49 +00008750 bool TargetTypeIsNonStaticMemberFunction;
8751 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008752
Douglas Gregorb491ed32011-02-19 21:32:49 +00008753 OverloadExpr::FindResult OvlExprInfo;
8754 OverloadExpr *OvlExpr;
8755 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008756 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008757
Douglas Gregorb491ed32011-02-19 21:32:49 +00008758public:
8759 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8760 const QualType& TargetType, bool Complain)
8761 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8762 Complain(Complain), Context(S.getASTContext()),
8763 TargetTypeIsNonStaticMemberFunction(
8764 !!TargetType->getAs<MemberPointerType>()),
8765 FoundNonTemplateFunction(false),
8766 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8767 OvlExpr(OvlExprInfo.Expression)
8768 {
8769 ExtractUnqualifiedFunctionTypeFromTargetType();
8770
8771 if (!TargetFunctionType->isFunctionType()) {
8772 if (OvlExpr->hasExplicitTemplateArgs()) {
8773 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008774 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008775 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008776
8777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8778 if (!Method->isStatic()) {
8779 // If the target type is a non-function type and the function
8780 // found is a non-static member function, pretend as if that was
8781 // the target, it's the only possible type to end up with.
8782 TargetTypeIsNonStaticMemberFunction = true;
8783
8784 // And skip adding the function if its not in the proper form.
8785 // We'll diagnose this due to an empty set of functions.
8786 if (!OvlExprInfo.HasFormOfMemberPointer)
8787 return;
8788 }
8789 }
8790
Douglas Gregorb491ed32011-02-19 21:32:49 +00008791 Matches.push_back(std::make_pair(dap,Fn));
8792 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008793 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008794 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008795 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008796
8797 if (OvlExpr->hasExplicitTemplateArgs())
8798 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008799
Douglas Gregorb491ed32011-02-19 21:32:49 +00008800 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8801 // C++ [over.over]p4:
8802 // If more than one function is selected, [...]
8803 if (Matches.size() > 1) {
8804 if (FoundNonTemplateFunction)
8805 EliminateAllTemplateMatches();
8806 else
8807 EliminateAllExceptMostSpecializedTemplate();
8808 }
8809 }
8810 }
8811
8812private:
8813 bool isTargetTypeAFunction() const {
8814 return TargetFunctionType->isFunctionType();
8815 }
8816
8817 // [ToType] [Return]
8818
8819 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8820 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8821 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8822 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8823 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8824 }
8825
8826 // return true if any matching specializations were found
8827 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8828 const DeclAccessPair& CurAccessFunPair) {
8829 if (CXXMethodDecl *Method
8830 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8831 // Skip non-static function templates when converting to pointer, and
8832 // static when converting to member pointer.
8833 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8834 return false;
8835 }
8836 else if (TargetTypeIsNonStaticMemberFunction)
8837 return false;
8838
8839 // C++ [over.over]p2:
8840 // If the name is a function template, template argument deduction is
8841 // done (14.8.2.2), and if the argument deduction succeeds, the
8842 // resulting template argument list is used to generate a single
8843 // function template specialization, which is added to the set of
8844 // overloaded functions considered.
8845 FunctionDecl *Specialization = 0;
8846 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8847 if (Sema::TemplateDeductionResult Result
8848 = S.DeduceTemplateArguments(FunctionTemplate,
8849 &OvlExplicitTemplateArgs,
8850 TargetFunctionType, Specialization,
8851 Info)) {
8852 // FIXME: make a note of the failed deduction for diagnostics.
8853 (void)Result;
8854 return false;
8855 }
8856
8857 // Template argument deduction ensures that we have an exact match.
8858 // This function template specicalization works.
8859 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8860 assert(TargetFunctionType
8861 == Context.getCanonicalType(Specialization->getType()));
8862 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8863 return true;
8864 }
8865
8866 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8867 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008868 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008869 // Skip non-static functions when converting to pointer, and static
8870 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008871 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8872 return false;
8873 }
8874 else if (TargetTypeIsNonStaticMemberFunction)
8875 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008876
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008877 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008878 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008879 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8880 if (S.CheckCUDATarget(Caller, FunDecl))
8881 return false;
8882
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008883 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008884 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8885 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008886 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8887 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008888 Matches.push_back(std::make_pair(CurAccessFunPair,
8889 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008890 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008891 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008892 }
Mike Stump11289f42009-09-09 15:08:12 +00008893 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008894
8895 return false;
8896 }
8897
8898 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8899 bool Ret = false;
8900
8901 // If the overload expression doesn't have the form of a pointer to
8902 // member, don't try to convert it to a pointer-to-member type.
8903 if (IsInvalidFormOfPointerToMemberFunction())
8904 return false;
8905
8906 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8907 E = OvlExpr->decls_end();
8908 I != E; ++I) {
8909 // Look through any using declarations to find the underlying function.
8910 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8911
8912 // C++ [over.over]p3:
8913 // Non-member functions and static member functions match
8914 // targets of type "pointer-to-function" or "reference-to-function."
8915 // Nonstatic member functions match targets of
8916 // type "pointer-to-member-function."
8917 // Note that according to DR 247, the containing class does not matter.
8918 if (FunctionTemplateDecl *FunctionTemplate
8919 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8920 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8921 Ret = true;
8922 }
8923 // If we have explicit template arguments supplied, skip non-templates.
8924 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8925 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8926 Ret = true;
8927 }
8928 assert(Ret || Matches.empty());
8929 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008930 }
8931
Douglas Gregorb491ed32011-02-19 21:32:49 +00008932 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008933 // [...] and any given function template specialization F1 is
8934 // eliminated if the set contains a second function template
8935 // specialization whose function template is more specialized
8936 // than the function template of F1 according to the partial
8937 // ordering rules of 14.5.5.2.
8938
8939 // The algorithm specified above is quadratic. We instead use a
8940 // two-pass algorithm (similar to the one used to identify the
8941 // best viable function in an overload set) that identifies the
8942 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008943
8944 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8945 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8946 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008947
John McCall58cc69d2010-01-27 01:50:18 +00008948 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008949 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8950 TPOC_Other, 0, SourceExpr->getLocStart(),
8951 S.PDiag(),
8952 S.PDiag(diag::err_addr_ovl_ambiguous)
8953 << Matches[0].second->getDeclName(),
8954 S.PDiag(diag::note_ovl_candidate)
8955 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008956 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008957
Douglas Gregorb491ed32011-02-19 21:32:49 +00008958 if (Result != MatchesCopy.end()) {
8959 // Make it the first and only element
8960 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8961 Matches[0].second = cast<FunctionDecl>(*Result);
8962 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008963 }
8964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008965
Douglas Gregorb491ed32011-02-19 21:32:49 +00008966 void EliminateAllTemplateMatches() {
8967 // [...] any function template specializations in the set are
8968 // eliminated if the set also contains a non-template function, [...]
8969 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8970 if (Matches[I].second->getPrimaryTemplate() == 0)
8971 ++I;
8972 else {
8973 Matches[I] = Matches[--N];
8974 Matches.set_size(N);
8975 }
8976 }
8977 }
8978
8979public:
8980 void ComplainNoMatchesFound() const {
8981 assert(Matches.empty());
8982 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8983 << OvlExpr->getName() << TargetFunctionType
8984 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008985 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008986 }
8987
8988 bool IsInvalidFormOfPointerToMemberFunction() const {
8989 return TargetTypeIsNonStaticMemberFunction &&
8990 !OvlExprInfo.HasFormOfMemberPointer;
8991 }
8992
8993 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8994 // TODO: Should we condition this on whether any functions might
8995 // have matched, or is it more appropriate to do that in callers?
8996 // TODO: a fixit wouldn't hurt.
8997 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8998 << TargetType << OvlExpr->getSourceRange();
8999 }
9000
9001 void ComplainOfInvalidConversion() const {
9002 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9003 << OvlExpr->getName() << TargetType;
9004 }
9005
9006 void ComplainMultipleMatchesFound() const {
9007 assert(Matches.size() > 1);
9008 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9009 << OvlExpr->getName()
9010 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009011 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009012 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009013
9014 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9015
Douglas Gregorb491ed32011-02-19 21:32:49 +00009016 int getNumMatches() const { return Matches.size(); }
9017
9018 FunctionDecl* getMatchingFunctionDecl() const {
9019 if (Matches.size() != 1) return 0;
9020 return Matches[0].second;
9021 }
9022
9023 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9024 if (Matches.size() != 1) return 0;
9025 return &Matches[0].first;
9026 }
9027};
9028
9029/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9030/// an overloaded function (C++ [over.over]), where @p From is an
9031/// expression with overloaded function type and @p ToType is the type
9032/// we're trying to resolve to. For example:
9033///
9034/// @code
9035/// int f(double);
9036/// int f(int);
9037///
9038/// int (*pfd)(double) = f; // selects f(double)
9039/// @endcode
9040///
9041/// This routine returns the resulting FunctionDecl if it could be
9042/// resolved, and NULL otherwise. When @p Complain is true, this
9043/// routine will emit diagnostics if there is an error.
9044FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009045Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9046 QualType TargetType,
9047 bool Complain,
9048 DeclAccessPair &FoundResult,
9049 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009050 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009051
9052 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9053 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009054 int NumMatches = Resolver.getNumMatches();
9055 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009056 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009057 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9058 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9059 else
9060 Resolver.ComplainNoMatchesFound();
9061 }
9062 else if (NumMatches > 1 && Complain)
9063 Resolver.ComplainMultipleMatchesFound();
9064 else if (NumMatches == 1) {
9065 Fn = Resolver.getMatchingFunctionDecl();
9066 assert(Fn);
9067 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00009068 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009069 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009070 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009071 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009072
9073 if (pHadMultipleCandidates)
9074 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009075 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009076}
9077
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009078/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009079/// resolve that overloaded function expression down to a single function.
9080///
9081/// This routine can only resolve template-ids that refer to a single function
9082/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009083/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009084/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009085FunctionDecl *
9086Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9087 bool Complain,
9088 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009089 // C++ [over.over]p1:
9090 // [...] [Note: any redundant set of parentheses surrounding the
9091 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009092 // C++ [over.over]p1:
9093 // [...] The overloaded function name can be preceded by the &
9094 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009095
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009096 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009097 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009098 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009099
9100 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009101 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009102
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009103 // Look through all of the overloaded functions, searching for one
9104 // whose type matches exactly.
9105 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009106 for (UnresolvedSetIterator I = ovl->decls_begin(),
9107 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009108 // C++0x [temp.arg.explicit]p3:
9109 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009110 // where deduction is not done, if a template argument list is
9111 // specified and it, along with any default template arguments,
9112 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009113 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009114 FunctionTemplateDecl *FunctionTemplate
9115 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009116
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009117 // C++ [over.over]p2:
9118 // If the name is a function template, template argument deduction is
9119 // done (14.8.2.2), and if the argument deduction succeeds, the
9120 // resulting template argument list is used to generate a single
9121 // function template specialization, which is added to the set of
9122 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009123 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009124 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009125 if (TemplateDeductionResult Result
9126 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9127 Specialization, Info)) {
9128 // FIXME: make a note of the failed deduction for diagnostics.
9129 (void)Result;
9130 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009131 }
9132
John McCall0009fcc2011-04-26 20:42:42 +00009133 assert(Specialization && "no specialization and no error?");
9134
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009135 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009136 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009137 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009138 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9139 << ovl->getName();
9140 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009141 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009142 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009143 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009144
John McCall0009fcc2011-04-26 20:42:42 +00009145 Matched = Specialization;
9146 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009148
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009149 return Matched;
9150}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009151
Douglas Gregor1beec452011-03-12 01:48:56 +00009152
9153
9154
John McCall50a2c2c2011-10-11 23:14:30 +00009155// Resolve and fix an overloaded expression that can be resolved
9156// because it identifies a single function template specialization.
9157//
Douglas Gregor1beec452011-03-12 01:48:56 +00009158// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009159//
9160// Return true if it was logically possible to so resolve the
9161// expression, regardless of whether or not it succeeded. Always
9162// returns true if 'complain' is set.
9163bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9164 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9165 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009166 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009167 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009168 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009169
John McCall50a2c2c2011-10-11 23:14:30 +00009170 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009171
John McCall0009fcc2011-04-26 20:42:42 +00009172 DeclAccessPair found;
9173 ExprResult SingleFunctionExpression;
9174 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9175 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009176 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009177 SrcExpr = ExprError();
9178 return true;
9179 }
John McCall0009fcc2011-04-26 20:42:42 +00009180
9181 // It is only correct to resolve to an instance method if we're
9182 // resolving a form that's permitted to be a pointer to member.
9183 // Otherwise we'll end up making a bound member expression, which
9184 // is illegal in all the contexts we resolve like this.
9185 if (!ovl.HasFormOfMemberPointer &&
9186 isa<CXXMethodDecl>(fn) &&
9187 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009188 if (!complain) return false;
9189
9190 Diag(ovl.Expression->getExprLoc(),
9191 diag::err_bound_member_function)
9192 << 0 << ovl.Expression->getSourceRange();
9193
9194 // TODO: I believe we only end up here if there's a mix of
9195 // static and non-static candidates (otherwise the expression
9196 // would have 'bound member' type, not 'overload' type).
9197 // Ideally we would note which candidate was chosen and why
9198 // the static candidates were rejected.
9199 SrcExpr = ExprError();
9200 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009201 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009202
John McCall0009fcc2011-04-26 20:42:42 +00009203 // Fix the expresion to refer to 'fn'.
9204 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009205 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009206
9207 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009208 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009209 SingleFunctionExpression =
9210 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009211 if (SingleFunctionExpression.isInvalid()) {
9212 SrcExpr = ExprError();
9213 return true;
9214 }
9215 }
John McCall0009fcc2011-04-26 20:42:42 +00009216 }
9217
9218 if (!SingleFunctionExpression.isUsable()) {
9219 if (complain) {
9220 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9221 << ovl.Expression->getName()
9222 << DestTypeForComplaining
9223 << OpRangeForComplaining
9224 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009225 NoteAllOverloadCandidates(SrcExpr.get());
9226
9227 SrcExpr = ExprError();
9228 return true;
9229 }
9230
9231 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009232 }
9233
John McCall50a2c2c2011-10-11 23:14:30 +00009234 SrcExpr = SingleFunctionExpression;
9235 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009236}
9237
Douglas Gregorcabea402009-09-22 15:41:20 +00009238/// \brief Add a single candidate to the overload set.
9239static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009240 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009241 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009242 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009243 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009244 bool PartialOverloading,
9245 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009246 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009247 if (isa<UsingShadowDecl>(Callee))
9248 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9249
Douglas Gregorcabea402009-09-22 15:41:20 +00009250 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009251 if (ExplicitTemplateArgs) {
9252 assert(!KnownValid && "Explicit template arguments?");
9253 return;
9254 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009255 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9256 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009257 return;
John McCalld14a8642009-11-21 08:51:07 +00009258 }
9259
9260 if (FunctionTemplateDecl *FuncTemplate
9261 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009262 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009263 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009264 return;
9265 }
9266
Richard Smith95ce4f62011-06-26 22:19:54 +00009267 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009268}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009269
Douglas Gregorcabea402009-09-22 15:41:20 +00009270/// \brief Add the overload candidates named by callee and/or found by argument
9271/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009272void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009273 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009274 OverloadCandidateSet &CandidateSet,
9275 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009276
9277#ifndef NDEBUG
9278 // Verify that ArgumentDependentLookup is consistent with the rules
9279 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009280 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009281 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9282 // and let Y be the lookup set produced by argument dependent
9283 // lookup (defined as follows). If X contains
9284 //
9285 // -- a declaration of a class member, or
9286 //
9287 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009288 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009289 //
9290 // -- a declaration that is neither a function or a function
9291 // template
9292 //
9293 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009294
John McCall57500772009-12-16 12:17:52 +00009295 if (ULE->requiresADL()) {
9296 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9297 E = ULE->decls_end(); I != E; ++I) {
9298 assert(!(*I)->getDeclContext()->isRecord());
9299 assert(isa<UsingShadowDecl>(*I) ||
9300 !(*I)->getDeclContext()->isFunctionOrMethod());
9301 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009302 }
9303 }
9304#endif
9305
John McCall57500772009-12-16 12:17:52 +00009306 // It would be nice to avoid this copy.
9307 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009308 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009309 if (ULE->hasExplicitTemplateArgs()) {
9310 ULE->copyTemplateArgumentsInto(TABuffer);
9311 ExplicitTemplateArgs = &TABuffer;
9312 }
9313
9314 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9315 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009316 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9317 CandidateSet, PartialOverloading,
9318 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009319
John McCall57500772009-12-16 12:17:52 +00009320 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009321 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009322 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009323 Args, ExplicitTemplateArgs,
9324 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009325 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009326}
John McCalld681c392009-12-16 08:11:27 +00009327
Richard Smith998a5912011-06-05 22:42:48 +00009328/// Attempt to recover from an ill-formed use of a non-dependent name in a
9329/// template, where the non-dependent name was declared after the template
9330/// was defined. This is common in code written for a compilers which do not
9331/// correctly implement two-stage name lookup.
9332///
9333/// Returns true if a viable candidate was found and a diagnostic was issued.
9334static bool
9335DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9336 const CXXScopeSpec &SS, LookupResult &R,
9337 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009338 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009339 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9340 return false;
9341
9342 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009343 if (DC->isTransparentContext())
9344 continue;
9345
Richard Smith998a5912011-06-05 22:42:48 +00009346 SemaRef.LookupQualifiedName(R, DC);
9347
9348 if (!R.empty()) {
9349 R.suppressDiagnostics();
9350
9351 if (isa<CXXRecordDecl>(DC)) {
9352 // Don't diagnose names we find in classes; we get much better
9353 // diagnostics for these from DiagnoseEmptyLookup.
9354 R.clear();
9355 return false;
9356 }
9357
9358 OverloadCandidateSet Candidates(FnLoc);
9359 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9360 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009361 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009362 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009363
9364 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009365 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009366 // No viable functions. Don't bother the user with notes for functions
9367 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009368 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009369 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009370 }
Richard Smith998a5912011-06-05 22:42:48 +00009371
9372 // Find the namespaces where ADL would have looked, and suggest
9373 // declaring the function there instead.
9374 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9375 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009376 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009377 AssociatedNamespaces,
9378 AssociatedClasses);
9379 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009380 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009381 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009382 for (Sema::AssociatedNamespaceSet::iterator
9383 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009384 end = AssociatedNamespaces.end(); it != end; ++it) {
9385 if (!Std->Encloses(*it))
9386 SuggestedNamespaces.insert(*it);
9387 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009388 } else {
9389 // Lacking the 'std::' namespace, use all of the associated namespaces.
9390 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009391 }
9392
9393 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9394 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009395 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009396 SemaRef.Diag(Best->Function->getLocation(),
9397 diag::note_not_found_by_two_phase_lookup)
9398 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009399 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009400 SemaRef.Diag(Best->Function->getLocation(),
9401 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009402 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009403 } else {
9404 // FIXME: It would be useful to list the associated namespaces here,
9405 // but the diagnostics infrastructure doesn't provide a way to produce
9406 // a localized representation of a list of items.
9407 SemaRef.Diag(Best->Function->getLocation(),
9408 diag::note_not_found_by_two_phase_lookup)
9409 << R.getLookupName() << 2;
9410 }
9411
9412 // Try to recover by calling this function.
9413 return true;
9414 }
9415
9416 R.clear();
9417 }
9418
9419 return false;
9420}
9421
9422/// Attempt to recover from ill-formed use of a non-dependent operator in a
9423/// template, where the non-dependent operator was declared after the template
9424/// was defined.
9425///
9426/// Returns true if a viable candidate was found and a diagnostic was issued.
9427static bool
9428DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9429 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009430 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009431 DeclarationName OpName =
9432 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9433 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9434 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009435 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009436}
9437
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009438namespace {
9439// Callback to limit the allowed keywords and to only accept typo corrections
9440// that are keywords or whose decls refer to functions (or template functions)
9441// that accept the given number of arguments.
9442class RecoveryCallCCC : public CorrectionCandidateCallback {
9443 public:
9444 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9445 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009446 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009447 WantRemainingKeywords = false;
9448 }
9449
9450 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9451 if (!candidate.getCorrectionDecl())
9452 return candidate.isKeyword();
9453
9454 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9455 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9456 FunctionDecl *FD = 0;
9457 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9458 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9459 FD = FTD->getTemplatedDecl();
9460 if (!HasExplicitTemplateArgs && !FD) {
9461 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9462 // If the Decl is neither a function nor a template function,
9463 // determine if it is a pointer or reference to a function. If so,
9464 // check against the number of arguments expected for the pointee.
9465 QualType ValType = cast<ValueDecl>(ND)->getType();
9466 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9467 ValType = ValType->getPointeeType();
9468 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9469 if (FPT->getNumArgs() == NumArgs)
9470 return true;
9471 }
9472 }
9473 if (FD && FD->getNumParams() >= NumArgs &&
9474 FD->getMinRequiredArguments() <= NumArgs)
9475 return true;
9476 }
9477 return false;
9478 }
9479
9480 private:
9481 unsigned NumArgs;
9482 bool HasExplicitTemplateArgs;
9483};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009484
9485// Callback that effectively disabled typo correction
9486class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9487 public:
9488 NoTypoCorrectionCCC() {
9489 WantTypeSpecifiers = false;
9490 WantExpressionKeywords = false;
9491 WantCXXNamedCasts = false;
9492 WantRemainingKeywords = false;
9493 }
9494
9495 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9496 return false;
9497 }
9498};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009499}
9500
John McCalld681c392009-12-16 08:11:27 +00009501/// Attempts to recover from a call where no functions were found.
9502///
9503/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009504static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009505BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009506 UnresolvedLookupExpr *ULE,
9507 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009508 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009509 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009510 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009511
9512 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009513 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009514 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009515
John McCall57500772009-12-16 12:17:52 +00009516 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009517 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009518 if (ULE->hasExplicitTemplateArgs()) {
9519 ULE->copyTemplateArgumentsInto(TABuffer);
9520 ExplicitTemplateArgs = &TABuffer;
9521 }
9522
John McCalld681c392009-12-16 08:11:27 +00009523 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9524 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009525 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009526 NoTypoCorrectionCCC RejectAll;
9527 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9528 (CorrectionCandidateCallback*)&Validator :
9529 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009530 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009531 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009532 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009533 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009534 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009535 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009536
John McCall57500772009-12-16 12:17:52 +00009537 assert(!R.empty() && "lookup results empty despite recovery");
9538
9539 // Build an implicit member call if appropriate. Just drop the
9540 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009541 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009542 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009543 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9544 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009545 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009546 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009547 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009548 else
9549 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9550
9551 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009552 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009553
9554 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009555 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009556 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009557 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009558 MultiExprArg(Args.data(), Args.size()),
9559 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009560}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009561
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009562/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009563/// (which eventually refers to the declaration Func) and the call
9564/// arguments Args/NumArgs, attempt to resolve the function call down
9565/// to a specific function. If overload resolution succeeds, returns
9566/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009567/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009568/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009569ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009570Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009571 SourceLocation LParenLoc,
9572 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009573 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009574 Expr *ExecConfig,
9575 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009576#ifndef NDEBUG
9577 if (ULE->requiresADL()) {
9578 // To do ADL, we must have found an unqualified name.
9579 assert(!ULE->getQualifier() && "qualified name with ADL");
9580
9581 // We don't perform ADL for implicit declarations of builtins.
9582 // Verify that this was correctly set up.
9583 FunctionDecl *F;
9584 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9585 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9586 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009587 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009588
John McCall57500772009-12-16 12:17:52 +00009589 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009590 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009591 } else
9592 assert(!ULE->isStdAssociatedNamespace() &&
9593 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009594#endif
9595
John McCall4124c492011-10-17 18:40:02 +00009596 UnbridgedCastsSet UnbridgedCasts;
9597 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9598 return ExprError();
9599
John McCallbc077cf2010-02-08 23:07:23 +00009600 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009601
John McCall57500772009-12-16 12:17:52 +00009602 // Add the functions denoted by the callee to the set of candidate
9603 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009604 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9605 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009606
9607 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009608 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9609 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009610 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009611 // In Microsoft mode, if we are inside a template class member function then
9612 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009613 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009614 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009615 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009616 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009617 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9618 Context.DependentTy, VK_RValue,
9619 RParenLoc);
9620 CE->setTypeDependent(true);
9621 return Owned(CE);
9622 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009623 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9624 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009625 RParenLoc, /*EmptyLookup=*/true,
9626 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009627 }
John McCalld681c392009-12-16 08:11:27 +00009628
John McCall4124c492011-10-17 18:40:02 +00009629 UnbridgedCasts.restore();
9630
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009631 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009632 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009633 case OR_Success: {
9634 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009635 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009636 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009637 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009638 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009639 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9640 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009641 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009642
Richard Smith998a5912011-06-05 22:42:48 +00009643 case OR_No_Viable_Function: {
9644 // Try to recover by looking for viable functions which the user might
9645 // have meant to call.
9646 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009647 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9648 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009649 /*EmptyLookup=*/false,
9650 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009651 if (!Recovery.isInvalid())
9652 return Recovery;
9653
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009654 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009655 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009656 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009657 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9658 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009659 break;
Richard Smith998a5912011-06-05 22:42:48 +00009660 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009661
9662 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009663 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009664 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009665 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9666 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009667 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009668
9669 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009670 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009671 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009672 << Best->Function->isDeleted()
9673 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009674 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009675 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009676 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9677 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009678
9679 // We emitted an error for the unvailable/deleted function call but keep
9680 // the call in the AST.
9681 FunctionDecl *FDecl = Best->Function;
9682 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9683 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9684 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009685 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009686 }
9687
Douglas Gregorb412e172010-07-25 18:17:45 +00009688 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009689 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009690}
9691
John McCall4c4c1df2010-01-26 03:27:55 +00009692static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009693 return Functions.size() > 1 ||
9694 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9695}
9696
Douglas Gregor084d8552009-03-13 23:49:33 +00009697/// \brief Create a unary operation that may resolve to an overloaded
9698/// operator.
9699///
9700/// \param OpLoc The location of the operator itself (e.g., '*').
9701///
9702/// \param OpcIn The UnaryOperator::Opcode that describes this
9703/// operator.
9704///
9705/// \param Functions The set of non-member functions that will be
9706/// considered by overload resolution. The caller needs to build this
9707/// set based on the context using, e.g.,
9708/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9709/// set should not contain any member functions; those will be added
9710/// by CreateOverloadedUnaryOp().
9711///
9712/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009713ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009714Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9715 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009716 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009717 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009718
9719 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9720 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9721 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009722 // TODO: provide better source location info.
9723 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009724
John McCall4124c492011-10-17 18:40:02 +00009725 if (checkPlaceholderForOverload(*this, Input))
9726 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009727
Douglas Gregor084d8552009-03-13 23:49:33 +00009728 Expr *Args[2] = { Input, 0 };
9729 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009730
Douglas Gregor084d8552009-03-13 23:49:33 +00009731 // For post-increment and post-decrement, add the implicit '0' as
9732 // the second argument, so that we know this is a post-increment or
9733 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009734 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009735 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009736 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9737 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009738 NumArgs = 2;
9739 }
9740
9741 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009742 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009743 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009744 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009745 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009746 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009747 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009748
John McCall58cc69d2010-01-27 01:50:18 +00009749 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009750 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009751 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009752 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009753 /*ADL*/ true, IsOverloaded(Fns),
9754 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009755 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009756 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009757 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009758 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009759 OpLoc));
9760 }
9761
9762 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009763 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009764
9765 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009766 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9767 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009768
9769 // Add operator candidates that are member functions.
9770 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9771
John McCall4c4c1df2010-01-26 03:27:55 +00009772 // Add candidates from ADL.
9773 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009774 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009775 /*ExplicitTemplateArgs*/ 0,
9776 CandidateSet);
9777
Douglas Gregor084d8552009-03-13 23:49:33 +00009778 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009779 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009780
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009781 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9782
Douglas Gregor084d8552009-03-13 23:49:33 +00009783 // Perform overload resolution.
9784 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009785 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009786 case OR_Success: {
9787 // We found a built-in operator or an overloaded operator.
9788 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009789
Douglas Gregor084d8552009-03-13 23:49:33 +00009790 if (FnDecl) {
9791 // We matched an overloaded operator. Build a call to that
9792 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009793
Eli Friedmanfa0df832012-02-02 03:46:19 +00009794 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009795
Douglas Gregor084d8552009-03-13 23:49:33 +00009796 // Convert the arguments.
9797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009798 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009799
John Wiegley01296292011-04-08 18:41:53 +00009800 ExprResult InputRes =
9801 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9802 Best->FoundDecl, Method);
9803 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009804 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009805 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009806 } else {
9807 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009808 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009809 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009810 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009811 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009812 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009813 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009814 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009815 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009816 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009817 }
9818
John McCall4fa0d5f2010-05-06 18:15:07 +00009819 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9820
John McCall7decc9e2010-11-18 06:31:45 +00009821 // Determine the result type.
9822 QualType ResultTy = FnDecl->getResultType();
9823 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9824 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009825
Douglas Gregor084d8552009-03-13 23:49:33 +00009826 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009827 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009828 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009829 if (FnExpr.isInvalid())
9830 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009831
Eli Friedman030eee42009-11-18 03:58:17 +00009832 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009833 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009834 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009835 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009836
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009837 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009838 FnDecl))
9839 return ExprError();
9840
John McCallb268a282010-08-23 23:25:46 +00009841 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009842 } else {
9843 // We matched a built-in operator. Convert the arguments, then
9844 // break out so that we will build the appropriate built-in
9845 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009846 ExprResult InputRes =
9847 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9848 Best->Conversions[0], AA_Passing);
9849 if (InputRes.isInvalid())
9850 return ExprError();
9851 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009852 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009853 }
John Wiegley01296292011-04-08 18:41:53 +00009854 }
9855
9856 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009857 // This is an erroneous use of an operator which can be overloaded by
9858 // a non-member function. Check for non-member operators which were
9859 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009860 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9861 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +00009862 // FIXME: Recover by calling the found function.
9863 return ExprError();
9864
John Wiegley01296292011-04-08 18:41:53 +00009865 // No viable function; fall through to handling this as a
9866 // built-in operator, which will produce an error message for us.
9867 break;
9868
9869 case OR_Ambiguous:
9870 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9871 << UnaryOperator::getOpcodeStr(Opc)
9872 << Input->getType()
9873 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009874 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9875 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +00009876 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9877 return ExprError();
9878
9879 case OR_Deleted:
9880 Diag(OpLoc, diag::err_ovl_deleted_oper)
9881 << Best->Function->isDeleted()
9882 << UnaryOperator::getOpcodeStr(Opc)
9883 << getDeletedOrUnavailableSuffix(Best->Function)
9884 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009885 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9886 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009887 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009888 return ExprError();
9889 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009890
9891 // Either we found no viable overloaded operator or we matched a
9892 // built-in operator. In either case, fall through to trying to
9893 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009894 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009895}
9896
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009897/// \brief Create a binary operation that may resolve to an overloaded
9898/// operator.
9899///
9900/// \param OpLoc The location of the operator itself (e.g., '+').
9901///
9902/// \param OpcIn The BinaryOperator::Opcode that describes this
9903/// operator.
9904///
9905/// \param Functions The set of non-member functions that will be
9906/// considered by overload resolution. The caller needs to build this
9907/// set based on the context using, e.g.,
9908/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9909/// set should not contain any member functions; those will be added
9910/// by CreateOverloadedBinOp().
9911///
9912/// \param LHS Left-hand argument.
9913/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009914ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009915Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009916 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009917 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009918 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009919 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009920 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009921
9922 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9923 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9924 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9925
9926 // If either side is type-dependent, create an appropriate dependent
9927 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009928 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009929 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009930 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009931 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009932 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009933 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009934 Context.DependentTy,
9935 VK_RValue, OK_Ordinary,
9936 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009937
Douglas Gregor5287f092009-11-05 00:51:44 +00009938 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9939 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009940 VK_LValue,
9941 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009942 Context.DependentTy,
9943 Context.DependentTy,
9944 OpLoc));
9945 }
John McCall4c4c1df2010-01-26 03:27:55 +00009946
9947 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009948 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009949 // TODO: provide better source location info in DNLoc component.
9950 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009951 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009952 = UnresolvedLookupExpr::Create(Context, NamingClass,
9953 NestedNameSpecifierLoc(), OpNameInfo,
9954 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009955 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009956 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009957 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009958 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009959 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009960 OpLoc));
9961 }
9962
John McCall4124c492011-10-17 18:40:02 +00009963 // Always do placeholder-like conversions on the RHS.
9964 if (checkPlaceholderForOverload(*this, Args[1]))
9965 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009966
John McCall526ab472011-10-25 17:37:35 +00009967 // Do placeholder-like conversion on the LHS; note that we should
9968 // not get here with a PseudoObject LHS.
9969 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009970 if (checkPlaceholderForOverload(*this, Args[0]))
9971 return ExprError();
9972
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009973 // If this is the assignment operator, we only perform overload resolution
9974 // if the left-hand side is a class or enumeration type. This is actually
9975 // a hack. The standard requires that we do overload resolution between the
9976 // various built-in candidates, but as DR507 points out, this can lead to
9977 // problems. So we do it this way, which pretty much follows what GCC does.
9978 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009979 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009980 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009981
John McCalle26a8722010-12-04 08:14:53 +00009982 // If this is the .* operator, which is not overloadable, just
9983 // create a built-in binary operator.
9984 if (Opc == BO_PtrMemD)
9985 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9986
Douglas Gregor084d8552009-03-13 23:49:33 +00009987 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009988 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009989
9990 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009991 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009992
9993 // Add operator candidates that are member functions.
9994 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9995
John McCall4c4c1df2010-01-26 03:27:55 +00009996 // Add candidates from ADL.
9997 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009998 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +00009999 /*ExplicitTemplateArgs*/ 0,
10000 CandidateSet);
10001
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010002 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010003 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010004
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010005 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10006
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010007 // Perform overload resolution.
10008 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010009 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010010 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010011 // We found a built-in operator or an overloaded operator.
10012 FunctionDecl *FnDecl = Best->Function;
10013
10014 if (FnDecl) {
10015 // We matched an overloaded operator. Build a call to that
10016 // operator.
10017
Eli Friedmanfa0df832012-02-02 03:46:19 +000010018 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010019
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010020 // Convert the arguments.
10021 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010022 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010023 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010024
Chandler Carruth8e543b32010-12-12 08:17:55 +000010025 ExprResult Arg1 =
10026 PerformCopyInitialization(
10027 InitializedEntity::InitializeParameter(Context,
10028 FnDecl->getParamDecl(0)),
10029 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010030 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010031 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010032
John Wiegley01296292011-04-08 18:41:53 +000010033 ExprResult Arg0 =
10034 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10035 Best->FoundDecl, Method);
10036 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010037 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010038 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010039 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010040 } else {
10041 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010042 ExprResult Arg0 = PerformCopyInitialization(
10043 InitializedEntity::InitializeParameter(Context,
10044 FnDecl->getParamDecl(0)),
10045 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010046 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010047 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010048
Chandler Carruth8e543b32010-12-12 08:17:55 +000010049 ExprResult Arg1 =
10050 PerformCopyInitialization(
10051 InitializedEntity::InitializeParameter(Context,
10052 FnDecl->getParamDecl(1)),
10053 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010054 if (Arg1.isInvalid())
10055 return ExprError();
10056 Args[0] = LHS = Arg0.takeAs<Expr>();
10057 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010058 }
10059
John McCall4fa0d5f2010-05-06 18:15:07 +000010060 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10061
John McCall7decc9e2010-11-18 06:31:45 +000010062 // Determine the result type.
10063 QualType ResultTy = FnDecl->getResultType();
10064 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10065 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010066
10067 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010068 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10069 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010070 if (FnExpr.isInvalid())
10071 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010072
John McCallb268a282010-08-23 23:25:46 +000010073 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010074 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010075 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010076
10077 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010078 FnDecl))
10079 return ExprError();
10080
John McCallb268a282010-08-23 23:25:46 +000010081 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010082 } else {
10083 // We matched a built-in operator. Convert the arguments, then
10084 // break out so that we will build the appropriate built-in
10085 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010086 ExprResult ArgsRes0 =
10087 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10088 Best->Conversions[0], AA_Passing);
10089 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010090 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010091 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010092
John Wiegley01296292011-04-08 18:41:53 +000010093 ExprResult ArgsRes1 =
10094 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10095 Best->Conversions[1], AA_Passing);
10096 if (ArgsRes1.isInvalid())
10097 return ExprError();
10098 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010099 break;
10100 }
10101 }
10102
Douglas Gregor66950a32009-09-30 21:46:01 +000010103 case OR_No_Viable_Function: {
10104 // C++ [over.match.oper]p9:
10105 // If the operator is the operator , [...] and there are no
10106 // viable functions, then the operator is assumed to be the
10107 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010108 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010109 break;
10110
Chandler Carruth8e543b32010-12-12 08:17:55 +000010111 // For class as left operand for assignment or compound assigment
10112 // operator do not fall through to handling in built-in, but report that
10113 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010114 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010115 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010116 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010117 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10118 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010119 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010120 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010121 // This is an erroneous use of an operator which can be overloaded by
10122 // a non-member function. Check for non-member operators which were
10123 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010124 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010125 // FIXME: Recover by calling the found function.
10126 return ExprError();
10127
Douglas Gregor66950a32009-09-30 21:46:01 +000010128 // No viable function; try to create a built-in operation, which will
10129 // produce an error. Then, show the non-viable candidates.
10130 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010132 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010133 "C++ binary operator overloading is missing candidates!");
10134 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010135 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010136 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010137 return move(Result);
10138 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010139
10140 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010141 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010142 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010143 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010144 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010145 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010146 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010147 return ExprError();
10148
10149 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010150 if (isImplicitlyDeleted(Best->Function)) {
10151 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10152 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10153 << getSpecialMember(Method)
10154 << BinaryOperator::getOpcodeStr(Opc)
10155 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010156
10157 if (getSpecialMember(Method) != CXXInvalid) {
10158 // The user probably meant to call this special member. Just
10159 // explain why it's deleted.
10160 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010161 return ExprError();
10162 }
10163 } else {
10164 Diag(OpLoc, diag::err_ovl_deleted_oper)
10165 << Best->Function->isDeleted()
10166 << BinaryOperator::getOpcodeStr(Opc)
10167 << getDeletedOrUnavailableSuffix(Best->Function)
10168 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10169 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010170 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010171 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010172 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010173 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010174
Douglas Gregor66950a32009-09-30 21:46:01 +000010175 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010176 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010177}
10178
John McCalldadc5752010-08-24 06:29:42 +000010179ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010180Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10181 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010182 Expr *Base, Expr *Idx) {
10183 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010184 DeclarationName OpName =
10185 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10186
10187 // If either side is type-dependent, create an appropriate dependent
10188 // expression.
10189 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10190
John McCall58cc69d2010-01-27 01:50:18 +000010191 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010192 // CHECKME: no 'operator' keyword?
10193 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10194 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010195 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010196 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010197 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010198 /*ADL*/ true, /*Overloaded*/ false,
10199 UnresolvedSetIterator(),
10200 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010201 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010202
Sebastian Redladba46e2009-10-29 20:17:01 +000010203 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10204 Args, 2,
10205 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010206 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010207 RLoc));
10208 }
10209
John McCall4124c492011-10-17 18:40:02 +000010210 // Handle placeholders on both operands.
10211 if (checkPlaceholderForOverload(*this, Args[0]))
10212 return ExprError();
10213 if (checkPlaceholderForOverload(*this, Args[1]))
10214 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010215
Sebastian Redladba46e2009-10-29 20:17:01 +000010216 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010217 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010218
10219 // Subscript can only be overloaded as a member function.
10220
10221 // Add operator candidates that are member functions.
10222 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10223
10224 // Add builtin operator candidates.
10225 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10226
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010227 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10228
Sebastian Redladba46e2009-10-29 20:17:01 +000010229 // Perform overload resolution.
10230 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010231 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010232 case OR_Success: {
10233 // We found a built-in operator or an overloaded operator.
10234 FunctionDecl *FnDecl = Best->Function;
10235
10236 if (FnDecl) {
10237 // We matched an overloaded operator. Build a call to that
10238 // operator.
10239
Eli Friedmanfa0df832012-02-02 03:46:19 +000010240 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010241
John McCalla0296f72010-03-19 07:35:19 +000010242 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010243 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010244
Sebastian Redladba46e2009-10-29 20:17:01 +000010245 // Convert the arguments.
10246 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010247 ExprResult Arg0 =
10248 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10249 Best->FoundDecl, Method);
10250 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010251 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010252 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010253
Anders Carlssona68e51e2010-01-29 18:37:50 +000010254 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010255 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010256 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010257 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010258 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010259 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010260 Owned(Args[1]));
10261 if (InputInit.isInvalid())
10262 return ExprError();
10263
10264 Args[1] = InputInit.takeAs<Expr>();
10265
Sebastian Redladba46e2009-10-29 20:17:01 +000010266 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010267 QualType ResultTy = FnDecl->getResultType();
10268 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10269 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010270
10271 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010272 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10273 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010274 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10275 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010276 OpLocInfo.getLoc(),
10277 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010278 if (FnExpr.isInvalid())
10279 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010280
John McCallb268a282010-08-23 23:25:46 +000010281 CXXOperatorCallExpr *TheCall =
10282 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010283 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010284 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010285
John McCallb268a282010-08-23 23:25:46 +000010286 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010287 FnDecl))
10288 return ExprError();
10289
John McCallb268a282010-08-23 23:25:46 +000010290 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010291 } else {
10292 // We matched a built-in operator. Convert the arguments, then
10293 // break out so that we will build the appropriate built-in
10294 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010295 ExprResult ArgsRes0 =
10296 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10297 Best->Conversions[0], AA_Passing);
10298 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010299 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010300 Args[0] = ArgsRes0.take();
10301
10302 ExprResult ArgsRes1 =
10303 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10304 Best->Conversions[1], AA_Passing);
10305 if (ArgsRes1.isInvalid())
10306 return ExprError();
10307 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010308
10309 break;
10310 }
10311 }
10312
10313 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010314 if (CandidateSet.empty())
10315 Diag(LLoc, diag::err_ovl_no_oper)
10316 << Args[0]->getType() << /*subscript*/ 0
10317 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10318 else
10319 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10320 << Args[0]->getType()
10321 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010322 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010323 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010324 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010325 }
10326
10327 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010328 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010329 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010330 << Args[0]->getType() << Args[1]->getType()
10331 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010332 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010333 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010334 return ExprError();
10335
10336 case OR_Deleted:
10337 Diag(LLoc, diag::err_ovl_deleted_oper)
10338 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010339 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010340 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010342 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010343 return ExprError();
10344 }
10345
10346 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010347 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010348}
10349
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010350/// BuildCallToMemberFunction - Build a call to a member
10351/// function. MemExpr is the expression that refers to the member
10352/// function (and includes the object parameter), Args/NumArgs are the
10353/// arguments to the function call (not including the object
10354/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010355/// expression refers to a non-static member function or an overloaded
10356/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010357ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010358Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10359 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010360 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010361 assert(MemExprE->getType() == Context.BoundMemberTy ||
10362 MemExprE->getType() == Context.OverloadTy);
10363
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010364 // Dig out the member expression. This holds both the object
10365 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010366 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010367
John McCall0009fcc2011-04-26 20:42:42 +000010368 // Determine whether this is a call to a pointer-to-member function.
10369 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10370 assert(op->getType() == Context.BoundMemberTy);
10371 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10372
10373 QualType fnType =
10374 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10375
10376 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10377 QualType resultType = proto->getCallResultType(Context);
10378 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10379
10380 // Check that the object type isn't more qualified than the
10381 // member function we're calling.
10382 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10383
10384 QualType objectType = op->getLHS()->getType();
10385 if (op->getOpcode() == BO_PtrMemI)
10386 objectType = objectType->castAs<PointerType>()->getPointeeType();
10387 Qualifiers objectQuals = objectType.getQualifiers();
10388
10389 Qualifiers difference = objectQuals - funcQuals;
10390 difference.removeObjCGCAttr();
10391 difference.removeAddressSpace();
10392 if (difference) {
10393 std::string qualsString = difference.getAsString();
10394 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10395 << fnType.getUnqualifiedType()
10396 << qualsString
10397 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10398 }
10399
10400 CXXMemberCallExpr *call
10401 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10402 resultType, valueKind, RParenLoc);
10403
10404 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010405 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010406 call, 0))
10407 return ExprError();
10408
10409 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10410 return ExprError();
10411
10412 return MaybeBindToTemporary(call);
10413 }
10414
John McCall4124c492011-10-17 18:40:02 +000010415 UnbridgedCastsSet UnbridgedCasts;
10416 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10417 return ExprError();
10418
John McCall10eae182009-11-30 22:42:35 +000010419 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010420 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010421 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010422 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010423 if (isa<MemberExpr>(NakedMemExpr)) {
10424 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010425 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010426 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010427 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010428 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010429 } else {
10430 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010431 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010432
John McCall6e9f8f62009-12-03 04:06:58 +000010433 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010434 Expr::Classification ObjectClassification
10435 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10436 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010437
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010438 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010439 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010440
John McCall2d74de92009-12-01 22:10:20 +000010441 // FIXME: avoid copy.
10442 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10443 if (UnresExpr->hasExplicitTemplateArgs()) {
10444 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10445 TemplateArgs = &TemplateArgsBuffer;
10446 }
10447
John McCall10eae182009-11-30 22:42:35 +000010448 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10449 E = UnresExpr->decls_end(); I != E; ++I) {
10450
John McCall6e9f8f62009-12-03 04:06:58 +000010451 NamedDecl *Func = *I;
10452 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10453 if (isa<UsingShadowDecl>(Func))
10454 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10455
Douglas Gregor02824322011-01-26 19:30:28 +000010456
Francois Pichet64225792011-01-18 05:04:39 +000010457 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010458 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010459 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10460 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010461 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010462 // If explicit template arguments were provided, we can't call a
10463 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010464 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010465 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010466
John McCalla0296f72010-03-19 07:35:19 +000010467 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010468 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010469 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010470 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010471 } else {
John McCall10eae182009-11-30 22:42:35 +000010472 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010473 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010474 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010475 llvm::makeArrayRef(Args, NumArgs),
10476 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010477 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010478 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010479 }
Mike Stump11289f42009-09-09 15:08:12 +000010480
John McCall10eae182009-11-30 22:42:35 +000010481 DeclarationName DeclName = UnresExpr->getMemberName();
10482
John McCall4124c492011-10-17 18:40:02 +000010483 UnbridgedCasts.restore();
10484
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010485 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010486 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010487 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010488 case OR_Success:
10489 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010490 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010491 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010492 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010493 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010494 break;
10495
10496 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010497 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010498 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010499 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010500 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10501 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010502 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010503 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010504
10505 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010506 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010507 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010508 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10509 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010510 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010511 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010512
10513 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010514 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010515 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010516 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010517 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010518 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010519 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10520 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010521 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010522 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010523 }
10524
John McCall16df1e52010-03-30 21:47:33 +000010525 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010526
John McCall2d74de92009-12-01 22:10:20 +000010527 // If overload resolution picked a static member, build a
10528 // non-member call based on that function.
10529 if (Method->isStatic()) {
10530 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10531 Args, NumArgs, RParenLoc);
10532 }
10533
John McCall10eae182009-11-30 22:42:35 +000010534 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010535 }
10536
John McCall7decc9e2010-11-18 06:31:45 +000010537 QualType ResultType = Method->getResultType();
10538 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10539 ResultType = ResultType.getNonLValueExprType(Context);
10540
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010541 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010542 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010543 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010544 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010545
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010546 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010547 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010548 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010549 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010550
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010551 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010552 // We only need to do this if there was actually an overload; otherwise
10553 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010554 if (!Method->isStatic()) {
10555 ExprResult ObjectArg =
10556 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10557 FoundDecl, Method);
10558 if (ObjectArg.isInvalid())
10559 return ExprError();
10560 MemExpr->setBase(ObjectArg.take());
10561 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010562
10563 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010564 const FunctionProtoType *Proto =
10565 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010566 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010567 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010568 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010569
Eli Friedmanff4b4072012-02-18 04:48:30 +000010570 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10571
John McCallb268a282010-08-23 23:25:46 +000010572 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010573 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010574
Anders Carlsson47061ee2011-05-06 14:25:31 +000010575 if ((isa<CXXConstructorDecl>(CurContext) ||
10576 isa<CXXDestructorDecl>(CurContext)) &&
10577 TheCall->getMethodDecl()->isPure()) {
10578 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10579
Chandler Carruth59259262011-06-27 08:31:58 +000010580 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010581 Diag(MemExpr->getLocStart(),
10582 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10583 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10584 << MD->getParent()->getDeclName();
10585
10586 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010587 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010588 }
John McCallb268a282010-08-23 23:25:46 +000010589 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010590}
10591
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010592/// BuildCallToObjectOfClassType - Build a call to an object of class
10593/// type (C++ [over.call.object]), which can end up invoking an
10594/// overloaded function call operator (@c operator()) or performing a
10595/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010596ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010597Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010598 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010599 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010600 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010601 if (checkPlaceholderForOverload(*this, Obj))
10602 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010603 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010604
10605 UnbridgedCastsSet UnbridgedCasts;
10606 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10607 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010608
John Wiegley01296292011-04-08 18:41:53 +000010609 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10610 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010611
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010612 // C++ [over.call.object]p1:
10613 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010614 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010615 // candidate functions includes at least the function call
10616 // operators of T. The function call operators of T are obtained by
10617 // ordinary lookup of the name operator() in the context of
10618 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010619 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010620 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010621
John Wiegley01296292011-04-08 18:41:53 +000010622 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010623 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010624 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010625
John McCall27b18f82009-11-17 02:14:36 +000010626 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10627 LookupQualifiedName(R, Record->getDecl());
10628 R.suppressDiagnostics();
10629
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010630 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010631 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010632 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10633 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010634 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010636
Douglas Gregorab7897a2008-11-19 22:57:39 +000010637 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010638 // In addition, for each (non-explicit in C++0x) conversion function
10639 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010640 //
10641 // operator conversion-type-id () cv-qualifier;
10642 //
10643 // where cv-qualifier is the same cv-qualification as, or a
10644 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010645 // denotes the type "pointer to function of (P1,...,Pn) returning
10646 // R", or the type "reference to pointer to function of
10647 // (P1,...,Pn) returning R", or the type "reference to function
10648 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010649 // is also considered as a candidate function. Similarly,
10650 // surrogate call functions are added to the set of candidate
10651 // functions for each conversion function declared in an
10652 // accessible base class provided the function is not hidden
10653 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010654 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010655 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010656 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010657 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010658 NamedDecl *D = *I;
10659 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10660 if (isa<UsingShadowDecl>(D))
10661 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010662
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010663 // Skip over templated conversion functions; they aren't
10664 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010665 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010666 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010667
John McCall6e9f8f62009-12-03 04:06:58 +000010668 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010669 if (!Conv->isExplicit()) {
10670 // Strip the reference type (if any) and then the pointer type (if
10671 // any) to get down to what might be a function type.
10672 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10673 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10674 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010675
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010676 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10677 {
10678 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010679 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10680 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010681 }
10682 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010683 }
Mike Stump11289f42009-09-09 15:08:12 +000010684
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010685 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10686
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010687 // Perform overload resolution.
10688 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010689 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010690 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010691 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010692 // Overload resolution succeeded; we'll build the appropriate call
10693 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010694 break;
10695
10696 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010697 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010698 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010699 << Object.get()->getType() << /*call*/ 1
10700 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010701 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010702 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010703 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010704 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010705 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10706 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010707 break;
10708
10709 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010710 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010711 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010712 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010713 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10714 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010715 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010716
10717 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010718 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010719 diag::err_ovl_deleted_object_call)
10720 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010721 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010722 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010723 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010724 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10725 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010726 break;
Mike Stump11289f42009-09-09 15:08:12 +000010727 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010728
Douglas Gregorb412e172010-07-25 18:17:45 +000010729 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010730 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010731
John McCall4124c492011-10-17 18:40:02 +000010732 UnbridgedCasts.restore();
10733
Douglas Gregorab7897a2008-11-19 22:57:39 +000010734 if (Best->Function == 0) {
10735 // Since there is no function declaration, this is one of the
10736 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010737 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010738 = cast<CXXConversionDecl>(
10739 Best->Conversions[0].UserDefined.ConversionFunction);
10740
John Wiegley01296292011-04-08 18:41:53 +000010741 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010742 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010743
Douglas Gregorab7897a2008-11-19 22:57:39 +000010744 // We selected one of the surrogate functions that converts the
10745 // object parameter to a function pointer. Perform the conversion
10746 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010747
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010748 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010749 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010750 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10751 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010752 if (Call.isInvalid())
10753 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010754 // Record usage of conversion in an implicit cast.
10755 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10756 CK_UserDefinedConversion,
10757 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010758
Douglas Gregor668443e2011-01-20 00:18:04 +000010759 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010760 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010761 }
10762
Eli Friedmanfa0df832012-02-02 03:46:19 +000010763 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010764 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010765 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010766
Douglas Gregorab7897a2008-11-19 22:57:39 +000010767 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10768 // that calls this method, using Object for the implicit object
10769 // parameter and passing along the remaining arguments.
10770 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010771 const FunctionProtoType *Proto =
10772 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010773
10774 unsigned NumArgsInProto = Proto->getNumArgs();
10775 unsigned NumArgsToCheck = NumArgs;
10776
10777 // Build the full argument list for the method call (the
10778 // implicit object parameter is placed at the beginning of the
10779 // list).
10780 Expr **MethodArgs;
10781 if (NumArgs < NumArgsInProto) {
10782 NumArgsToCheck = NumArgsInProto;
10783 MethodArgs = new Expr*[NumArgsInProto + 1];
10784 } else {
10785 MethodArgs = new Expr*[NumArgs + 1];
10786 }
John Wiegley01296292011-04-08 18:41:53 +000010787 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010788 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10789 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010790
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010791 DeclarationNameInfo OpLocInfo(
10792 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10793 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010794 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010795 HadMultipleCandidates,
10796 OpLocInfo.getLoc(),
10797 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010798 if (NewFn.isInvalid())
10799 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010800
10801 // Once we've built TheCall, all of the expressions are properly
10802 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010803 QualType ResultTy = Method->getResultType();
10804 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10805 ResultTy = ResultTy.getNonLValueExprType(Context);
10806
John McCallb268a282010-08-23 23:25:46 +000010807 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010808 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010809 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010810 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010811 delete [] MethodArgs;
10812
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010813 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010814 Method))
10815 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010816
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010817 // We may have default arguments. If so, we need to allocate more
10818 // slots in the call for them.
10819 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010820 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010821 else if (NumArgs > NumArgsInProto)
10822 NumArgsToCheck = NumArgsInProto;
10823
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010824 bool IsError = false;
10825
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010826 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010827 ExprResult ObjRes =
10828 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10829 Best->FoundDecl, Method);
10830 if (ObjRes.isInvalid())
10831 IsError = true;
10832 else
10833 Object = move(ObjRes);
10834 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010835
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010836 // Check the argument types.
10837 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010838 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010839 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010840 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010841
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010842 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010843
John McCalldadc5752010-08-24 06:29:42 +000010844 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010845 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010846 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010847 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010848 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010849
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010850 IsError |= InputInit.isInvalid();
10851 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010852 } else {
John McCalldadc5752010-08-24 06:29:42 +000010853 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010854 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10855 if (DefArg.isInvalid()) {
10856 IsError = true;
10857 break;
10858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010859
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010860 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010861 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010862
10863 TheCall->setArg(i + 1, Arg);
10864 }
10865
10866 // If this is a variadic call, handle args passed through "...".
10867 if (Proto->isVariadic()) {
10868 // Promote the arguments (C99 6.5.2.2p7).
10869 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010870 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10871 IsError |= Arg.isInvalid();
10872 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010873 }
10874 }
10875
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010876 if (IsError) return true;
10877
Eli Friedmanff4b4072012-02-18 04:48:30 +000010878 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10879
John McCallb268a282010-08-23 23:25:46 +000010880 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010881 return true;
10882
John McCalle172be52010-08-24 06:09:16 +000010883 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010884}
10885
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010886/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010887/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010888/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010889ExprResult
John McCallb268a282010-08-23 23:25:46 +000010890Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010891 assert(Base->getType()->isRecordType() &&
10892 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010893
John McCall4124c492011-10-17 18:40:02 +000010894 if (checkPlaceholderForOverload(*this, Base))
10895 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010896
John McCallbc077cf2010-02-08 23:07:23 +000010897 SourceLocation Loc = Base->getExprLoc();
10898
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010899 // C++ [over.ref]p1:
10900 //
10901 // [...] An expression x->m is interpreted as (x.operator->())->m
10902 // for a class object x of type T if T::operator->() exists and if
10903 // the operator is selected as the best match function by the
10904 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010905 DeclarationName OpName =
10906 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010907 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010908 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010909
John McCallbc077cf2010-02-08 23:07:23 +000010910 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010911 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000010912 return ExprError();
10913
John McCall27b18f82009-11-17 02:14:36 +000010914 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10915 LookupQualifiedName(R, BaseRecord->getDecl());
10916 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010917
10918 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010919 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010920 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10921 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010922 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010923
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010924 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10925
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010926 // Perform overload resolution.
10927 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010928 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010929 case OR_Success:
10930 // Overload resolution succeeded; we'll build the call below.
10931 break;
10932
10933 case OR_No_Viable_Function:
10934 if (CandidateSet.empty())
10935 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010936 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010937 else
10938 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010939 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010940 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010941 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010942
10943 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010944 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10945 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010946 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010947 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010948
10949 case OR_Deleted:
10950 Diag(OpLoc, diag::err_ovl_deleted_oper)
10951 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010952 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010953 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010954 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010955 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010956 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010957 }
10958
Eli Friedmanfa0df832012-02-02 03:46:19 +000010959 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010960 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010961 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010962
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010963 // Convert the object parameter.
10964 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010965 ExprResult BaseResult =
10966 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10967 Best->FoundDecl, Method);
10968 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010969 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010970 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010971
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010972 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010973 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010974 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010975 if (FnExpr.isInvalid())
10976 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010977
John McCall7decc9e2010-11-18 06:31:45 +000010978 QualType ResultTy = Method->getResultType();
10979 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10980 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010981 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010982 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010983 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010984
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010985 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010986 Method))
10987 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010988
10989 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010990}
10991
Richard Smithbcc22fc2012-03-09 08:00:36 +000010992/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10993/// a literal operator described by the provided lookup results.
10994ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10995 DeclarationNameInfo &SuffixInfo,
10996 ArrayRef<Expr*> Args,
10997 SourceLocation LitEndLoc,
10998 TemplateArgumentListInfo *TemplateArgs) {
10999 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011000
Richard Smithbcc22fc2012-03-09 08:00:36 +000011001 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11002 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11003 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011004
Richard Smithbcc22fc2012-03-09 08:00:36 +000011005 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11006
Richard Smithbcc22fc2012-03-09 08:00:36 +000011007 // Perform overload resolution. This will usually be trivial, but might need
11008 // to perform substitutions for a literal operator template.
11009 OverloadCandidateSet::iterator Best;
11010 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11011 case OR_Success:
11012 case OR_Deleted:
11013 break;
11014
11015 case OR_No_Viable_Function:
11016 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11017 << R.getLookupName();
11018 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11019 return ExprError();
11020
11021 case OR_Ambiguous:
11022 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11023 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11024 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011025 }
11026
Richard Smithbcc22fc2012-03-09 08:00:36 +000011027 FunctionDecl *FD = Best->Function;
11028 MarkFunctionReferenced(UDSuffixLoc, FD);
11029 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011030
Richard Smithbcc22fc2012-03-09 08:00:36 +000011031 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11032 SuffixInfo.getLoc(),
11033 SuffixInfo.getInfo());
11034 if (Fn.isInvalid())
11035 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011036
11037 // Check the argument types. This should almost always be a no-op, except
11038 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011039 Expr *ConvArgs[2];
11040 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11041 ExprResult InputInit = PerformCopyInitialization(
11042 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11043 SourceLocation(), Args[ArgIdx]);
11044 if (InputInit.isInvalid())
11045 return true;
11046 ConvArgs[ArgIdx] = InputInit.take();
11047 }
11048
Richard Smithc67fdd42012-03-07 08:35:16 +000011049 QualType ResultTy = FD->getResultType();
11050 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11051 ResultTy = ResultTy.getNonLValueExprType(Context);
11052
Richard Smithc67fdd42012-03-07 08:35:16 +000011053 UserDefinedLiteral *UDL =
11054 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11055 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11056
11057 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11058 return ExprError();
11059
11060 if (CheckFunctionCall(FD, UDL))
11061 return ExprError();
11062
11063 return MaybeBindToTemporary(UDL);
11064}
11065
Douglas Gregorcd695e52008-11-10 20:40:00 +000011066/// FixOverloadedFunctionReference - E is an expression that refers to
11067/// a C++ overloaded function (possibly with some parentheses and
11068/// perhaps a '&' around it). We have resolved the overloaded function
11069/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011070/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011071Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011072 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011073 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011074 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11075 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011076 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011077 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011078
Douglas Gregor51c538b2009-11-20 19:42:02 +000011079 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011080 }
11081
Douglas Gregor51c538b2009-11-20 19:42:02 +000011082 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011083 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11084 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011085 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011086 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011087 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011088 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011089 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011090 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011091
11092 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011093 ICE->getCastKind(),
11094 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011095 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011096 }
11097
Douglas Gregor51c538b2009-11-20 19:42:02 +000011098 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011099 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011100 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011101 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11102 if (Method->isStatic()) {
11103 // Do nothing: static member functions aren't any different
11104 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011105 } else {
John McCalle66edc12009-11-24 19:00:30 +000011106 // Fix the sub expression, which really has to be an
11107 // UnresolvedLookupExpr holding an overloaded member function
11108 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011109 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11110 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011111 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011112 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011113
John McCalld14a8642009-11-21 08:51:07 +000011114 assert(isa<DeclRefExpr>(SubExpr)
11115 && "fixed to something other than a decl ref");
11116 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11117 && "fixed to a member ref with no nested name qualifier");
11118
11119 // We have taken the address of a pointer to member
11120 // function. Perform the computation here so that we get the
11121 // appropriate pointer to member type.
11122 QualType ClassType
11123 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11124 QualType MemPtrType
11125 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11126
John McCall7decc9e2010-11-18 06:31:45 +000011127 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11128 VK_RValue, OK_Ordinary,
11129 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011130 }
11131 }
John McCall16df1e52010-03-30 21:47:33 +000011132 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11133 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011134 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011135 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011136
John McCalle3027922010-08-25 11:45:40 +000011137 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011138 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011139 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011140 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011141 }
John McCalld14a8642009-11-21 08:51:07 +000011142
11143 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011144 // FIXME: avoid copy.
11145 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011146 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011147 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11148 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011149 }
11150
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011151 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11152 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011153 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011154 Fn,
John McCall113bee02012-03-10 09:33:50 +000011155 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011156 ULE->getNameLoc(),
11157 Fn->getType(),
11158 VK_LValue,
11159 Found.getDecl(),
11160 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011161 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011162 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11163 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011164 }
11165
John McCall10eae182009-11-30 22:42:35 +000011166 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011167 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011168 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11169 if (MemExpr->hasExplicitTemplateArgs()) {
11170 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11171 TemplateArgs = &TemplateArgsBuffer;
11172 }
John McCall6b51f282009-11-23 01:53:49 +000011173
John McCall2d74de92009-12-01 22:10:20 +000011174 Expr *Base;
11175
John McCall7decc9e2010-11-18 06:31:45 +000011176 // If we're filling in a static method where we used to have an
11177 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011178 if (MemExpr->isImplicitAccess()) {
11179 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011180 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11181 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011182 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011183 Fn,
John McCall113bee02012-03-10 09:33:50 +000011184 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011185 MemExpr->getMemberLoc(),
11186 Fn->getType(),
11187 VK_LValue,
11188 Found.getDecl(),
11189 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011190 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011191 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11192 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011193 } else {
11194 SourceLocation Loc = MemExpr->getMemberLoc();
11195 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011196 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011197 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011198 Base = new (Context) CXXThisExpr(Loc,
11199 MemExpr->getBaseType(),
11200 /*isImplicit=*/true);
11201 }
John McCall2d74de92009-12-01 22:10:20 +000011202 } else
John McCallc3007a22010-10-26 07:05:15 +000011203 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011204
John McCall4adb38c2011-04-27 00:36:17 +000011205 ExprValueKind valueKind;
11206 QualType type;
11207 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11208 valueKind = VK_LValue;
11209 type = Fn->getType();
11210 } else {
11211 valueKind = VK_RValue;
11212 type = Context.BoundMemberTy;
11213 }
11214
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011215 MemberExpr *ME = MemberExpr::Create(Context, Base,
11216 MemExpr->isArrow(),
11217 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011218 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011219 Fn,
11220 Found,
11221 MemExpr->getMemberNameInfo(),
11222 TemplateArgs,
11223 type, valueKind, OK_Ordinary);
11224 ME->setHadMultipleCandidates(true);
11225 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011227
John McCallc3007a22010-10-26 07:05:15 +000011228 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011229}
11230
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011231ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011232 DeclAccessPair Found,
11233 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011234 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011235}
11236
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011237} // end namespace clang