blob: be0243403b5e623fc3971e2c003f34e9a9fc7d27 [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 Gregor26bee0b2008-10-31 16:23:19 +00001297/// IsStandardConversion - Determines whether there is a standard
1298/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1299/// expression From to the type ToType. Standard conversion sequences
1300/// only consider non-class types; for conversions that involve class
1301/// types, use TryImplicitConversion. If a conversion exists, SCS will
1302/// contain the standard conversion sequence required to perform this
1303/// conversion and this routine will return true. Otherwise, this
1304/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001305static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1306 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001307 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001308 bool CStyle,
1309 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001310 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001312 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001313 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001314 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001315 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001316 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001317 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001318
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001319 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001320 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001321 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001322 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001323 return false;
1324
Mike Stump11289f42009-09-09 15:08:12 +00001325 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001326 }
1327
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001328 // The first conversion can be an lvalue-to-rvalue conversion,
1329 // array-to-pointer conversion, or function-to-pointer conversion
1330 // (C++ 4p1).
1331
John McCall5c32be02010-08-24 20:38:10 +00001332 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001333 DeclAccessPair AccessPair;
1334 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001336 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001337 // We were able to resolve the address of the overloaded function,
1338 // so we can convert to the type of that function.
1339 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001340
1341 // we can sometimes resolve &foo<int> regardless of ToType, so check
1342 // if the type matches (identity) or we are converting to bool
1343 if (!S.Context.hasSameUnqualifiedType(
1344 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1345 QualType resultTy;
1346 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001347 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001348 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1349 // otherwise, only a boolean conversion is standard
1350 if (!ToType->isBooleanType())
1351 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353
Chandler Carruthffce2452011-03-29 08:08:18 +00001354 // Check if the "from" expression is taking the address of an overloaded
1355 // function and recompute the FromType accordingly. Take advantage of the
1356 // fact that non-static member functions *must* have such an address-of
1357 // expression.
1358 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1359 if (Method && !Method->isStatic()) {
1360 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1361 "Non-unary operator on non-static member address");
1362 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1363 == UO_AddrOf &&
1364 "Non-address-of operator on non-static member address");
1365 const Type *ClassType
1366 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1367 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001368 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1369 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1370 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001371 "Non-address-of operator for overloaded function expression");
1372 FromType = S.Context.getPointerType(FromType);
1373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregor980fb162010-04-29 18:24:40 +00001375 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001376 assert(S.Context.hasSameType(
1377 FromType,
1378 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001379 } else {
1380 return false;
1381 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001382 }
John McCall154a2fd2011-08-30 00:57:29 +00001383 // Lvalue-to-rvalue conversion (C++11 4.1):
1384 // A glvalue (3.10) of a non-function, non-array type T can
1385 // be converted to a prvalue.
1386 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001387 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001388 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001389 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001390 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001391
1392 // If T is a non-class type, the type of the rvalue is the
1393 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001394 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1395 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001396 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001397 } else if (FromType->isArrayType()) {
1398 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001399 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400
1401 // An lvalue or rvalue of type "array of N T" or "array of unknown
1402 // bound of T" can be converted to an rvalue of type "pointer to
1403 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001404 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405
John McCall5c32be02010-08-24 20:38:10 +00001406 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001408 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409
1410 // For the purpose of ranking in overload resolution
1411 // (13.3.3.1.1), this conversion is considered an
1412 // array-to-pointer conversion followed by a qualification
1413 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001414 SCS.Second = ICK_Identity;
1415 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001416 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001417 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001418 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001419 }
John McCall086a4642010-11-24 05:12:34 +00001420 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001421 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001422 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001423
1424 // An lvalue of function type T can be converted to an rvalue of
1425 // type "pointer to T." The result is a pointer to the
1426 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001427 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001428 } else {
1429 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001430 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001431 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001432 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001433
1434 // The second conversion can be an integral promotion, floating
1435 // point promotion, integral conversion, floating point conversion,
1436 // floating-integral conversion, pointer conversion,
1437 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001438 // For overloading in C, this can also be a "compatible-type"
1439 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001440 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001441 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001442 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001443 // The unqualified versions of the types are the same: there's no
1444 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001445 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001446 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001447 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001448 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001449 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001450 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001451 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001452 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001454 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001455 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001456 SCS.Second = ICK_Complex_Promotion;
1457 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001458 } else if (ToType->isBooleanType() &&
1459 (FromType->isArithmeticType() ||
1460 FromType->isAnyPointerType() ||
1461 FromType->isBlockPointerType() ||
1462 FromType->isMemberPointerType() ||
1463 FromType->isNullPtrType())) {
1464 // Boolean conversions (C++ 4.12).
1465 SCS.Second = ICK_Boolean_Conversion;
1466 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001467 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001468 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001469 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001472 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001473 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001474 SCS.Second = ICK_Complex_Conversion;
1475 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001476 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1477 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001478 // Complex-real conversions (C99 6.3.1.7)
1479 SCS.Second = ICK_Complex_Real;
1480 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001481 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001482 // Floating point conversions (C++ 4.8).
1483 SCS.Second = ICK_Floating_Conversion;
1484 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001486 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001487 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001488 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001489 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001490 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001491 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001492 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001493 SCS.Second = ICK_Block_Pointer_Conversion;
1494 } else if (AllowObjCWritebackConversion &&
1495 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1496 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001497 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1498 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001499 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001501 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001502 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001504 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001505 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001506 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001507 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001508 SCS.Second = SecondICK;
1509 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001510 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001511 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001512 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001513 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001514 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001515 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001516 // Treat a conversion that strips "noreturn" as an identity conversion.
1517 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001518 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1519 InOverloadResolution,
1520 SCS, CStyle)) {
1521 SCS.Second = ICK_TransparentUnionConversion;
1522 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523 } else {
1524 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001525 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001526 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001527 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001528
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001529 QualType CanonFrom;
1530 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001532 bool ObjCLifetimeConversion;
1533 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1534 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001535 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001536 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001538 CanonFrom = S.Context.getCanonicalType(FromType);
1539 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001540 } else {
1541 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 SCS.Third = ICK_Identity;
1543
Mike Stump11289f42009-09-09 15:08:12 +00001544 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545 // [...] Any difference in top-level cv-qualification is
1546 // subsumed by the initialization itself and does not constitute
1547 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001548 CanonFrom = S.Context.getCanonicalType(FromType);
1549 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001550 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001551 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001552 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001553 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1554 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001555 FromType = ToType;
1556 CanonFrom = CanonTo;
1557 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001559 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560
1561 // If we have not converted the argument type to the parameter type,
1562 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001563 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001568
1569static bool
1570IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1571 QualType &ToType,
1572 bool InOverloadResolution,
1573 StandardConversionSequence &SCS,
1574 bool CStyle) {
1575
1576 const RecordType *UT = ToType->getAsUnionType();
1577 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1578 return false;
1579 // The field to initialize within the transparent union.
1580 RecordDecl *UD = UT->getDecl();
1581 // It's compatible if the expression matches any of the fields.
1582 for (RecordDecl::field_iterator it = UD->field_begin(),
1583 itend = UD->field_end();
1584 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001585 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1586 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001587 ToType = it->getType();
1588 return true;
1589 }
1590 }
1591 return false;
1592}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593
1594/// IsIntegralPromotion - Determines whether the conversion from the
1595/// expression From (whose potentially-adjusted type is FromType) to
1596/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1597/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001598bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001599 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001600 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001601 if (!To) {
1602 return false;
1603 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604
1605 // An rvalue of type char, signed char, unsigned char, short int, or
1606 // unsigned short int can be converted to an rvalue of type int if
1607 // int can represent all the values of the source type; otherwise,
1608 // the source rvalue can be converted to an rvalue of type unsigned
1609 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001610 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1611 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 if (// We can promote any signed, promotable integer type to an int
1613 (FromType->isSignedIntegerType() ||
1614 // We can promote any unsigned integer type whose size is
1615 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001616 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001617 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001618 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001619 }
1620
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001621 return To->getKind() == BuiltinType::UInt;
1622 }
1623
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624 // C++0x [conv.prom]p3:
1625 // A prvalue of an unscoped enumeration type whose underlying type is not
1626 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1627 // following types that can represent all the values of the enumeration
1628 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1629 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001630 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001632 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633 // with lowest integer conversion rank (4.13) greater than the rank of long
1634 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001635 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001636 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1637 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1638 // provided for a scoped enumeration.
1639 if (FromEnumType->getDecl()->isScoped())
1640 return false;
1641
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001642 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001644 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001645 return Context.hasSameUnqualifiedType(ToType,
1646 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001647 }
John McCall56774992009-12-09 09:09:27 +00001648
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001649 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1651 // to an rvalue a prvalue of the first of the following types that can
1652 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001653 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001655 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001657 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001659 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001660 // Determine whether the type we're converting from is signed or
1661 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001662 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001664
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 // The types we'll try to promote to, in the appropriate
1666 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001667 QualType PromoteTypes[6] = {
1668 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001669 Context.LongTy, Context.UnsignedLongTy ,
1670 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001672 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1674 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001675 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1677 // We found the type that we can promote to. If this is the
1678 // type we wanted, we have a promotion. Otherwise, no
1679 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001680 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681 }
1682 }
1683 }
1684
1685 // An rvalue for an integral bit-field (9.6) can be converted to an
1686 // rvalue of type int if int can represent all the values of the
1687 // bit-field; otherwise, it can be converted to unsigned int if
1688 // unsigned int can represent all the values of the bit-field. If
1689 // the bit-field is larger yet, no integral promotion applies to
1690 // it. If the bit-field has an enumerated type, it is treated as any
1691 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001692 // FIXME: We should delay checking of bit-fields until we actually perform the
1693 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001694 using llvm::APSInt;
1695 if (From)
1696 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001697 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001698 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001699 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1700 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1701 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001702
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001703 // Are we promoting to an int from a bitfield that fits in an int?
1704 if (BitWidth < ToSize ||
1705 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1706 return To->getKind() == BuiltinType::Int;
1707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001709 // Are we promoting to an unsigned int from an unsigned bitfield
1710 // that fits into an unsigned int?
1711 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1712 return To->getKind() == BuiltinType::UInt;
1713 }
Mike Stump11289f42009-09-09 15:08:12 +00001714
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001715 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001716 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719 // An rvalue of type bool can be converted to an rvalue of type int,
1720 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001721 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001723 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724
1725 return false;
1726}
1727
1728/// IsFloatingPointPromotion - Determines whether the conversion from
1729/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1730/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001731bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001732 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1733 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001734 /// An rvalue of type float can be converted to an rvalue of type
1735 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001736 if (FromBuiltin->getKind() == BuiltinType::Float &&
1737 ToBuiltin->getKind() == BuiltinType::Double)
1738 return true;
1739
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001740 // C99 6.3.1.5p1:
1741 // When a float is promoted to double or long double, or a
1742 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001744 (FromBuiltin->getKind() == BuiltinType::Float ||
1745 FromBuiltin->getKind() == BuiltinType::Double) &&
1746 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1747 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001748
1749 // Half can be promoted to float.
1750 if (FromBuiltin->getKind() == BuiltinType::Half &&
1751 ToBuiltin->getKind() == BuiltinType::Float)
1752 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001753 }
1754
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001755 return false;
1756}
1757
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001758/// \brief Determine if a conversion is a complex promotion.
1759///
1760/// A complex promotion is defined as a complex -> complex conversion
1761/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001762/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001763bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001764 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001765 if (!FromComplex)
1766 return false;
1767
John McCall9dd450b2009-09-21 23:43:11 +00001768 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001769 if (!ToComplex)
1770 return false;
1771
1772 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001773 ToComplex->getElementType()) ||
1774 IsIntegralPromotion(0, FromComplex->getElementType(),
1775 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001776}
1777
Douglas Gregor237f96c2008-11-26 23:31:11 +00001778/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1779/// the pointer type FromPtr to a pointer to type ToPointee, with the
1780/// same type qualifiers as FromPtr has on its pointee type. ToType,
1781/// if non-empty, will be a pointer to ToType that may or may not have
1782/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001783///
Mike Stump11289f42009-09-09 15:08:12 +00001784static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001785BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001786 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001787 ASTContext &Context,
1788 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001789 assert((FromPtr->getTypeClass() == Type::Pointer ||
1790 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1791 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001792
John McCall31168b02011-06-15 23:02:42 +00001793 /// Conversions to 'id' subsume cv-qualifier conversions.
1794 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001795 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796
1797 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001798 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001799 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001800 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001801
John McCall31168b02011-06-15 23:02:42 +00001802 if (StripObjCLifetime)
1803 Quals.removeObjCLifetime();
1804
Mike Stump11289f42009-09-09 15:08:12 +00001805 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001806 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001807 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001808 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001809 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001810
1811 // Build a pointer to ToPointee. It has the right qualifiers
1812 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001813 if (isa<ObjCObjectPointerType>(ToType))
1814 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001815 return Context.getPointerType(ToPointee);
1816 }
1817
1818 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001819 QualType QualifiedCanonToPointee
1820 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001822 if (isa<ObjCObjectPointerType>(ToType))
1823 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1824 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001825}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Mike Stump11289f42009-09-09 15:08:12 +00001827static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001828 bool InOverloadResolution,
1829 ASTContext &Context) {
1830 // Handle value-dependent integral null pointer constants correctly.
1831 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1832 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001833 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001834 return !InOverloadResolution;
1835
Douglas Gregor56751b52009-09-25 04:25:58 +00001836 return Expr->isNullPointerConstant(Context,
1837 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1838 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001839}
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841/// IsPointerConversion - Determines whether the conversion of the
1842/// expression From, which has the (possibly adjusted) type FromType,
1843/// can be converted to the type ToType via a pointer conversion (C++
1844/// 4.10). If so, returns true and places the converted type (that
1845/// might differ from ToType in its cv-qualifiers at some level) into
1846/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001847///
Douglas Gregora29dc052008-11-27 01:19:21 +00001848/// This routine also supports conversions to and from block pointers
1849/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1850/// pointers to interfaces. FIXME: Once we've determined the
1851/// appropriate overloading rules for Objective-C, we may want to
1852/// split the Objective-C checks into a different routine; however,
1853/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001854/// conversions, so for now they live here. IncompatibleObjC will be
1855/// set if the conversion is an allowed Objective-C conversion that
1856/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001857bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001858 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001859 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001860 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001861 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001862 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1863 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001864 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001865
Mike Stump11289f42009-09-09 15:08:12 +00001866 // Conversion from a null pointer constant to any Objective-C pointer type.
1867 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001868 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001869 ConvertedType = ToType;
1870 return true;
1871 }
1872
Douglas Gregor231d1c62008-11-27 00:15:41 +00001873 // Blocks: Block pointers can be converted to void*.
1874 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001875 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001876 ConvertedType = ToType;
1877 return true;
1878 }
1879 // Blocks: A null pointer constant can be converted to a block
1880 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001881 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001882 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001883 ConvertedType = ToType;
1884 return true;
1885 }
1886
Sebastian Redl576fd422009-05-10 18:38:11 +00001887 // If the left-hand-side is nullptr_t, the right side can be a null
1888 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001889 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001890 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001891 ConvertedType = ToType;
1892 return true;
1893 }
1894
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001895 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001896 if (!ToTypePtr)
1897 return false;
1898
1899 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001900 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001901 ConvertedType = ToType;
1902 return true;
1903 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001904
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001906 // , including objective-c pointers.
1907 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001908 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001909 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001910 ConvertedType = BuildSimilarlyQualifiedPointerType(
1911 FromType->getAs<ObjCObjectPointerType>(),
1912 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001913 ToType, Context);
1914 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001915 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001916 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001917 if (!FromTypePtr)
1918 return false;
1919
1920 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001921
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001923 // pointer conversion, so don't do all of the work below.
1924 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1925 return false;
1926
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927 // An rvalue of type "pointer to cv T," where T is an object type,
1928 // can be converted to an rvalue of type "pointer to cv void" (C++
1929 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001930 if (FromPointeeType->isIncompleteOrObjectType() &&
1931 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001932 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001933 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001934 ToType, Context,
1935 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001936 return true;
1937 }
1938
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001939 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001940 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001941 ToPointeeType->isVoidType()) {
1942 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1943 ToPointeeType,
1944 ToType, Context);
1945 return true;
1946 }
1947
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001948 // When we're overloading in C, we allow a special kind of pointer
1949 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001951 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001952 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001953 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001954 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001955 return true;
1956 }
1957
Douglas Gregor5c407d92008-10-23 00:40:37 +00001958 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001959 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001960 // An rvalue of type "pointer to cv D," where D is a class type,
1961 // can be converted to an rvalue of type "pointer to cv B," where
1962 // B is a base class (clause 10) of D. If B is an inaccessible
1963 // (clause 11) or ambiguous (10.2) base class of D, a program that
1964 // necessitates this conversion is ill-formed. The result of the
1965 // conversion is a pointer to the base class sub-object of the
1966 // derived class object. The null pointer value is converted to
1967 // the null pointer value of the destination type.
1968 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001969 // Note that we do not check for ambiguity or inaccessibility
1970 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001971 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001972 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001973 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001974 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001975 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001977 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001978 ToType, Context);
1979 return true;
1980 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001981
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001982 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1983 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1984 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1985 ToPointeeType,
1986 ToType, Context);
1987 return true;
1988 }
1989
Douglas Gregora119f102008-12-19 19:13:09 +00001990 return false;
1991}
Douglas Gregoraec25842011-04-26 23:16:46 +00001992
1993/// \brief Adopt the given qualifiers for the given type.
1994static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1995 Qualifiers TQs = T.getQualifiers();
1996
1997 // Check whether qualifiers already match.
1998 if (TQs == Qs)
1999 return T;
2000
2001 if (Qs.compatiblyIncludes(TQs))
2002 return Context.getQualifiedType(T, Qs);
2003
2004 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2005}
Douglas Gregora119f102008-12-19 19:13:09 +00002006
2007/// isObjCPointerConversion - Determines whether this is an
2008/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2009/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002010bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002011 QualType& ConvertedType,
2012 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002013 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002014 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregoraec25842011-04-26 23:16:46 +00002016 // The set of qualifiers on the type we're converting from.
2017 Qualifiers FromQualifiers = FromType.getQualifiers();
2018
Steve Naroff7cae42b2009-07-10 23:34:53 +00002019 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002020 const ObjCObjectPointerType* ToObjCPtr =
2021 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002022 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002023 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002024
Steve Naroff7cae42b2009-07-10 23:34:53 +00002025 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002026 // If the pointee types are the same (ignoring qualifications),
2027 // then this is not a pointer conversion.
2028 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2029 FromObjCPtr->getPointeeType()))
2030 return false;
2031
Douglas Gregoraec25842011-04-26 23:16:46 +00002032 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002033 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002034 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002035 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002036 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002037 return true;
2038 }
2039 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002040 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002041 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002042 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002043 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002044 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002045 return true;
2046 }
2047 // Objective C++: We're able to convert from a pointer to an
2048 // interface to a pointer to a different interface.
2049 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002050 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2051 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002052 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002053 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2054 FromObjCPtr->getPointeeType()))
2055 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002057 ToObjCPtr->getPointeeType(),
2058 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002059 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002060 return true;
2061 }
2062
2063 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2064 // Okay: this is some kind of implicit downcast of Objective-C
2065 // interfaces, which is permitted. However, we're going to
2066 // complain about it.
2067 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002069 ToObjCPtr->getPointeeType(),
2070 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002071 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002072 return true;
2073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002075 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002076 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002077 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002078 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002080 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002081 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002082 // to a block pointer type.
2083 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002084 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002085 return true;
2086 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002087 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002090 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002091 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002092 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002093 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002094 return true;
2095 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002096 else
Douglas Gregora119f102008-12-19 19:13:09 +00002097 return false;
2098
Douglas Gregor033f56d2008-12-23 00:53:59 +00002099 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002100 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002101 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002102 else if (const BlockPointerType *FromBlockPtr =
2103 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002104 FromPointeeType = FromBlockPtr->getPointeeType();
2105 else
Douglas Gregora119f102008-12-19 19:13:09 +00002106 return false;
2107
Douglas Gregora119f102008-12-19 19:13:09 +00002108 // If we have pointers to pointers, recursively check whether this
2109 // is an Objective-C conversion.
2110 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2111 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2112 IncompatibleObjC)) {
2113 // We always complain about this conversion.
2114 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002115 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002116 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002117 return true;
2118 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002119 // Allow conversion of pointee being objective-c pointer to another one;
2120 // as in I* to id.
2121 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2122 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2123 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2124 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002125
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002126 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002127 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002128 return true;
2129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregor033f56d2008-12-23 00:53:59 +00002131 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002132 // differences in the argument and result types are in Objective-C
2133 // pointer conversions. If so, we permit the conversion (but
2134 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002135 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002136 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002137 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002138 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002139 if (FromFunctionType && ToFunctionType) {
2140 // If the function types are exactly the same, this isn't an
2141 // Objective-C pointer conversion.
2142 if (Context.getCanonicalType(FromPointeeType)
2143 == Context.getCanonicalType(ToPointeeType))
2144 return false;
2145
2146 // Perform the quick checks that will tell us whether these
2147 // function types are obviously different.
2148 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2149 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2150 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2151 return false;
2152
2153 bool HasObjCConversion = false;
2154 if (Context.getCanonicalType(FromFunctionType->getResultType())
2155 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2156 // Okay, the types match exactly. Nothing to do.
2157 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2158 ToFunctionType->getResultType(),
2159 ConvertedType, IncompatibleObjC)) {
2160 // Okay, we have an Objective-C pointer conversion.
2161 HasObjCConversion = true;
2162 } else {
2163 // Function types are too different. Abort.
2164 return false;
2165 }
Mike Stump11289f42009-09-09 15:08:12 +00002166
Douglas Gregora119f102008-12-19 19:13:09 +00002167 // Check argument types.
2168 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2169 ArgIdx != NumArgs; ++ArgIdx) {
2170 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2171 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2172 if (Context.getCanonicalType(FromArgType)
2173 == Context.getCanonicalType(ToArgType)) {
2174 // Okay, the types match exactly. Nothing to do.
2175 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2176 ConvertedType, IncompatibleObjC)) {
2177 // Okay, we have an Objective-C pointer conversion.
2178 HasObjCConversion = true;
2179 } else {
2180 // Argument types are too different. Abort.
2181 return false;
2182 }
2183 }
2184
2185 if (HasObjCConversion) {
2186 // We had an Objective-C conversion. Allow this pointer
2187 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002189 IncompatibleObjC = true;
2190 return true;
2191 }
2192 }
2193
Sebastian Redl72b597d2009-01-25 19:43:20 +00002194 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002195}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
John McCall31168b02011-06-15 23:02:42 +00002197/// \brief Determine whether this is an Objective-C writeback conversion,
2198/// used for parameter passing when performing automatic reference counting.
2199///
2200/// \param FromType The type we're converting form.
2201///
2202/// \param ToType The type we're converting to.
2203///
2204/// \param ConvertedType The type that will be produced after applying
2205/// this conversion.
2206bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2207 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002208 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002209 Context.hasSameUnqualifiedType(FromType, ToType))
2210 return false;
2211
2212 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2213 QualType ToPointee;
2214 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2215 ToPointee = ToPointer->getPointeeType();
2216 else
2217 return false;
2218
2219 Qualifiers ToQuals = ToPointee.getQualifiers();
2220 if (!ToPointee->isObjCLifetimeType() ||
2221 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002222 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002223 return false;
2224
2225 // Argument must be a pointer to __strong to __weak.
2226 QualType FromPointee;
2227 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2228 FromPointee = FromPointer->getPointeeType();
2229 else
2230 return false;
2231
2232 Qualifiers FromQuals = FromPointee.getQualifiers();
2233 if (!FromPointee->isObjCLifetimeType() ||
2234 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2235 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2236 return false;
2237
2238 // Make sure that we have compatible qualifiers.
2239 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2240 if (!ToQuals.compatiblyIncludes(FromQuals))
2241 return false;
2242
2243 // Remove qualifiers from the pointee type we're converting from; they
2244 // aren't used in the compatibility check belong, and we'll be adding back
2245 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2246 FromPointee = FromPointee.getUnqualifiedType();
2247
2248 // The unqualified form of the pointee types must be compatible.
2249 ToPointee = ToPointee.getUnqualifiedType();
2250 bool IncompatibleObjC;
2251 if (Context.typesAreCompatible(FromPointee, ToPointee))
2252 FromPointee = ToPointee;
2253 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2254 IncompatibleObjC))
2255 return false;
2256
2257 /// \brief Construct the type we're converting to, which is a pointer to
2258 /// __autoreleasing pointee.
2259 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2260 ConvertedType = Context.getPointerType(FromPointee);
2261 return true;
2262}
2263
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002264bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2265 QualType& ConvertedType) {
2266 QualType ToPointeeType;
2267 if (const BlockPointerType *ToBlockPtr =
2268 ToType->getAs<BlockPointerType>())
2269 ToPointeeType = ToBlockPtr->getPointeeType();
2270 else
2271 return false;
2272
2273 QualType FromPointeeType;
2274 if (const BlockPointerType *FromBlockPtr =
2275 FromType->getAs<BlockPointerType>())
2276 FromPointeeType = FromBlockPtr->getPointeeType();
2277 else
2278 return false;
2279 // We have pointer to blocks, check whether the only
2280 // differences in the argument and result types are in Objective-C
2281 // pointer conversions. If so, we permit the conversion.
2282
2283 const FunctionProtoType *FromFunctionType
2284 = FromPointeeType->getAs<FunctionProtoType>();
2285 const FunctionProtoType *ToFunctionType
2286 = ToPointeeType->getAs<FunctionProtoType>();
2287
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002288 if (!FromFunctionType || !ToFunctionType)
2289 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002290
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002291 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002292 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002293
2294 // Perform the quick checks that will tell us whether these
2295 // function types are obviously different.
2296 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2297 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2298 return false;
2299
2300 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2301 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2302 if (FromEInfo != ToEInfo)
2303 return false;
2304
2305 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002306 if (Context.hasSameType(FromFunctionType->getResultType(),
2307 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002308 // Okay, the types match exactly. Nothing to do.
2309 } else {
2310 QualType RHS = FromFunctionType->getResultType();
2311 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002312 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002313 !RHS.hasQualifiers() && LHS.hasQualifiers())
2314 LHS = LHS.getUnqualifiedType();
2315
2316 if (Context.hasSameType(RHS,LHS)) {
2317 // OK exact match.
2318 } else if (isObjCPointerConversion(RHS, LHS,
2319 ConvertedType, IncompatibleObjC)) {
2320 if (IncompatibleObjC)
2321 return false;
2322 // Okay, we have an Objective-C pointer conversion.
2323 }
2324 else
2325 return false;
2326 }
2327
2328 // Check argument types.
2329 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2330 ArgIdx != NumArgs; ++ArgIdx) {
2331 IncompatibleObjC = false;
2332 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2333 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2334 if (Context.hasSameType(FromArgType, ToArgType)) {
2335 // Okay, the types match exactly. Nothing to do.
2336 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2337 ConvertedType, IncompatibleObjC)) {
2338 if (IncompatibleObjC)
2339 return false;
2340 // Okay, we have an Objective-C pointer conversion.
2341 } else
2342 // Argument types are too different. Abort.
2343 return false;
2344 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002345 if (LangOpts.ObjCAutoRefCount &&
2346 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2347 ToFunctionType))
2348 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002349
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002350 ConvertedType = ToType;
2351 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002352}
2353
Richard Trieucaff2472011-11-23 22:32:32 +00002354enum {
2355 ft_default,
2356 ft_different_class,
2357 ft_parameter_arity,
2358 ft_parameter_mismatch,
2359 ft_return_type,
2360 ft_qualifer_mismatch
2361};
2362
2363/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2364/// function types. Catches different number of parameter, mismatch in
2365/// parameter types, and different return types.
2366void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2367 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002368 // If either type is not valid, include no extra info.
2369 if (FromType.isNull() || ToType.isNull()) {
2370 PDiag << ft_default;
2371 return;
2372 }
2373
Richard Trieucaff2472011-11-23 22:32:32 +00002374 // Get the function type from the pointers.
2375 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2376 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2377 *ToMember = ToType->getAs<MemberPointerType>();
2378 if (FromMember->getClass() != ToMember->getClass()) {
2379 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2380 << QualType(FromMember->getClass(), 0);
2381 return;
2382 }
2383 FromType = FromMember->getPointeeType();
2384 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002385 }
2386
Richard Trieu96ed5b62011-12-13 23:19:45 +00002387 if (FromType->isPointerType())
2388 FromType = FromType->getPointeeType();
2389 if (ToType->isPointerType())
2390 ToType = ToType->getPointeeType();
2391
2392 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002393 FromType = FromType.getNonReferenceType();
2394 ToType = ToType.getNonReferenceType();
2395
Richard Trieucaff2472011-11-23 22:32:32 +00002396 // Don't print extra info for non-specialized template functions.
2397 if (FromType->isInstantiationDependentType() &&
2398 !FromType->getAs<TemplateSpecializationType>()) {
2399 PDiag << ft_default;
2400 return;
2401 }
2402
Richard Trieu96ed5b62011-12-13 23:19:45 +00002403 // No extra info for same types.
2404 if (Context.hasSameType(FromType, ToType)) {
2405 PDiag << ft_default;
2406 return;
2407 }
2408
Richard Trieucaff2472011-11-23 22:32:32 +00002409 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2410 *ToFunction = ToType->getAs<FunctionProtoType>();
2411
2412 // Both types need to be function types.
2413 if (!FromFunction || !ToFunction) {
2414 PDiag << ft_default;
2415 return;
2416 }
2417
2418 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2419 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2420 << FromFunction->getNumArgs();
2421 return;
2422 }
2423
2424 // Handle different parameter types.
2425 unsigned ArgPos;
2426 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2427 PDiag << ft_parameter_mismatch << ArgPos + 1
2428 << ToFunction->getArgType(ArgPos)
2429 << FromFunction->getArgType(ArgPos);
2430 return;
2431 }
2432
2433 // Handle different return type.
2434 if (!Context.hasSameType(FromFunction->getResultType(),
2435 ToFunction->getResultType())) {
2436 PDiag << ft_return_type << ToFunction->getResultType()
2437 << FromFunction->getResultType();
2438 return;
2439 }
2440
2441 unsigned FromQuals = FromFunction->getTypeQuals(),
2442 ToQuals = ToFunction->getTypeQuals();
2443 if (FromQuals != ToQuals) {
2444 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2445 return;
2446 }
2447
2448 // Unable to find a difference, so add no extra info.
2449 PDiag << ft_default;
2450}
2451
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002452/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002453/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002454/// they have same number of arguments. This routine assumes that Objective-C
2455/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002456/// If the parameters are different, ArgPos will have the the parameter index
2457/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002459 const FunctionProtoType *NewType,
2460 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002461 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002462 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2463 N = NewType->arg_type_begin(),
2464 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2465 if (!Context.hasSameType(*O, *N)) {
2466 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2467 return false;
2468 }
2469 }
2470 return true;
2471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002472
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002473 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2474 N = NewType->arg_type_begin(),
2475 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2476 QualType ToType = (*O);
2477 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002478 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002479 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2480 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002481 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2482 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2483 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2484 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002485 continue;
2486 }
John McCall8b07ec22010-05-15 11:32:37 +00002487 else if (const ObjCObjectPointerType *PTTo =
2488 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002490 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002491 if (Context.hasSameUnqualifiedType(
2492 PTTo->getObjectType()->getBaseType(),
2493 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002494 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002495 }
Richard Trieucaff2472011-11-23 22:32:32 +00002496 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002498 }
2499 }
2500 return true;
2501}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002502
Douglas Gregor39c16d42008-10-24 04:54:22 +00002503/// CheckPointerConversion - Check the pointer conversion from the
2504/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002505/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002506/// conversions for which IsPointerConversion has already returned
2507/// true. It returns true and produces a diagnostic if there was an
2508/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002509bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002510 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002511 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002512 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002513 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002514 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002515
John McCall8cb679e2010-11-15 09:13:47 +00002516 Kind = CK_BitCast;
2517
Chandler Carruthffab8732011-04-09 07:32:05 +00002518 if (!IsCStyleOrFunctionalCast &&
2519 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2520 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2521 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002522 PDiag(diag::warn_impcast_bool_to_null_pointer)
2523 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002524
John McCall9320b872011-09-09 05:25:32 +00002525 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2526 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002527 QualType FromPointeeType = FromPtrType->getPointeeType(),
2528 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002529
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002530 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2531 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002532 // We must have a derived-to-base conversion. Check an
2533 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002534 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2535 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002536 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002537 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002538 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002540 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002541 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002542 }
2543 }
John McCall9320b872011-09-09 05:25:32 +00002544 } else if (const ObjCObjectPointerType *ToPtrType =
2545 ToType->getAs<ObjCObjectPointerType>()) {
2546 if (const ObjCObjectPointerType *FromPtrType =
2547 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002548 // Objective-C++ conversions are always okay.
2549 // FIXME: We should have a different class of conversions for the
2550 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002551 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002552 return false;
John McCall9320b872011-09-09 05:25:32 +00002553 } else if (FromType->isBlockPointerType()) {
2554 Kind = CK_BlockPointerToObjCPointerCast;
2555 } else {
2556 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002557 }
John McCall9320b872011-09-09 05:25:32 +00002558 } else if (ToType->isBlockPointerType()) {
2559 if (!FromType->isBlockPointerType())
2560 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002561 }
John McCall8cb679e2010-11-15 09:13:47 +00002562
2563 // We shouldn't fall into this case unless it's valid for other
2564 // reasons.
2565 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2566 Kind = CK_NullToPointer;
2567
Douglas Gregor39c16d42008-10-24 04:54:22 +00002568 return false;
2569}
2570
Sebastian Redl72b597d2009-01-25 19:43:20 +00002571/// IsMemberPointerConversion - Determines whether the conversion of the
2572/// expression From, which has the (possibly adjusted) type FromType, can be
2573/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2574/// If so, returns true and places the converted type (that might differ from
2575/// ToType in its cv-qualifiers at some level) into ConvertedType.
2576bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002577 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002578 bool InOverloadResolution,
2579 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002580 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002581 if (!ToTypePtr)
2582 return false;
2583
2584 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002585 if (From->isNullPointerConstant(Context,
2586 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2587 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002588 ConvertedType = ToType;
2589 return true;
2590 }
2591
2592 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002593 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002594 if (!FromTypePtr)
2595 return false;
2596
2597 // A pointer to member of B can be converted to a pointer to member of D,
2598 // where D is derived from B (C++ 4.11p2).
2599 QualType FromClass(FromTypePtr->getClass(), 0);
2600 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002601
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002602 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2603 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2604 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002605 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2606 ToClass.getTypePtr());
2607 return true;
2608 }
2609
2610 return false;
2611}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612
Sebastian Redl72b597d2009-01-25 19:43:20 +00002613/// CheckMemberPointerConversion - Check the member pointer conversion from the
2614/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002615/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002616/// for which IsMemberPointerConversion has already returned true. It returns
2617/// true and produces a diagnostic if there was an error, or returns false
2618/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002619bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002620 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002621 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002622 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002623 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002624 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002625 if (!FromPtrType) {
2626 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002627 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002628 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002629 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002630 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002631 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002632 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002633
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002634 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002635 assert(ToPtrType && "No member pointer cast has a target type "
2636 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002637
Sebastian Redled8f2002009-01-28 18:33:18 +00002638 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2639 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002640
Sebastian Redled8f2002009-01-28 18:33:18 +00002641 // FIXME: What about dependent types?
2642 assert(FromClass->isRecordType() && "Pointer into non-class.");
2643 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002644
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002645 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002646 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002647 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2648 assert(DerivationOkay &&
2649 "Should not have been called if derivation isn't OK.");
2650 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002651
Sebastian Redled8f2002009-01-28 18:33:18 +00002652 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2653 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002654 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2655 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2656 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2657 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002658 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002659
Douglas Gregor89ee6822009-02-28 01:32:25 +00002660 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002661 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2662 << FromClass << ToClass << QualType(VBase, 0)
2663 << From->getSourceRange();
2664 return true;
2665 }
2666
John McCall5b0829a2010-02-10 09:31:12 +00002667 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002668 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2669 Paths.front(),
2670 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002671
Anders Carlssond7923c62009-08-22 23:33:40 +00002672 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002673 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002674 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002675 return false;
2676}
2677
Douglas Gregor9a657932008-10-21 23:43:52 +00002678/// IsQualificationConversion - Determines whether the conversion from
2679/// an rvalue of type FromType to ToType is a qualification conversion
2680/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002681///
2682/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2683/// when the qualification conversion involves a change in the Objective-C
2684/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002685bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002686Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002687 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002688 FromType = Context.getCanonicalType(FromType);
2689 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002690 ObjCLifetimeConversion = false;
2691
Douglas Gregor9a657932008-10-21 23:43:52 +00002692 // If FromType and ToType are the same type, this is not a
2693 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002694 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002695 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002696
Douglas Gregor9a657932008-10-21 23:43:52 +00002697 // (C++ 4.4p4):
2698 // A conversion can add cv-qualifiers at levels other than the first
2699 // in multi-level pointers, subject to the following rules: [...]
2700 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002701 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002702 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002703 // Within each iteration of the loop, we check the qualifiers to
2704 // determine if this still looks like a qualification
2705 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002706 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002707 // until there are no more pointers or pointers-to-members left to
2708 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002709 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002710
Douglas Gregor90609aa2011-04-25 18:40:17 +00002711 Qualifiers FromQuals = FromType.getQualifiers();
2712 Qualifiers ToQuals = ToType.getQualifiers();
2713
John McCall31168b02011-06-15 23:02:42 +00002714 // Objective-C ARC:
2715 // Check Objective-C lifetime conversions.
2716 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2717 UnwrappedAnyPointer) {
2718 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2719 ObjCLifetimeConversion = true;
2720 FromQuals.removeObjCLifetime();
2721 ToQuals.removeObjCLifetime();
2722 } else {
2723 // Qualification conversions cannot cast between different
2724 // Objective-C lifetime qualifiers.
2725 return false;
2726 }
2727 }
2728
Douglas Gregorf30053d2011-05-08 06:09:53 +00002729 // Allow addition/removal of GC attributes but not changing GC attributes.
2730 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2731 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2732 FromQuals.removeObjCGCAttr();
2733 ToQuals.removeObjCGCAttr();
2734 }
2735
Douglas Gregor9a657932008-10-21 23:43:52 +00002736 // -- for every j > 0, if const is in cv 1,j then const is in cv
2737 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002738 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002739 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002740
Douglas Gregor9a657932008-10-21 23:43:52 +00002741 // -- if the cv 1,j and cv 2,j are different, then const is in
2742 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002743 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002744 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002745 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002746
Douglas Gregor9a657932008-10-21 23:43:52 +00002747 // Keep track of whether all prior cv-qualifiers in the "to" type
2748 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002749 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002750 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002751 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002752
2753 // We are left with FromType and ToType being the pointee types
2754 // after unwrapping the original FromType and ToType the same number
2755 // of types. If we unwrapped any pointers, and if FromType and
2756 // ToType have the same unqualified type (since we checked
2757 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002758 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002759}
2760
Sebastian Redl82ace982012-02-11 23:51:08 +00002761static OverloadingResult
2762IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2763 CXXRecordDecl *To,
2764 UserDefinedConversionSequence &User,
2765 OverloadCandidateSet &CandidateSet,
2766 bool AllowExplicit) {
2767 DeclContext::lookup_iterator Con, ConEnd;
2768 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2769 Con != ConEnd; ++Con) {
2770 NamedDecl *D = *Con;
2771 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2772
2773 // Find the constructor (which may be a template).
2774 CXXConstructorDecl *Constructor = 0;
2775 FunctionTemplateDecl *ConstructorTmpl
2776 = dyn_cast<FunctionTemplateDecl>(D);
2777 if (ConstructorTmpl)
2778 Constructor
2779 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2780 else
2781 Constructor = cast<CXXConstructorDecl>(D);
2782
2783 bool Usable = !Constructor->isInvalidDecl() &&
2784 S.isInitListConstructor(Constructor) &&
2785 (AllowExplicit || !Constructor->isExplicit());
2786 if (Usable) {
2787 if (ConstructorTmpl)
2788 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2789 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002790 From, CandidateSet,
Sebastian Redl82ace982012-02-11 23:51:08 +00002791 /*SuppressUserConversions=*/true);
2792 else
2793 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002794 From, CandidateSet,
Sebastian Redl82ace982012-02-11 23:51:08 +00002795 /*SuppressUserConversions=*/true);
2796 }
2797 }
2798
2799 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2800
2801 OverloadCandidateSet::iterator Best;
2802 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2803 case OR_Success: {
2804 // Record the standard conversion we used and the conversion function.
2805 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2806 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2807
2808 QualType ThisType = Constructor->getThisType(S.Context);
2809 // Initializer lists don't have conversions as such.
2810 User.Before.setAsIdentityConversion();
2811 User.HadMultipleCandidates = HadMultipleCandidates;
2812 User.ConversionFunction = Constructor;
2813 User.FoundConversionFunction = Best->FoundDecl;
2814 User.After.setAsIdentityConversion();
2815 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2816 User.After.setAllToTypes(ToType);
2817 return OR_Success;
2818 }
2819
2820 case OR_No_Viable_Function:
2821 return OR_No_Viable_Function;
2822 case OR_Deleted:
2823 return OR_Deleted;
2824 case OR_Ambiguous:
2825 return OR_Ambiguous;
2826 }
2827
2828 llvm_unreachable("Invalid OverloadResult!");
2829}
2830
Douglas Gregor576e98c2009-01-30 23:27:23 +00002831/// Determines whether there is a user-defined conversion sequence
2832/// (C++ [over.ics.user]) that converts expression From to the type
2833/// ToType. If such a conversion exists, User will contain the
2834/// user-defined conversion sequence that performs such a conversion
2835/// and this routine will return true. Otherwise, this routine returns
2836/// false and User is unspecified.
2837///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002838/// \param AllowExplicit true if the conversion should consider C++0x
2839/// "explicit" conversion functions as well as non-explicit conversion
2840/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002841static OverloadingResult
2842IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002843 UserDefinedConversionSequence &User,
2844 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002845 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002846 // Whether we will only visit constructors.
2847 bool ConstructorsOnly = false;
2848
2849 // If the type we are conversion to is a class type, enumerate its
2850 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002851 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002852 // C++ [over.match.ctor]p1:
2853 // When objects of class type are direct-initialized (8.5), or
2854 // copy-initialized from an expression of the same or a
2855 // derived class type (8.5), overload resolution selects the
2856 // constructor. [...] For copy-initialization, the candidate
2857 // functions are all the converting constructors (12.3.1) of
2858 // that class. The argument list is the expression-list within
2859 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002860 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002861 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002862 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002863 ConstructorsOnly = true;
2864
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002865 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2866 // RequireCompleteType may have returned true due to some invalid decl
2867 // during template instantiation, but ToType may be complete enough now
2868 // to try to recover.
2869 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002870 // We're not going to find any constructors.
2871 } else if (CXXRecordDecl *ToRecordDecl
2872 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002873
2874 Expr **Args = &From;
2875 unsigned NumArgs = 1;
2876 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002877 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002878 // But first, see if there is an init-list-contructor that will work.
2879 OverloadingResult Result = IsInitializerListConstructorConversion(
2880 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2881 if (Result != OR_No_Viable_Function)
2882 return Result;
2883 // Never mind.
2884 CandidateSet.clear();
2885
2886 // If we're list-initializing, we pass the individual elements as
2887 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002888 Args = InitList->getInits();
2889 NumArgs = InitList->getNumInits();
2890 ListInitializing = true;
2891 }
2892
Douglas Gregor89ee6822009-02-28 01:32:25 +00002893 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002894 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002895 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002896 NamedDecl *D = *Con;
2897 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2898
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002899 // Find the constructor (which may be a template).
2900 CXXConstructorDecl *Constructor = 0;
2901 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002902 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002903 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002904 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002905 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2906 else
John McCalla0296f72010-03-19 07:35:19 +00002907 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002908
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002909 bool Usable = !Constructor->isInvalidDecl();
2910 if (ListInitializing)
2911 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2912 else
2913 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2914 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00002915 bool SuppressUserConversions = !ConstructorsOnly;
2916 if (SuppressUserConversions && ListInitializing) {
2917 SuppressUserConversions = false;
2918 if (NumArgs == 1) {
2919 // If the first argument is (a reference to) the target type,
2920 // suppress conversions.
2921 const FunctionProtoType *CtorType =
2922 Constructor->getType()->getAs<FunctionProtoType>();
2923 if (CtorType->getNumArgs() > 0) {
2924 QualType FirstArg = CtorType->getArgType(0);
2925 if (S.Context.hasSameUnqualifiedType(ToType,
2926 FirstArg.getNonReferenceType())) {
2927 SuppressUserConversions = true;
2928 }
2929 }
2930 }
2931 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002932 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002933 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2934 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002935 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002936 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002937 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002938 // Allow one user-defined conversion when user specifies a
2939 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002940 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002941 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002942 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002943 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002944 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002945 }
2946 }
2947
Douglas Gregor5ab11652010-04-17 22:01:05 +00002948 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002949 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002950 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2951 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002952 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002953 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002954 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002955 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002956 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2957 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002958 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002959 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002960 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002961 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002962 DeclAccessPair FoundDecl = I.getPair();
2963 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002964 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2965 if (isa<UsingShadowDecl>(D))
2966 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2967
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002968 CXXConversionDecl *Conv;
2969 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002970 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2971 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002972 else
John McCallda4458e2010-03-31 01:36:47 +00002973 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002974
2975 if (AllowExplicit || !Conv->isExplicit()) {
2976 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002977 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2978 ActingContext, From, ToType,
2979 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002980 else
John McCall5c32be02010-08-24 20:38:10 +00002981 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2982 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002983 }
2984 }
2985 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002986 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002987
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002988 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2989
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002990 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002991 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002992 case OR_Success:
2993 // Record the standard conversion we used and the conversion function.
2994 if (CXXConstructorDecl *Constructor
2995 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002996 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00002997
John McCall5c32be02010-08-24 20:38:10 +00002998 // C++ [over.ics.user]p1:
2999 // If the user-defined conversion is specified by a
3000 // constructor (12.3.1), the initial standard conversion
3001 // sequence converts the source type to the type required by
3002 // the argument of the constructor.
3003 //
3004 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003005 if (isa<InitListExpr>(From)) {
3006 // Initializer lists don't have conversions as such.
3007 User.Before.setAsIdentityConversion();
3008 } else {
3009 if (Best->Conversions[0].isEllipsis())
3010 User.EllipsisConversion = true;
3011 else {
3012 User.Before = Best->Conversions[0].Standard;
3013 User.EllipsisConversion = false;
3014 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003015 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003016 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003017 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003018 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003019 User.After.setAsIdentityConversion();
3020 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3021 User.After.setAllToTypes(ToType);
3022 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003023 }
3024 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003025 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003026 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003027
John McCall5c32be02010-08-24 20:38:10 +00003028 // C++ [over.ics.user]p1:
3029 //
3030 // [...] If the user-defined conversion is specified by a
3031 // conversion function (12.3.2), the initial standard
3032 // conversion sequence converts the source type to the
3033 // implicit object parameter of the conversion function.
3034 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003035 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003036 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003037 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003038 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003039
John McCall5c32be02010-08-24 20:38:10 +00003040 // C++ [over.ics.user]p2:
3041 // The second standard conversion sequence converts the
3042 // result of the user-defined conversion to the target type
3043 // for the sequence. Since an implicit conversion sequence
3044 // is an initialization, the special rules for
3045 // initialization by user-defined conversion apply when
3046 // selecting the best user-defined conversion for a
3047 // user-defined conversion sequence (see 13.3.3 and
3048 // 13.3.3.1).
3049 User.After = Best->FinalConversion;
3050 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003051 }
David Blaikie8a40f702012-01-17 06:56:22 +00003052 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003053
John McCall5c32be02010-08-24 20:38:10 +00003054 case OR_No_Viable_Function:
3055 return OR_No_Viable_Function;
3056 case OR_Deleted:
3057 // No conversion here! We're done.
3058 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059
John McCall5c32be02010-08-24 20:38:10 +00003060 case OR_Ambiguous:
3061 return OR_Ambiguous;
3062 }
3063
David Blaikie8a40f702012-01-17 06:56:22 +00003064 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003065}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003067bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003068Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003069 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003070 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003071 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003072 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003073 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003074 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003075 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003076 diag::err_typecheck_ambiguous_condition)
3077 << From->getType() << ToType << From->getSourceRange();
3078 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003079 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003080 diag::err_typecheck_nonviable_condition)
3081 << From->getType() << ToType << From->getSourceRange();
3082 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003083 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003084 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003085 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003086}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003087
Douglas Gregor2837aa22012-02-22 17:32:19 +00003088/// \brief Compare the user-defined conversion functions or constructors
3089/// of two user-defined conversion sequences to determine whether any ordering
3090/// is possible.
3091static ImplicitConversionSequence::CompareKind
3092compareConversionFunctions(Sema &S,
3093 FunctionDecl *Function1,
3094 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003095 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003096 return ImplicitConversionSequence::Indistinguishable;
3097
3098 // Objective-C++:
3099 // If both conversion functions are implicitly-declared conversions from
3100 // a lambda closure type to a function pointer and a block pointer,
3101 // respectively, always prefer the conversion to a function pointer,
3102 // because the function pointer is more lightweight and is more likely
3103 // to keep code working.
3104 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3105 if (!Conv1)
3106 return ImplicitConversionSequence::Indistinguishable;
3107
3108 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3109 if (!Conv2)
3110 return ImplicitConversionSequence::Indistinguishable;
3111
3112 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3113 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3114 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3115 if (Block1 != Block2)
3116 return Block1? ImplicitConversionSequence::Worse
3117 : ImplicitConversionSequence::Better;
3118 }
3119
3120 return ImplicitConversionSequence::Indistinguishable;
3121}
3122
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003123/// CompareImplicitConversionSequences - Compare two implicit
3124/// conversion sequences to determine whether one is better than the
3125/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003126static ImplicitConversionSequence::CompareKind
3127CompareImplicitConversionSequences(Sema &S,
3128 const ImplicitConversionSequence& ICS1,
3129 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003130{
3131 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3132 // conversion sequences (as defined in 13.3.3.1)
3133 // -- a standard conversion sequence (13.3.3.1.1) is a better
3134 // conversion sequence than a user-defined conversion sequence or
3135 // an ellipsis conversion sequence, and
3136 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3137 // conversion sequence than an ellipsis conversion sequence
3138 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003139 //
John McCall0d1da222010-01-12 00:44:57 +00003140 // C++0x [over.best.ics]p10:
3141 // For the purpose of ranking implicit conversion sequences as
3142 // described in 13.3.3.2, the ambiguous conversion sequence is
3143 // treated as a user-defined sequence that is indistinguishable
3144 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003145 if (ICS1.getKindRank() < ICS2.getKindRank())
3146 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003147 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003148 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003149
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003150 // The following checks require both conversion sequences to be of
3151 // the same kind.
3152 if (ICS1.getKind() != ICS2.getKind())
3153 return ImplicitConversionSequence::Indistinguishable;
3154
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003155 ImplicitConversionSequence::CompareKind Result =
3156 ImplicitConversionSequence::Indistinguishable;
3157
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003158 // Two implicit conversion sequences of the same form are
3159 // indistinguishable conversion sequences unless one of the
3160 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003161 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003162 Result = CompareStandardConversionSequences(S,
3163 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003164 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003165 // User-defined conversion sequence U1 is a better conversion
3166 // sequence than another user-defined conversion sequence U2 if
3167 // they contain the same user-defined conversion function or
3168 // constructor and if the second standard conversion sequence of
3169 // U1 is better than the second standard conversion sequence of
3170 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003171 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003172 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003173 Result = CompareStandardConversionSequences(S,
3174 ICS1.UserDefined.After,
3175 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003176 else
3177 Result = compareConversionFunctions(S,
3178 ICS1.UserDefined.ConversionFunction,
3179 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003180 }
3181
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003182 // List-initialization sequence L1 is a better conversion sequence than
3183 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3184 // for some X and L2 does not.
3185 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003186 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003187 ICS1.isListInitializationSequence() &&
3188 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003189 if (ICS1.isStdInitializerListElement() &&
3190 !ICS2.isStdInitializerListElement())
3191 return ImplicitConversionSequence::Better;
3192 if (!ICS1.isStdInitializerListElement() &&
3193 ICS2.isStdInitializerListElement())
3194 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003195 }
3196
3197 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003198}
3199
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003200static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3201 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3202 Qualifiers Quals;
3203 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003207 return Context.hasSameUnqualifiedType(T1, T2);
3208}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003210// Per 13.3.3.2p3, compare the given standard conversion sequences to
3211// determine if one is a proper subset of the other.
3212static ImplicitConversionSequence::CompareKind
3213compareStandardConversionSubsets(ASTContext &Context,
3214 const StandardConversionSequence& SCS1,
3215 const StandardConversionSequence& SCS2) {
3216 ImplicitConversionSequence::CompareKind Result
3217 = ImplicitConversionSequence::Indistinguishable;
3218
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003220 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003221 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3222 return ImplicitConversionSequence::Better;
3223 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3224 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003226 if (SCS1.Second != SCS2.Second) {
3227 if (SCS1.Second == ICK_Identity)
3228 Result = ImplicitConversionSequence::Better;
3229 else if (SCS2.Second == ICK_Identity)
3230 Result = ImplicitConversionSequence::Worse;
3231 else
3232 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003233 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003234 return ImplicitConversionSequence::Indistinguishable;
3235
3236 if (SCS1.Third == SCS2.Third) {
3237 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3238 : ImplicitConversionSequence::Indistinguishable;
3239 }
3240
3241 if (SCS1.Third == ICK_Identity)
3242 return Result == ImplicitConversionSequence::Worse
3243 ? ImplicitConversionSequence::Indistinguishable
3244 : ImplicitConversionSequence::Better;
3245
3246 if (SCS2.Third == ICK_Identity)
3247 return Result == ImplicitConversionSequence::Better
3248 ? ImplicitConversionSequence::Indistinguishable
3249 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003251 return ImplicitConversionSequence::Indistinguishable;
3252}
3253
Douglas Gregore696ebb2011-01-26 14:52:12 +00003254/// \brief Determine whether one of the given reference bindings is better
3255/// than the other based on what kind of bindings they are.
3256static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3257 const StandardConversionSequence &SCS2) {
3258 // C++0x [over.ics.rank]p3b4:
3259 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3260 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003261 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003262 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003264 // reference*.
3265 //
3266 // FIXME: Rvalue references. We're going rogue with the above edits,
3267 // because the semantics in the current C++0x working paper (N3225 at the
3268 // time of this writing) break the standard definition of std::forward
3269 // and std::reference_wrapper when dealing with references to functions.
3270 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003271 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3272 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3273 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274
Douglas Gregore696ebb2011-01-26 14:52:12 +00003275 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3276 SCS2.IsLvalueReference) ||
3277 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3278 !SCS2.IsLvalueReference);
3279}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003281/// CompareStandardConversionSequences - Compare two standard
3282/// conversion sequences to determine whether one is better than the
3283/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003284static ImplicitConversionSequence::CompareKind
3285CompareStandardConversionSequences(Sema &S,
3286 const StandardConversionSequence& SCS1,
3287 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003288{
3289 // Standard conversion sequence S1 is a better conversion sequence
3290 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3291
3292 // -- S1 is a proper subsequence of S2 (comparing the conversion
3293 // sequences in the canonical form defined by 13.3.3.1.1,
3294 // excluding any Lvalue Transformation; the identity conversion
3295 // sequence is considered to be a subsequence of any
3296 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003297 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003298 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003299 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003300
3301 // -- the rank of S1 is better than the rank of S2 (by the rules
3302 // defined below), or, if not that,
3303 ImplicitConversionRank Rank1 = SCS1.getRank();
3304 ImplicitConversionRank Rank2 = SCS2.getRank();
3305 if (Rank1 < Rank2)
3306 return ImplicitConversionSequence::Better;
3307 else if (Rank2 < Rank1)
3308 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003309
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003310 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3311 // are indistinguishable unless one of the following rules
3312 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003313
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003314 // A conversion that is not a conversion of a pointer, or
3315 // pointer to member, to bool is better than another conversion
3316 // that is such a conversion.
3317 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3318 return SCS2.isPointerConversionToBool()
3319 ? ImplicitConversionSequence::Better
3320 : ImplicitConversionSequence::Worse;
3321
Douglas Gregor5c407d92008-10-23 00:40:37 +00003322 // C++ [over.ics.rank]p4b2:
3323 //
3324 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003325 // conversion of B* to A* is better than conversion of B* to
3326 // void*, and conversion of A* to void* is better than conversion
3327 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003328 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003329 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003330 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003331 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003332 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3333 // Exactly one of the conversion sequences is a conversion to
3334 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003335 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3336 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003337 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3338 // Neither conversion sequence converts to a void pointer; compare
3339 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003340 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003341 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003342 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003343 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3344 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003345 // Both conversion sequences are conversions to void
3346 // pointers. Compare the source types to determine if there's an
3347 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003348 QualType FromType1 = SCS1.getFromType();
3349 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003350
3351 // Adjust the types we're converting from via the array-to-pointer
3352 // conversion, if we need to.
3353 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003354 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003355 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003356 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003357
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003358 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3359 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003360
John McCall5c32be02010-08-24 20:38:10 +00003361 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003362 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003363 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003364 return ImplicitConversionSequence::Worse;
3365
3366 // Objective-C++: If one interface is more specific than the
3367 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003368 const ObjCObjectPointerType* FromObjCPtr1
3369 = FromType1->getAs<ObjCObjectPointerType>();
3370 const ObjCObjectPointerType* FromObjCPtr2
3371 = FromType2->getAs<ObjCObjectPointerType>();
3372 if (FromObjCPtr1 && FromObjCPtr2) {
3373 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3374 FromObjCPtr2);
3375 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3376 FromObjCPtr1);
3377 if (AssignLeft != AssignRight) {
3378 return AssignLeft? ImplicitConversionSequence::Better
3379 : ImplicitConversionSequence::Worse;
3380 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003381 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003382 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003383
3384 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3385 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003386 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003387 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003388 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003389
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003390 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003391 // Check for a better reference binding based on the kind of bindings.
3392 if (isBetterReferenceBindingKind(SCS1, SCS2))
3393 return ImplicitConversionSequence::Better;
3394 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3395 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396
Sebastian Redlb28b4072009-03-22 23:49:27 +00003397 // C++ [over.ics.rank]p3b4:
3398 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3399 // which the references refer are the same type except for
3400 // top-level cv-qualifiers, and the type to which the reference
3401 // initialized by S2 refers is more cv-qualified than the type
3402 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003403 QualType T1 = SCS1.getToType(2);
3404 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003405 T1 = S.Context.getCanonicalType(T1);
3406 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003407 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003408 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3409 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003410 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003411 // Objective-C++ ARC: If the references refer to objects with different
3412 // lifetimes, prefer bindings that don't change lifetime.
3413 if (SCS1.ObjCLifetimeConversionBinding !=
3414 SCS2.ObjCLifetimeConversionBinding) {
3415 return SCS1.ObjCLifetimeConversionBinding
3416 ? ImplicitConversionSequence::Worse
3417 : ImplicitConversionSequence::Better;
3418 }
3419
Chandler Carruth8e543b32010-12-12 08:17:55 +00003420 // If the type is an array type, promote the element qualifiers to the
3421 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003422 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003423 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003424 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003425 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003426 if (T2.isMoreQualifiedThan(T1))
3427 return ImplicitConversionSequence::Better;
3428 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003429 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003430 }
3431 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003432
Francois Pichet08d2fa02011-09-18 21:37:37 +00003433 // In Microsoft mode, prefer an integral conversion to a
3434 // floating-to-integral conversion if the integral conversion
3435 // is between types of the same size.
3436 // For example:
3437 // void f(float);
3438 // void f(int);
3439 // int main {
3440 // long a;
3441 // f(a);
3442 // }
3443 // Here, MSVC will call f(int) instead of generating a compile error
3444 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003445 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003446 SCS1.Second == ICK_Integral_Conversion &&
3447 SCS2.Second == ICK_Floating_Integral &&
3448 S.Context.getTypeSize(SCS1.getFromType()) ==
3449 S.Context.getTypeSize(SCS1.getToType(2)))
3450 return ImplicitConversionSequence::Better;
3451
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003452 return ImplicitConversionSequence::Indistinguishable;
3453}
3454
3455/// CompareQualificationConversions - Compares two standard conversion
3456/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003457/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3458ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003459CompareQualificationConversions(Sema &S,
3460 const StandardConversionSequence& SCS1,
3461 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003462 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003463 // -- S1 and S2 differ only in their qualification conversion and
3464 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3465 // cv-qualification signature of type T1 is a proper subset of
3466 // the cv-qualification signature of type T2, and S1 is not the
3467 // deprecated string literal array-to-pointer conversion (4.2).
3468 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3469 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3470 return ImplicitConversionSequence::Indistinguishable;
3471
3472 // FIXME: the example in the standard doesn't use a qualification
3473 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003474 QualType T1 = SCS1.getToType(2);
3475 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003476 T1 = S.Context.getCanonicalType(T1);
3477 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003478 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003479 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3480 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003481
3482 // If the types are the same, we won't learn anything by unwrapped
3483 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003484 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003485 return ImplicitConversionSequence::Indistinguishable;
3486
Chandler Carruth607f38e2009-12-29 07:16:59 +00003487 // If the type is an array type, promote the element qualifiers to the type
3488 // for comparison.
3489 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003490 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003491 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003492 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003493
Mike Stump11289f42009-09-09 15:08:12 +00003494 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003495 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003496
3497 // Objective-C++ ARC:
3498 // Prefer qualification conversions not involving a change in lifetime
3499 // to qualification conversions that do not change lifetime.
3500 if (SCS1.QualificationIncludesObjCLifetime !=
3501 SCS2.QualificationIncludesObjCLifetime) {
3502 Result = SCS1.QualificationIncludesObjCLifetime
3503 ? ImplicitConversionSequence::Worse
3504 : ImplicitConversionSequence::Better;
3505 }
3506
John McCall5c32be02010-08-24 20:38:10 +00003507 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003508 // Within each iteration of the loop, we check the qualifiers to
3509 // determine if this still looks like a qualification
3510 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003511 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003512 // until there are no more pointers or pointers-to-members left
3513 // to unwrap. This essentially mimics what
3514 // IsQualificationConversion does, but here we're checking for a
3515 // strict subset of qualifiers.
3516 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3517 // The qualifiers are the same, so this doesn't tell us anything
3518 // about how the sequences rank.
3519 ;
3520 else if (T2.isMoreQualifiedThan(T1)) {
3521 // T1 has fewer qualifiers, so it could be the better sequence.
3522 if (Result == ImplicitConversionSequence::Worse)
3523 // Neither has qualifiers that are a subset of the other's
3524 // qualifiers.
3525 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003526
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003527 Result = ImplicitConversionSequence::Better;
3528 } else if (T1.isMoreQualifiedThan(T2)) {
3529 // T2 has fewer qualifiers, so it could be the better sequence.
3530 if (Result == ImplicitConversionSequence::Better)
3531 // Neither has qualifiers that are a subset of the other's
3532 // qualifiers.
3533 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003535 Result = ImplicitConversionSequence::Worse;
3536 } else {
3537 // Qualifiers are disjoint.
3538 return ImplicitConversionSequence::Indistinguishable;
3539 }
3540
3541 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003542 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003543 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003544 }
3545
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003546 // Check that the winning standard conversion sequence isn't using
3547 // the deprecated string literal array to pointer conversion.
3548 switch (Result) {
3549 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003550 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003551 Result = ImplicitConversionSequence::Indistinguishable;
3552 break;
3553
3554 case ImplicitConversionSequence::Indistinguishable:
3555 break;
3556
3557 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003558 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559 Result = ImplicitConversionSequence::Indistinguishable;
3560 break;
3561 }
3562
3563 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003564}
3565
Douglas Gregor5c407d92008-10-23 00:40:37 +00003566/// CompareDerivedToBaseConversions - Compares two standard conversion
3567/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003568/// various kinds of derived-to-base conversions (C++
3569/// [over.ics.rank]p4b3). As part of these checks, we also look at
3570/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003571ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003572CompareDerivedToBaseConversions(Sema &S,
3573 const StandardConversionSequence& SCS1,
3574 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003575 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003576 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003577 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003578 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003579
3580 // Adjust the types we're converting from via the array-to-pointer
3581 // conversion, if we need to.
3582 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003583 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003584 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003585 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003586
3587 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003588 FromType1 = S.Context.getCanonicalType(FromType1);
3589 ToType1 = S.Context.getCanonicalType(ToType1);
3590 FromType2 = S.Context.getCanonicalType(FromType2);
3591 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003592
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003593 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003594 //
3595 // If class B is derived directly or indirectly from class A and
3596 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003597 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003598 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003599 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003600 SCS2.Second == ICK_Pointer_Conversion &&
3601 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3602 FromType1->isPointerType() && FromType2->isPointerType() &&
3603 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003604 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003605 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003606 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003607 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003608 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003609 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003610 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003611 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003612
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003613 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003614 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003615 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003616 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003617 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003618 return ImplicitConversionSequence::Worse;
3619 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003620
3621 // -- conversion of B* to A* is better than conversion of C* to A*,
3622 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003623 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003624 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003625 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003626 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003627 }
3628 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3629 SCS2.Second == ICK_Pointer_Conversion) {
3630 const ObjCObjectPointerType *FromPtr1
3631 = FromType1->getAs<ObjCObjectPointerType>();
3632 const ObjCObjectPointerType *FromPtr2
3633 = FromType2->getAs<ObjCObjectPointerType>();
3634 const ObjCObjectPointerType *ToPtr1
3635 = ToType1->getAs<ObjCObjectPointerType>();
3636 const ObjCObjectPointerType *ToPtr2
3637 = ToType2->getAs<ObjCObjectPointerType>();
3638
3639 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3640 // Apply the same conversion ranking rules for Objective-C pointer types
3641 // that we do for C++ pointers to class types. However, we employ the
3642 // Objective-C pseudo-subtyping relationship used for assignment of
3643 // Objective-C pointer types.
3644 bool FromAssignLeft
3645 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3646 bool FromAssignRight
3647 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3648 bool ToAssignLeft
3649 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3650 bool ToAssignRight
3651 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3652
3653 // A conversion to an a non-id object pointer type or qualified 'id'
3654 // type is better than a conversion to 'id'.
3655 if (ToPtr1->isObjCIdType() &&
3656 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3657 return ImplicitConversionSequence::Worse;
3658 if (ToPtr2->isObjCIdType() &&
3659 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3660 return ImplicitConversionSequence::Better;
3661
3662 // A conversion to a non-id object pointer type is better than a
3663 // conversion to a qualified 'id' type
3664 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3665 return ImplicitConversionSequence::Worse;
3666 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3667 return ImplicitConversionSequence::Better;
3668
3669 // A conversion to an a non-Class object pointer type or qualified 'Class'
3670 // type is better than a conversion to 'Class'.
3671 if (ToPtr1->isObjCClassType() &&
3672 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3673 return ImplicitConversionSequence::Worse;
3674 if (ToPtr2->isObjCClassType() &&
3675 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3676 return ImplicitConversionSequence::Better;
3677
3678 // A conversion to a non-Class object pointer type is better than a
3679 // conversion to a qualified 'Class' type.
3680 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3681 return ImplicitConversionSequence::Worse;
3682 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3683 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003684
Douglas Gregor058d3de2011-01-31 18:51:41 +00003685 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3686 if (S.Context.hasSameType(FromType1, FromType2) &&
3687 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3688 (ToAssignLeft != ToAssignRight))
3689 return ToAssignLeft? ImplicitConversionSequence::Worse
3690 : ImplicitConversionSequence::Better;
3691
3692 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3693 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3694 (FromAssignLeft != FromAssignRight))
3695 return FromAssignLeft? ImplicitConversionSequence::Better
3696 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003697 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003698 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003699
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003700 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003701 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3702 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3703 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003705 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003707 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003709 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003710 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003711 ToType2->getAs<MemberPointerType>();
3712 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3713 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3714 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3715 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3716 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3717 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3718 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3719 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003720 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003721 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003722 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003723 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003724 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003725 return ImplicitConversionSequence::Better;
3726 }
3727 // conversion of B::* to C::* is better than conversion of A::* to C::*
3728 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003729 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003730 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003731 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003732 return ImplicitConversionSequence::Worse;
3733 }
3734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
Douglas Gregor5ab11652010-04-17 22:01:05 +00003736 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003737 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003738 // -- binding of an expression of type C to a reference of type
3739 // B& is better than binding an expression of type C to a
3740 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003741 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3742 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3743 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003744 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003745 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003746 return ImplicitConversionSequence::Worse;
3747 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003748
Douglas Gregor2fe98832008-11-03 19:09:14 +00003749 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003750 // -- binding of an expression of type B to a reference of type
3751 // A& is better than binding an expression of type C to a
3752 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003753 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3754 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3755 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003756 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003757 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003758 return ImplicitConversionSequence::Worse;
3759 }
3760 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003761
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762 return ImplicitConversionSequence::Indistinguishable;
3763}
3764
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003765/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3766/// determine whether they are reference-related,
3767/// reference-compatible, reference-compatible with added
3768/// qualification, or incompatible, for use in C++ initialization by
3769/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3770/// type, and the first type (T1) is the pointee type of the reference
3771/// type being initialized.
3772Sema::ReferenceCompareResult
3773Sema::CompareReferenceRelationship(SourceLocation Loc,
3774 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003775 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003776 bool &ObjCConversion,
3777 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003778 assert(!OrigT1->isReferenceType() &&
3779 "T1 must be the pointee type of the reference type");
3780 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3781
3782 QualType T1 = Context.getCanonicalType(OrigT1);
3783 QualType T2 = Context.getCanonicalType(OrigT2);
3784 Qualifiers T1Quals, T2Quals;
3785 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3786 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3787
3788 // C++ [dcl.init.ref]p4:
3789 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3790 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3791 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003792 DerivedToBase = false;
3793 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003794 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003795 if (UnqualT1 == UnqualT2) {
3796 // Nothing to do.
3797 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003798 IsDerivedFrom(UnqualT2, UnqualT1))
3799 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003800 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3801 UnqualT2->isObjCObjectOrInterfaceType() &&
3802 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3803 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003804 else
3805 return Ref_Incompatible;
3806
3807 // At this point, we know that T1 and T2 are reference-related (at
3808 // least).
3809
3810 // If the type is an array type, promote the element qualifiers to the type
3811 // for comparison.
3812 if (isa<ArrayType>(T1) && T1Quals)
3813 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3814 if (isa<ArrayType>(T2) && T2Quals)
3815 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3816
3817 // C++ [dcl.init.ref]p4:
3818 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3819 // reference-related to T2 and cv1 is the same cv-qualification
3820 // as, or greater cv-qualification than, cv2. For purposes of
3821 // overload resolution, cases for which cv1 is greater
3822 // cv-qualification than cv2 are identified as
3823 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003824 //
3825 // Note that we also require equivalence of Objective-C GC and address-space
3826 // qualifiers when performing these computations, so that e.g., an int in
3827 // address space 1 is not reference-compatible with an int in address
3828 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003829 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3830 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3831 T1Quals.removeObjCLifetime();
3832 T2Quals.removeObjCLifetime();
3833 ObjCLifetimeConversion = true;
3834 }
3835
Douglas Gregord517d552011-04-28 17:56:11 +00003836 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003837 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003838 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003839 return Ref_Compatible_With_Added_Qualification;
3840 else
3841 return Ref_Related;
3842}
3843
Douglas Gregor836a7e82010-08-11 02:15:33 +00003844/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003845/// with DeclType. Return true if something definite is found.
3846static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003847FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3848 QualType DeclType, SourceLocation DeclLoc,
3849 Expr *Init, QualType T2, bool AllowRvalues,
3850 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003851 assert(T2->isRecordType() && "Can only find conversions of record types.");
3852 CXXRecordDecl *T2RecordDecl
3853 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3854
3855 OverloadCandidateSet CandidateSet(DeclLoc);
3856 const UnresolvedSetImpl *Conversions
3857 = T2RecordDecl->getVisibleConversionFunctions();
3858 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3859 E = Conversions->end(); I != E; ++I) {
3860 NamedDecl *D = *I;
3861 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3862 if (isa<UsingShadowDecl>(D))
3863 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3864
3865 FunctionTemplateDecl *ConvTemplate
3866 = dyn_cast<FunctionTemplateDecl>(D);
3867 CXXConversionDecl *Conv;
3868 if (ConvTemplate)
3869 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3870 else
3871 Conv = cast<CXXConversionDecl>(D);
3872
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003874 // explicit conversions, skip it.
3875 if (!AllowExplicit && Conv->isExplicit())
3876 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877
Douglas Gregor836a7e82010-08-11 02:15:33 +00003878 if (AllowRvalues) {
3879 bool DerivedToBase = false;
3880 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003881 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003882
3883 // If we are initializing an rvalue reference, don't permit conversion
3884 // functions that return lvalues.
3885 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3886 const ReferenceType *RefType
3887 = Conv->getConversionType()->getAs<LValueReferenceType>();
3888 if (RefType && !RefType->getPointeeType()->isFunctionType())
3889 continue;
3890 }
3891
Douglas Gregor836a7e82010-08-11 02:15:33 +00003892 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003893 S.CompareReferenceRelationship(
3894 DeclLoc,
3895 Conv->getConversionType().getNonReferenceType()
3896 .getUnqualifiedType(),
3897 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003898 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003899 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003900 continue;
3901 } else {
3902 // If the conversion function doesn't return a reference type,
3903 // it can't be considered for this conversion. An rvalue reference
3904 // is only acceptable if its referencee is a function type.
3905
3906 const ReferenceType *RefType =
3907 Conv->getConversionType()->getAs<ReferenceType>();
3908 if (!RefType ||
3909 (!RefType->isLValueReferenceType() &&
3910 !RefType->getPointeeType()->isFunctionType()))
3911 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003912 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913
Douglas Gregor836a7e82010-08-11 02:15:33 +00003914 if (ConvTemplate)
3915 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003916 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003917 else
3918 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003919 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003920 }
3921
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003922 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3923
Sebastian Redld92badf2010-06-30 18:13:39 +00003924 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003925 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003926 case OR_Success:
3927 // C++ [over.ics.ref]p1:
3928 //
3929 // [...] If the parameter binds directly to the result of
3930 // applying a conversion function to the argument
3931 // expression, the implicit conversion sequence is a
3932 // user-defined conversion sequence (13.3.3.1.2), with the
3933 // second standard conversion sequence either an identity
3934 // conversion or, if the conversion function returns an
3935 // entity of a type that is a derived class of the parameter
3936 // type, a derived-to-base Conversion.
3937 if (!Best->FinalConversion.DirectBinding)
3938 return false;
3939
Chandler Carruth30141632011-02-25 19:41:05 +00003940 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003941 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003942 ICS.setUserDefined();
3943 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3944 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003945 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003946 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003947 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003948 ICS.UserDefined.EllipsisConversion = false;
3949 assert(ICS.UserDefined.After.ReferenceBinding &&
3950 ICS.UserDefined.After.DirectBinding &&
3951 "Expected a direct reference binding!");
3952 return true;
3953
3954 case OR_Ambiguous:
3955 ICS.setAmbiguous();
3956 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3957 Cand != CandidateSet.end(); ++Cand)
3958 if (Cand->Viable)
3959 ICS.Ambiguous.addConversion(Cand->Function);
3960 return true;
3961
3962 case OR_No_Viable_Function:
3963 case OR_Deleted:
3964 // There was no suitable conversion, or we found a deleted
3965 // conversion; continue with other checks.
3966 return false;
3967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968
David Blaikie8a40f702012-01-17 06:56:22 +00003969 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00003970}
3971
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003972/// \brief Compute an implicit conversion sequence for reference
3973/// initialization.
3974static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003975TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003976 SourceLocation DeclLoc,
3977 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003978 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003979 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3980
3981 // Most paths end in a failed conversion.
3982 ImplicitConversionSequence ICS;
3983 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3984
3985 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3986 QualType T2 = Init->getType();
3987
3988 // If the initializer is the address of an overloaded function, try
3989 // to resolve the overloaded function. If all goes well, T2 is the
3990 // type of the resulting function.
3991 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3992 DeclAccessPair Found;
3993 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3994 false, Found))
3995 T2 = Fn->getType();
3996 }
3997
3998 // Compute some basic properties of the types and the initializer.
3999 bool isRValRef = DeclType->isRValueReferenceType();
4000 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004001 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004002 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004003 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004004 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004005 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004006 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004007
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004008
Sebastian Redld92badf2010-06-30 18:13:39 +00004009 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004010 // A reference to type "cv1 T1" is initialized by an expression
4011 // of type "cv2 T2" as follows:
4012
Sebastian Redld92badf2010-06-30 18:13:39 +00004013 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004014 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004015 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4016 // reference-compatible with "cv2 T2," or
4017 //
4018 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4019 if (InitCategory.isLValue() &&
4020 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004021 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004022 // When a parameter of reference type binds directly (8.5.3)
4023 // to an argument expression, the implicit conversion sequence
4024 // is the identity conversion, unless the argument expression
4025 // has a type that is a derived class of the parameter type,
4026 // in which case the implicit conversion sequence is a
4027 // derived-to-base Conversion (13.3.3.1).
4028 ICS.setStandard();
4029 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004030 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4031 : ObjCConversion? ICK_Compatible_Conversion
4032 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004033 ICS.Standard.Third = ICK_Identity;
4034 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4035 ICS.Standard.setToType(0, T2);
4036 ICS.Standard.setToType(1, T1);
4037 ICS.Standard.setToType(2, T1);
4038 ICS.Standard.ReferenceBinding = true;
4039 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004040 ICS.Standard.IsLvalueReference = !isRValRef;
4041 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4042 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004043 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004044 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004045 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004046
Sebastian Redld92badf2010-06-30 18:13:39 +00004047 // Nothing more to do: the inaccessibility/ambiguity check for
4048 // derived-to-base conversions is suppressed when we're
4049 // computing the implicit conversion sequence (C++
4050 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004051 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004052 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004053
Sebastian Redld92badf2010-06-30 18:13:39 +00004054 // -- has a class type (i.e., T2 is a class type), where T1 is
4055 // not reference-related to T2, and can be implicitly
4056 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4057 // is reference-compatible with "cv3 T3" 92) (this
4058 // conversion is selected by enumerating the applicable
4059 // conversion functions (13.3.1.6) and choosing the best
4060 // one through overload resolution (13.3)),
4061 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004063 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004064 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4065 Init, T2, /*AllowRvalues=*/false,
4066 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004067 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004068 }
4069 }
4070
Sebastian Redld92badf2010-06-30 18:13:39 +00004071 // -- Otherwise, the reference shall be an lvalue reference to a
4072 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004073 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004075 // We actually handle one oddity of C++ [over.ics.ref] at this
4076 // point, which is that, due to p2 (which short-circuits reference
4077 // binding by only attempting a simple conversion for non-direct
4078 // bindings) and p3's strange wording, we allow a const volatile
4079 // reference to bind to an rvalue. Hence the check for the presence
4080 // of "const" rather than checking for "const" being the only
4081 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004082 // This is also the point where rvalue references and lvalue inits no longer
4083 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00004084 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004085 return ICS;
4086
Douglas Gregorf143cd52011-01-24 16:14:37 +00004087 // -- If the initializer expression
4088 //
4089 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004090 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004091 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4092 (InitCategory.isXValue() ||
4093 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4094 (InitCategory.isLValue() && T2->isFunctionType()))) {
4095 ICS.setStandard();
4096 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004097 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004098 : ObjCConversion? ICK_Compatible_Conversion
4099 : ICK_Identity;
4100 ICS.Standard.Third = ICK_Identity;
4101 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4102 ICS.Standard.setToType(0, T2);
4103 ICS.Standard.setToType(1, T1);
4104 ICS.Standard.setToType(2, T1);
4105 ICS.Standard.ReferenceBinding = true;
4106 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4107 // binding unless we're binding to a class prvalue.
4108 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4109 // allow the use of rvalue references in C++98/03 for the benefit of
4110 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004112 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004113 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004114 ICS.Standard.IsLvalueReference = !isRValRef;
4115 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004117 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004118 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004119 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004120 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
Douglas Gregorf143cd52011-01-24 16:14:37 +00004123 // -- has a class type (i.e., T2 is a class type), where T1 is not
4124 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004125 // an xvalue, class prvalue, or function lvalue of type
4126 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004127 // "cv3 T3",
4128 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004129 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004130 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004132 // class subobject).
4133 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004135 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4136 Init, T2, /*AllowRvalues=*/true,
4137 AllowExplicit)) {
4138 // In the second case, if the reference is an rvalue reference
4139 // and the second standard conversion sequence of the
4140 // user-defined conversion sequence includes an lvalue-to-rvalue
4141 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004143 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4144 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4145
Douglas Gregor95273c32011-01-21 16:36:05 +00004146 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004149 // -- Otherwise, a temporary of type "cv1 T1" is created and
4150 // initialized from the initializer expression using the
4151 // rules for a non-reference copy initialization (8.5). The
4152 // reference is then bound to the temporary. If T1 is
4153 // reference-related to T2, cv1 must be the same
4154 // cv-qualification as, or greater cv-qualification than,
4155 // cv2; otherwise, the program is ill-formed.
4156 if (RefRelationship == Sema::Ref_Related) {
4157 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4158 // we would be reference-compatible or reference-compatible with
4159 // added qualification. But that wasn't the case, so the reference
4160 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004161 //
4162 // Note that we only want to check address spaces and cvr-qualifiers here.
4163 // ObjC GC and lifetime qualifiers aren't important.
4164 Qualifiers T1Quals = T1.getQualifiers();
4165 Qualifiers T2Quals = T2.getQualifiers();
4166 T1Quals.removeObjCGCAttr();
4167 T1Quals.removeObjCLifetime();
4168 T2Quals.removeObjCGCAttr();
4169 T2Quals.removeObjCLifetime();
4170 if (!T1Quals.compatiblyIncludes(T2Quals))
4171 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004172 }
4173
4174 // If at least one of the types is a class type, the types are not
4175 // related, and we aren't allowed any user conversions, the
4176 // reference binding fails. This case is important for breaking
4177 // recursion, since TryImplicitConversion below will attempt to
4178 // create a temporary through the use of a copy constructor.
4179 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4180 (T1->isRecordType() || T2->isRecordType()))
4181 return ICS;
4182
Douglas Gregorcba72b12011-01-21 05:18:22 +00004183 // If T1 is reference-related to T2 and the reference is an rvalue
4184 // reference, the initializer expression shall not be an lvalue.
4185 if (RefRelationship >= Sema::Ref_Related &&
4186 isRValRef && Init->Classify(S.Context).isLValue())
4187 return ICS;
4188
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004189 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004190 // When a parameter of reference type is not bound directly to
4191 // an argument expression, the conversion sequence is the one
4192 // required to convert the argument expression to the
4193 // underlying type of the reference according to
4194 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4195 // to copy-initializing a temporary of the underlying type with
4196 // the argument expression. Any difference in top-level
4197 // cv-qualification is subsumed by the initialization itself
4198 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004199 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4200 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004201 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004202 /*CStyle=*/false,
4203 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004204
4205 // Of course, that's still a reference binding.
4206 if (ICS.isStandard()) {
4207 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004208 ICS.Standard.IsLvalueReference = !isRValRef;
4209 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4210 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004211 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004212 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004213 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004214 // Don't allow rvalue references to bind to lvalues.
4215 if (DeclType->isRValueReferenceType()) {
4216 if (const ReferenceType *RefType
4217 = ICS.UserDefined.ConversionFunction->getResultType()
4218 ->getAs<LValueReferenceType>()) {
4219 if (!RefType->getPointeeType()->isFunctionType()) {
4220 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4221 DeclType);
4222 return ICS;
4223 }
4224 }
4225 }
4226
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004227 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004228 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4229 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4230 ICS.UserDefined.After.BindsToRvalue = true;
4231 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4232 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004233 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004234
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004235 return ICS;
4236}
4237
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004238static ImplicitConversionSequence
4239TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4240 bool SuppressUserConversions,
4241 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004242 bool AllowObjCWritebackConversion,
4243 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004244
4245/// TryListConversion - Try to copy-initialize a value of type ToType from the
4246/// initializer list From.
4247static ImplicitConversionSequence
4248TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4249 bool SuppressUserConversions,
4250 bool InOverloadResolution,
4251 bool AllowObjCWritebackConversion) {
4252 // C++11 [over.ics.list]p1:
4253 // When an argument is an initializer list, it is not an expression and
4254 // special rules apply for converting it to a parameter type.
4255
4256 ImplicitConversionSequence Result;
4257 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004258 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004259
Sebastian Redl09edce02012-01-23 22:09:39 +00004260 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004261 // initialized from init lists.
4262 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4263 return Result;
4264
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004265 // C++11 [over.ics.list]p2:
4266 // If the parameter type is std::initializer_list<X> or "array of X" and
4267 // all the elements can be implicitly converted to X, the implicit
4268 // conversion sequence is the worst conversion necessary to convert an
4269 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004270 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004271 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004272 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004273 X = S.Context.getBaseElementType(ToType);
4274 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004275 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004276 if (!X.isNull()) {
4277 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4278 Expr *Init = From->getInit(i);
4279 ImplicitConversionSequence ICS =
4280 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4281 InOverloadResolution,
4282 AllowObjCWritebackConversion);
4283 // If a single element isn't convertible, fail.
4284 if (ICS.isBad()) {
4285 Result = ICS;
4286 break;
4287 }
4288 // Otherwise, look for the worst conversion.
4289 if (Result.isBad() ||
4290 CompareImplicitConversionSequences(S, ICS, Result) ==
4291 ImplicitConversionSequence::Worse)
4292 Result = ICS;
4293 }
4294 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004295 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004296 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004297 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004298
4299 // C++11 [over.ics.list]p3:
4300 // Otherwise, if the parameter is a non-aggregate class X and overload
4301 // resolution chooses a single best constructor [...] the implicit
4302 // conversion sequence is a user-defined conversion sequence. If multiple
4303 // constructors are viable but none is better than the others, the
4304 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004305 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4306 // This function can deal with initializer lists.
4307 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4308 /*AllowExplicit=*/false,
4309 InOverloadResolution, /*CStyle=*/false,
4310 AllowObjCWritebackConversion);
4311 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004312 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004313 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004314
4315 // C++11 [over.ics.list]p4:
4316 // Otherwise, if the parameter has an aggregate type which can be
4317 // initialized from the initializer list [...] the implicit conversion
4318 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004319 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004320 // Type is an aggregate, argument is an init list. At this point it comes
4321 // down to checking whether the initialization works.
4322 // FIXME: Find out whether this parameter is consumed or not.
4323 InitializedEntity Entity =
4324 InitializedEntity::InitializeParameter(S.Context, ToType,
4325 /*Consumed=*/false);
4326 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4327 Result.setUserDefined();
4328 Result.UserDefined.Before.setAsIdentityConversion();
4329 // Initializer lists don't have a type.
4330 Result.UserDefined.Before.setFromType(QualType());
4331 Result.UserDefined.Before.setAllToTypes(QualType());
4332
4333 Result.UserDefined.After.setAsIdentityConversion();
4334 Result.UserDefined.After.setFromType(ToType);
4335 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004336 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004337 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004338 return Result;
4339 }
4340
4341 // C++11 [over.ics.list]p5:
4342 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004343 if (ToType->isReferenceType()) {
4344 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4345 // mention initializer lists in any way. So we go by what list-
4346 // initialization would do and try to extrapolate from that.
4347
4348 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4349
4350 // If the initializer list has a single element that is reference-related
4351 // to the parameter type, we initialize the reference from that.
4352 if (From->getNumInits() == 1) {
4353 Expr *Init = From->getInit(0);
4354
4355 QualType T2 = Init->getType();
4356
4357 // If the initializer is the address of an overloaded function, try
4358 // to resolve the overloaded function. If all goes well, T2 is the
4359 // type of the resulting function.
4360 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4361 DeclAccessPair Found;
4362 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4363 Init, ToType, false, Found))
4364 T2 = Fn->getType();
4365 }
4366
4367 // Compute some basic properties of the types and the initializer.
4368 bool dummy1 = false;
4369 bool dummy2 = false;
4370 bool dummy3 = false;
4371 Sema::ReferenceCompareResult RefRelationship
4372 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4373 dummy2, dummy3);
4374
4375 if (RefRelationship >= Sema::Ref_Related)
4376 return TryReferenceInit(S, Init, ToType,
4377 /*FIXME:*/From->getLocStart(),
4378 SuppressUserConversions,
4379 /*AllowExplicit=*/false);
4380 }
4381
4382 // Otherwise, we bind the reference to a temporary created from the
4383 // initializer list.
4384 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4385 InOverloadResolution,
4386 AllowObjCWritebackConversion);
4387 if (Result.isFailure())
4388 return Result;
4389 assert(!Result.isEllipsis() &&
4390 "Sub-initialization cannot result in ellipsis conversion.");
4391
4392 // Can we even bind to a temporary?
4393 if (ToType->isRValueReferenceType() ||
4394 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4395 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4396 Result.UserDefined.After;
4397 SCS.ReferenceBinding = true;
4398 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4399 SCS.BindsToRvalue = true;
4400 SCS.BindsToFunctionLvalue = false;
4401 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4402 SCS.ObjCLifetimeConversionBinding = false;
4403 } else
4404 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4405 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004406 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004407 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004408
4409 // C++11 [over.ics.list]p6:
4410 // Otherwise, if the parameter type is not a class:
4411 if (!ToType->isRecordType()) {
4412 // - if the initializer list has one element, the implicit conversion
4413 // sequence is the one required to convert the element to the
4414 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004415 unsigned NumInits = From->getNumInits();
4416 if (NumInits == 1)
4417 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4418 SuppressUserConversions,
4419 InOverloadResolution,
4420 AllowObjCWritebackConversion);
4421 // - if the initializer list has no elements, the implicit conversion
4422 // sequence is the identity conversion.
4423 else if (NumInits == 0) {
4424 Result.setStandard();
4425 Result.Standard.setAsIdentityConversion();
4426 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004427 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004428 return Result;
4429 }
4430
4431 // C++11 [over.ics.list]p7:
4432 // In all cases other than those enumerated above, no conversion is possible
4433 return Result;
4434}
4435
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004436/// TryCopyInitialization - Try to copy-initialize a value of type
4437/// ToType from the expression From. Return the implicit conversion
4438/// sequence required to pass this argument, which may be a bad
4439/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004440/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004441/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004442static ImplicitConversionSequence
4443TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004445 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004446 bool AllowObjCWritebackConversion,
4447 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004448 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4449 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4450 InOverloadResolution,AllowObjCWritebackConversion);
4451
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004452 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004453 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004454 /*FIXME:*/From->getLocStart(),
4455 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004456 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004457
John McCall5c32be02010-08-24 20:38:10 +00004458 return TryImplicitConversion(S, From, ToType,
4459 SuppressUserConversions,
4460 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004461 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004462 /*CStyle=*/false,
4463 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004464}
4465
Anna Zaks1b068122011-07-28 19:46:48 +00004466static bool TryCopyInitialization(const CanQualType FromQTy,
4467 const CanQualType ToQTy,
4468 Sema &S,
4469 SourceLocation Loc,
4470 ExprValueKind FromVK) {
4471 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4472 ImplicitConversionSequence ICS =
4473 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4474
4475 return !ICS.isBad();
4476}
4477
Douglas Gregor436424c2008-11-18 23:14:02 +00004478/// TryObjectArgumentInitialization - Try to initialize the object
4479/// parameter of the given member function (@c Method) from the
4480/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004481static ImplicitConversionSequence
4482TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004483 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004484 CXXMethodDecl *Method,
4485 CXXRecordDecl *ActingContext) {
4486 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004487 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4488 // const volatile object.
4489 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4490 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004491 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004492
4493 // Set up the conversion sequence as a "bad" conversion, to allow us
4494 // to exit early.
4495 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004496
4497 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004498 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004499 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004500 FromType = PT->getPointeeType();
4501
Douglas Gregor02824322011-01-26 19:30:28 +00004502 // When we had a pointer, it's implicitly dereferenced, so we
4503 // better have an lvalue.
4504 assert(FromClassification.isLValue());
4505 }
4506
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004507 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004508
Douglas Gregor02824322011-01-26 19:30:28 +00004509 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004511 // parameter is
4512 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004513 // - "lvalue reference to cv X" for functions declared without a
4514 // ref-qualifier or with the & ref-qualifier
4515 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004516 // ref-qualifier
4517 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004519 // cv-qualification on the member function declaration.
4520 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004522 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004523 // (C++ [over.match.funcs]p5). We perform a simplified version of
4524 // reference binding here, that allows class rvalues to bind to
4525 // non-constant references.
4526
Douglas Gregor02824322011-01-26 19:30:28 +00004527 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004528 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004530 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004531 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004532 ICS.setBad(BadConversionSequence::bad_qualifiers,
4533 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004534 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004535 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004536
4537 // Check that we have either the same type or a derived type. It
4538 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004539 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004540 ImplicitConversionKind SecondKind;
4541 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4542 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004543 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004544 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004545 else {
John McCall65eb8792010-02-25 01:37:24 +00004546 ICS.setBad(BadConversionSequence::unrelated_class,
4547 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004548 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004549 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004550
Douglas Gregor02824322011-01-26 19:30:28 +00004551 // Check the ref-qualifier.
4552 switch (Method->getRefQualifier()) {
4553 case RQ_None:
4554 // Do nothing; we don't care about lvalueness or rvalueness.
4555 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556
Douglas Gregor02824322011-01-26 19:30:28 +00004557 case RQ_LValue:
4558 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4559 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004561 ImplicitParamType);
4562 return ICS;
4563 }
4564 break;
4565
4566 case RQ_RValue:
4567 if (!FromClassification.isRValue()) {
4568 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004569 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004570 ImplicitParamType);
4571 return ICS;
4572 }
4573 break;
4574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
Douglas Gregor436424c2008-11-18 23:14:02 +00004576 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004577 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004578 ICS.Standard.setAsIdentityConversion();
4579 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004580 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004581 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004582 ICS.Standard.ReferenceBinding = true;
4583 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004585 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004586 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4587 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4588 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004589 return ICS;
4590}
4591
4592/// PerformObjectArgumentInitialization - Perform initialization of
4593/// the implicit object parameter for the given Method with the given
4594/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004595ExprResult
4596Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004598 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004599 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004600 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004601 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004602 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004603
Douglas Gregor02824322011-01-26 19:30:28 +00004604 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004605 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004606 FromRecordType = PT->getPointeeType();
4607 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004608 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004609 } else {
4610 FromRecordType = From->getType();
4611 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004612 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004613 }
4614
John McCall6e9f8f62009-12-03 04:06:58 +00004615 // Note that we always use the true parent context when performing
4616 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004617 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004618 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4619 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004620 if (ICS.isBad()) {
4621 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4622 Qualifiers FromQs = FromRecordType.getQualifiers();
4623 Qualifiers ToQs = DestType.getQualifiers();
4624 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4625 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004626 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004627 diag::err_member_function_call_bad_cvr)
4628 << Method->getDeclName() << FromRecordType << (CVR - 1)
4629 << From->getSourceRange();
4630 Diag(Method->getLocation(), diag::note_previous_decl)
4631 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004632 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004633 }
4634 }
4635
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004636 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004637 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004638 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004639 }
Mike Stump11289f42009-09-09 15:08:12 +00004640
John Wiegley01296292011-04-08 18:41:53 +00004641 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4642 ExprResult FromRes =
4643 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4644 if (FromRes.isInvalid())
4645 return ExprError();
4646 From = FromRes.take();
4647 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004648
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004649 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004650 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004651 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004652 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004653}
4654
Douglas Gregor5fb53972009-01-14 15:45:31 +00004655/// TryContextuallyConvertToBool - Attempt to contextually convert the
4656/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004657static ImplicitConversionSequence
4658TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004659 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004660 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004661 // FIXME: Are these flags correct?
4662 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004663 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004664 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004665 /*CStyle=*/false,
4666 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004667}
4668
4669/// PerformContextuallyConvertToBool - Perform a contextual conversion
4670/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004671ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004672 if (checkPlaceholderForOverload(*this, From))
4673 return ExprError();
4674
John McCall5c32be02010-08-24 20:38:10 +00004675 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004676 if (!ICS.isBad())
4677 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004678
Fariborz Jahanian76197412009-11-18 18:26:29 +00004679 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004680 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004681 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004682 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004683 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004684}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004685
Richard Smithf8379a02012-01-18 23:55:52 +00004686/// Check that the specified conversion is permitted in a converted constant
4687/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4688/// is acceptable.
4689static bool CheckConvertedConstantConversions(Sema &S,
4690 StandardConversionSequence &SCS) {
4691 // Since we know that the target type is an integral or unscoped enumeration
4692 // type, most conversion kinds are impossible. All possible First and Third
4693 // conversions are fine.
4694 switch (SCS.Second) {
4695 case ICK_Identity:
4696 case ICK_Integral_Promotion:
4697 case ICK_Integral_Conversion:
4698 return true;
4699
4700 case ICK_Boolean_Conversion:
4701 // Conversion from an integral or unscoped enumeration type to bool is
4702 // classified as ICK_Boolean_Conversion, but it's also an integral
4703 // conversion, so it's permitted in a converted constant expression.
4704 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4705 SCS.getToType(2)->isBooleanType();
4706
4707 case ICK_Floating_Integral:
4708 case ICK_Complex_Real:
4709 return false;
4710
4711 case ICK_Lvalue_To_Rvalue:
4712 case ICK_Array_To_Pointer:
4713 case ICK_Function_To_Pointer:
4714 case ICK_NoReturn_Adjustment:
4715 case ICK_Qualification:
4716 case ICK_Compatible_Conversion:
4717 case ICK_Vector_Conversion:
4718 case ICK_Vector_Splat:
4719 case ICK_Derived_To_Base:
4720 case ICK_Pointer_Conversion:
4721 case ICK_Pointer_Member:
4722 case ICK_Block_Pointer_Conversion:
4723 case ICK_Writeback_Conversion:
4724 case ICK_Floating_Promotion:
4725 case ICK_Complex_Promotion:
4726 case ICK_Complex_Conversion:
4727 case ICK_Floating_Conversion:
4728 case ICK_TransparentUnionConversion:
4729 llvm_unreachable("unexpected second conversion kind");
4730
4731 case ICK_Num_Conversion_Kinds:
4732 break;
4733 }
4734
4735 llvm_unreachable("unknown conversion kind");
4736}
4737
4738/// CheckConvertedConstantExpression - Check that the expression From is a
4739/// converted constant expression of type T, perform the conversion and produce
4740/// the converted expression, per C++11 [expr.const]p3.
4741ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4742 llvm::APSInt &Value,
4743 CCEKind CCE) {
4744 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4745 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4746
4747 if (checkPlaceholderForOverload(*this, From))
4748 return ExprError();
4749
4750 // C++11 [expr.const]p3 with proposed wording fixes:
4751 // A converted constant expression of type T is a core constant expression,
4752 // implicitly converted to a prvalue of type T, where the converted
4753 // expression is a literal constant expression and the implicit conversion
4754 // sequence contains only user-defined conversions, lvalue-to-rvalue
4755 // conversions, integral promotions, and integral conversions other than
4756 // narrowing conversions.
4757 ImplicitConversionSequence ICS =
4758 TryImplicitConversion(From, T,
4759 /*SuppressUserConversions=*/false,
4760 /*AllowExplicit=*/false,
4761 /*InOverloadResolution=*/false,
4762 /*CStyle=*/false,
4763 /*AllowObjcWritebackConversion=*/false);
4764 StandardConversionSequence *SCS = 0;
4765 switch (ICS.getKind()) {
4766 case ImplicitConversionSequence::StandardConversion:
4767 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004768 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004769 diag::err_typecheck_converted_constant_expression_disallowed)
4770 << From->getType() << From->getSourceRange() << T;
4771 SCS = &ICS.Standard;
4772 break;
4773 case ImplicitConversionSequence::UserDefinedConversion:
4774 // We are converting from class type to an integral or enumeration type, so
4775 // the Before sequence must be trivial.
4776 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004777 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004778 diag::err_typecheck_converted_constant_expression_disallowed)
4779 << From->getType() << From->getSourceRange() << T;
4780 SCS = &ICS.UserDefined.After;
4781 break;
4782 case ImplicitConversionSequence::AmbiguousConversion:
4783 case ImplicitConversionSequence::BadConversion:
4784 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004785 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004786 diag::err_typecheck_converted_constant_expression)
4787 << From->getType() << From->getSourceRange() << T;
4788 return ExprError();
4789
4790 case ImplicitConversionSequence::EllipsisConversion:
4791 llvm_unreachable("ellipsis conversion in converted constant expression");
4792 }
4793
4794 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4795 if (Result.isInvalid())
4796 return Result;
4797
4798 // Check for a narrowing implicit conversion.
4799 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004800 QualType PreNarrowingType;
Richard Smith911e1422012-01-30 22:27:01 +00004801 bool Diagnosed = false;
Richard Smith5614ca72012-03-23 23:55:39 +00004802 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4803 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004804 case NK_Variable_Narrowing:
4805 // Implicit conversion to a narrower type, and the value is not a constant
4806 // expression. We'll diagnose this in a moment.
4807 case NK_Not_Narrowing:
4808 break;
4809
4810 case NK_Constant_Narrowing:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004811 Diag(From->getLocStart(), diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004812 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004813 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith911e1422012-01-30 22:27:01 +00004814 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004815 break;
4816
4817 case NK_Type_Narrowing:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004818 Diag(From->getLocStart(), diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004819 << CCE << /*Constant*/0 << From->getType() << T;
Richard Smith911e1422012-01-30 22:27:01 +00004820 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004821 break;
4822 }
4823
4824 // Check the expression is a constant expression.
4825 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4826 Expr::EvalResult Eval;
4827 Eval.Diag = &Notes;
4828
4829 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4830 // The expression can't be folded, so we can't keep it at this position in
4831 // the AST.
4832 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004833 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004834 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004835
4836 if (Notes.empty()) {
4837 // It's a constant expression.
4838 return Result;
4839 }
Richard Smithf8379a02012-01-18 23:55:52 +00004840 }
4841
Richard Smith911e1422012-01-30 22:27:01 +00004842 // Only issue one narrowing diagnostic.
4843 if (Diagnosed)
4844 return Result;
4845
Richard Smithf8379a02012-01-18 23:55:52 +00004846 // It's not a constant expression. Produce an appropriate diagnostic.
4847 if (Notes.size() == 1 &&
4848 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4849 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4850 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004851 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004852 << CCE << From->getSourceRange();
4853 for (unsigned I = 0; I < Notes.size(); ++I)
4854 Diag(Notes[I].first, Notes[I].second);
4855 }
Richard Smith911e1422012-01-30 22:27:01 +00004856 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004857}
4858
John McCallfec112d2011-09-09 06:11:02 +00004859/// dropPointerConversions - If the given standard conversion sequence
4860/// involves any pointer conversions, remove them. This may change
4861/// the result type of the conversion sequence.
4862static void dropPointerConversion(StandardConversionSequence &SCS) {
4863 if (SCS.Second == ICK_Pointer_Conversion) {
4864 SCS.Second = ICK_Identity;
4865 SCS.Third = ICK_Identity;
4866 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4867 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004868}
John McCall5c32be02010-08-24 20:38:10 +00004869
John McCallfec112d2011-09-09 06:11:02 +00004870/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4871/// convert the expression From to an Objective-C pointer type.
4872static ImplicitConversionSequence
4873TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4874 // Do an implicit conversion to 'id'.
4875 QualType Ty = S.Context.getObjCIdType();
4876 ImplicitConversionSequence ICS
4877 = TryImplicitConversion(S, From, Ty,
4878 // FIXME: Are these flags correct?
4879 /*SuppressUserConversions=*/false,
4880 /*AllowExplicit=*/true,
4881 /*InOverloadResolution=*/false,
4882 /*CStyle=*/false,
4883 /*AllowObjCWritebackConversion=*/false);
4884
4885 // Strip off any final conversions to 'id'.
4886 switch (ICS.getKind()) {
4887 case ImplicitConversionSequence::BadConversion:
4888 case ImplicitConversionSequence::AmbiguousConversion:
4889 case ImplicitConversionSequence::EllipsisConversion:
4890 break;
4891
4892 case ImplicitConversionSequence::UserDefinedConversion:
4893 dropPointerConversion(ICS.UserDefined.After);
4894 break;
4895
4896 case ImplicitConversionSequence::StandardConversion:
4897 dropPointerConversion(ICS.Standard);
4898 break;
4899 }
4900
4901 return ICS;
4902}
4903
4904/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4905/// conversion of the expression From to an Objective-C pointer type.
4906ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004907 if (checkPlaceholderForOverload(*this, From))
4908 return ExprError();
4909
John McCall8b07ec22010-05-15 11:32:37 +00004910 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004911 ImplicitConversionSequence ICS =
4912 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004913 if (!ICS.isBad())
4914 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004915 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004916}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004917
Richard Smith8dd34252012-02-04 07:07:42 +00004918/// Determine whether the provided type is an integral type, or an enumeration
4919/// type of a permitted flavor.
4920static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4921 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4922 : T->isIntegralOrUnscopedEnumerationType();
4923}
4924
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004926/// enumeration type.
4927///
4928/// This routine will attempt to convert an expression of class type to an
4929/// integral or enumeration type, if that class type only has a single
4930/// conversion to an integral or enumeration type.
4931///
Douglas Gregor4799d032010-06-30 00:20:43 +00004932/// \param Loc The source location of the construct that requires the
4933/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004934///
Douglas Gregor4799d032010-06-30 00:20:43 +00004935/// \param FromE The expression we're converting from.
4936///
4937/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4938/// have integral or enumeration type.
4939///
4940/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4941/// incomplete class type.
4942///
4943/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4944/// explicit conversion function (because no implicit conversion functions
4945/// were available). This is a recovery mode.
4946///
4947/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4948/// showing which conversion was picked.
4949///
4950/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4951/// conversion function that could convert to integral or enumeration type.
4952///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004954/// usable conversion function.
4955///
4956/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4957/// function, which may be an extension in this case.
4958///
Richard Smith8dd34252012-02-04 07:07:42 +00004959/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4960/// enumerations should be considered.
4961///
Douglas Gregor4799d032010-06-30 00:20:43 +00004962/// \returns The expression, converted to an integral or enumeration type if
4963/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964ExprResult
John McCallb268a282010-08-23 23:25:46 +00004965Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004966 const PartialDiagnostic &NotIntDiag,
4967 const PartialDiagnostic &IncompleteDiag,
4968 const PartialDiagnostic &ExplicitConvDiag,
4969 const PartialDiagnostic &ExplicitConvNote,
4970 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004971 const PartialDiagnostic &AmbigNote,
Richard Smith8dd34252012-02-04 07:07:42 +00004972 const PartialDiagnostic &ConvDiag,
4973 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004974 // We can't perform any more checking for type-dependent expressions.
4975 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004976 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977
Eli Friedman1da70392012-01-26 00:26:18 +00004978 // Process placeholders immediately.
4979 if (From->hasPlaceholderType()) {
4980 ExprResult result = CheckPlaceholderExpr(From);
4981 if (result.isInvalid()) return result;
4982 From = result.take();
4983 }
4984
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004985 // If the expression already has integral or enumeration type, we're golden.
4986 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00004987 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00004988 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004989
4990 // FIXME: Check for missing '()' if T is a function type?
4991
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004992 // 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 +00004993 // expression of integral or enumeration type.
4994 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004995 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithf4c51d92012-02-04 09:53:13 +00004996 if (NotIntDiag.getDiagID())
4997 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004998 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005001 // We must have a complete class type.
5002 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00005003 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005005 // Look for a conversion to an integral or enumeration type.
5006 UnresolvedSet<4> ViableConversions;
5007 UnresolvedSet<4> ExplicitConversions;
5008 const UnresolvedSetImpl *Conversions
5009 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005010
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005011 bool HadMultipleCandidates = (Conversions->size() > 1);
5012
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005013 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014 E = Conversions->end();
5015 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005016 ++I) {
5017 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005018 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5019 if (isIntegralOrEnumerationType(
5020 Conversion->getConversionType().getNonReferenceType(),
5021 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005022 if (Conversion->isExplicit())
5023 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5024 else
5025 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5026 }
Richard Smith8dd34252012-02-04 07:07:42 +00005027 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005028 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005029
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005030 switch (ViableConversions.size()) {
5031 case 0:
Richard Smithf4c51d92012-02-04 09:53:13 +00005032 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005033 DeclAccessPair Found = ExplicitConversions[0];
5034 CXXConversionDecl *Conversion
5035 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005037 // The user probably meant to invoke the given explicit
5038 // conversion; use it.
5039 QualType ConvTy
5040 = Conversion->getConversionType().getNonReferenceType();
5041 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005042 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005044 Diag(Loc, ExplicitConvDiag)
5045 << T << ConvTy
5046 << FixItHint::CreateInsertion(From->getLocStart(),
5047 "static_cast<" + TypeStr + ">(")
5048 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5049 ")");
5050 Diag(Conversion->getLocation(), ExplicitConvNote)
5051 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
5053 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005054 // explicit conversion function.
5055 if (isSFINAEContext())
5056 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005058 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005059 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5060 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005061 if (Result.isInvalid())
5062 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005063 // Record usage of conversion in an implicit cast.
5064 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5065 CK_UserDefinedConversion,
5066 Result.get(), 0,
5067 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005070 // We'll complain below about a non-integral condition type.
5071 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005073 case 1: {
5074 // Apply this conversion.
5075 DeclAccessPair Found = ViableConversions[0];
5076 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077
Douglas Gregor4799d032010-06-30 00:20:43 +00005078 CXXConversionDecl *Conversion
5079 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5080 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00005082 if (ConvDiag.getDiagID()) {
5083 if (isSFINAEContext())
5084 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085
Douglas Gregor4799d032010-06-30 00:20:43 +00005086 Diag(Loc, ConvDiag)
5087 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005090 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5091 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005092 if (Result.isInvalid())
5093 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005094 // Record usage of conversion in an implicit cast.
5095 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5096 CK_UserDefinedConversion,
5097 Result.get(), 0,
5098 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005099 break;
5100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005102 default:
Richard Smithf4c51d92012-02-04 09:53:13 +00005103 if (!AmbigDiag.getDiagID())
5104 return Owned(From);
5105
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005106 Diag(Loc, AmbigDiag)
5107 << T << From->getSourceRange();
5108 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5109 CXXConversionDecl *Conv
5110 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5111 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5112 Diag(Conv->getLocation(), AmbigNote)
5113 << ConvTy->isEnumeralType() << ConvTy;
5114 }
John McCallb268a282010-08-23 23:25:46 +00005115 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Richard Smithf4c51d92012-02-04 09:53:13 +00005118 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5119 NotIntDiag.getDiagID())
5120 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005121
Eli Friedman1da70392012-01-26 00:26:18 +00005122 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005123}
5124
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005125/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005126/// candidate functions, using the given function call arguments. If
5127/// @p SuppressUserConversions, then don't allow user-defined
5128/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005129///
5130/// \para PartialOverloading true if we are performing "partial" overloading
5131/// based on an incomplete set of function arguments. This feature is used by
5132/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005133void
5134Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005135 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005136 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005137 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005138 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005139 bool PartialOverloading,
5140 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005141 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005142 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005143 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005144 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005145 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005146
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005148 if (!isa<CXXConstructorDecl>(Method)) {
5149 // If we get here, it's because we're calling a member function
5150 // that is named without a member access expression (e.g.,
5151 // "this->f") that was either written explicitly or created
5152 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005153 // function, e.g., X::f(). We use an empty type for the implied
5154 // object argument (C++ [over.call.func]p3), and the acting context
5155 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005156 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005158 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005159 return;
5160 }
5161 // We treat a constructor like a non-member function, since its object
5162 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005163 }
5164
Douglas Gregorff7028a2009-11-13 23:59:09 +00005165 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005166 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005167
Douglas Gregor27381f32009-11-23 12:27:39 +00005168 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005169 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005170
Douglas Gregorffe14e32009-11-14 01:20:54 +00005171 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5172 // C++ [class.copy]p3:
5173 // A member function template is never instantiated to perform the copy
5174 // of a class object to an object of its class type.
5175 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005176 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005177 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005178 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5179 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005180 return;
5181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005182
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005183 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005184 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005185 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005186 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005187 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005188 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005189 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005190 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005191
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005192 unsigned NumArgsInProto = Proto->getNumArgs();
5193
5194 // (C++ 13.3.2p2): A candidate function having fewer than m
5195 // parameters is viable only if it has an ellipsis in its parameter
5196 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005197 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005198 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005199 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005200 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005201 return;
5202 }
5203
5204 // (C++ 13.3.2p2): A candidate function having more than m parameters
5205 // is viable only if the (m+1)st parameter has a default argument
5206 // (8.3.6). For the purposes of overload resolution, the
5207 // parameter list is truncated on the right, so that there are
5208 // exactly m parameters.
5209 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005210 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005211 // Not enough arguments.
5212 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005213 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005214 return;
5215 }
5216
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005217 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005218 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005219 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5220 if (CheckCUDATarget(Caller, Function)) {
5221 Candidate.Viable = false;
5222 Candidate.FailureKind = ovl_fail_bad_target;
5223 return;
5224 }
5225
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005226 // Determine the implicit conversion sequences for each of the
5227 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005228 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005229 if (ArgIdx < NumArgsInProto) {
5230 // (C++ 13.3.2p3): for F to be a viable function, there shall
5231 // exist for each argument an implicit conversion sequence
5232 // (13.3.3.1) that converts that argument to the corresponding
5233 // parameter of F.
5234 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005235 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005236 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005237 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005238 /*InOverloadResolution=*/true,
5239 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005240 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005241 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005242 if (Candidate.Conversions[ArgIdx].isBad()) {
5243 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005244 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005245 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005246 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005247 } else {
5248 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5249 // argument for which there is no corresponding parameter is
5250 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005251 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005252 }
5253 }
5254}
5255
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005256/// \brief Add all of the function declarations in the given function set to
5257/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005258void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005259 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005260 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005261 bool SuppressUserConversions,
5262 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005263 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005264 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5265 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005266 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005267 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005268 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005269 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005270 Args.slice(1), CandidateSet,
5271 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005272 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005273 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005274 SuppressUserConversions);
5275 } else {
John McCalla0296f72010-03-19 07:35:19 +00005276 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005277 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5278 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005279 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005280 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005281 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005282 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005283 Args[0]->Classify(Context), Args.slice(1),
5284 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005285 else
John McCalla0296f72010-03-19 07:35:19 +00005286 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005287 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005288 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005289 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005290 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005291}
5292
John McCallf0f1cf02009-11-17 07:50:12 +00005293/// AddMethodCandidate - Adds a named decl (which is some kind of
5294/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005295void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005296 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005297 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005298 Expr **Args, unsigned NumArgs,
5299 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005300 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005301 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005302 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005303
5304 if (isa<UsingShadowDecl>(Decl))
5305 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306
John McCallf0f1cf02009-11-17 07:50:12 +00005307 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5308 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5309 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005310 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5311 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005312 ObjectType, ObjectClassification,
5313 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005314 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005315 } else {
John McCalla0296f72010-03-19 07:35:19 +00005316 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005317 ObjectType, ObjectClassification,
5318 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005319 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005320 }
5321}
5322
Douglas Gregor436424c2008-11-18 23:14:02 +00005323/// AddMethodCandidate - Adds the given C++ member function to the set
5324/// of candidate functions, using the given function call arguments
5325/// and the object argument (@c Object). For example, in a call
5326/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5327/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5328/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005329/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005330void
John McCalla0296f72010-03-19 07:35:19 +00005331Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005332 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005333 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005334 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005335 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005336 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005337 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005338 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005339 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005340 assert(!isa<CXXConstructorDecl>(Method) &&
5341 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005342
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005343 if (!CandidateSet.isNewCandidate(Method))
5344 return;
5345
Douglas Gregor27381f32009-11-23 12:27:39 +00005346 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005347 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005348
Douglas Gregor436424c2008-11-18 23:14:02 +00005349 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005350 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005351 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005352 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005353 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005354 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005355 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005356
5357 unsigned NumArgsInProto = Proto->getNumArgs();
5358
5359 // (C++ 13.3.2p2): A candidate function having fewer than m
5360 // parameters is viable only if it has an ellipsis in its parameter
5361 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005362 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005363 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005364 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005365 return;
5366 }
5367
5368 // (C++ 13.3.2p2): A candidate function having more than m parameters
5369 // is viable only if the (m+1)st parameter has a default argument
5370 // (8.3.6). For the purposes of overload resolution, the
5371 // parameter list is truncated on the right, so that there are
5372 // exactly m parameters.
5373 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005374 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005375 // Not enough arguments.
5376 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005377 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005378 return;
5379 }
5380
5381 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005382
John McCall6e9f8f62009-12-03 04:06:58 +00005383 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005384 // The implicit object argument is ignored.
5385 Candidate.IgnoreObjectArgument = true;
5386 else {
5387 // Determine the implicit conversion sequence for the object
5388 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005389 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005390 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5391 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005392 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005393 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005394 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005395 return;
5396 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005397 }
5398
5399 // Determine the implicit conversion sequences for each of the
5400 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005401 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005402 if (ArgIdx < NumArgsInProto) {
5403 // (C++ 13.3.2p3): for F to be a viable function, there shall
5404 // exist for each argument an implicit conversion sequence
5405 // (13.3.3.1) that converts that argument to the corresponding
5406 // parameter of F.
5407 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005408 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005409 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005410 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005411 /*InOverloadResolution=*/true,
5412 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005413 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005414 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005415 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005416 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005417 break;
5418 }
5419 } else {
5420 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5421 // argument for which there is no corresponding parameter is
5422 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005423 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005424 }
5425 }
5426}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
Douglas Gregor97628d62009-08-21 00:16:32 +00005428/// \brief Add a C++ member function template as a candidate to the candidate
5429/// set, using template argument deduction to produce an appropriate member
5430/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005431void
Douglas Gregor97628d62009-08-21 00:16:32 +00005432Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005433 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005434 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005435 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005436 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005437 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005438 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005439 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005440 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005441 if (!CandidateSet.isNewCandidate(MethodTmpl))
5442 return;
5443
Douglas Gregor97628d62009-08-21 00:16:32 +00005444 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005445 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005446 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005447 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005448 // candidate functions in the usual way.113) A given name can refer to one
5449 // or more function templates and also to a set of overloaded non-template
5450 // functions. In such a case, the candidate functions generated from each
5451 // function template are combined with the set of non-template candidate
5452 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005453 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005454 FunctionDecl *Specialization = 0;
5455 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005456 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5457 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005458 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005459 Candidate.FoundDecl = FoundDecl;
5460 Candidate.Function = MethodTmpl->getTemplatedDecl();
5461 Candidate.Viable = false;
5462 Candidate.FailureKind = ovl_fail_bad_deduction;
5463 Candidate.IsSurrogate = false;
5464 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005465 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005466 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005467 Info);
5468 return;
5469 }
Mike Stump11289f42009-09-09 15:08:12 +00005470
Douglas Gregor97628d62009-08-21 00:16:32 +00005471 // Add the function template specialization produced by template argument
5472 // deduction as a candidate.
5473 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005474 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005475 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005476 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005477 ActingContext, ObjectType, ObjectClassification, Args,
5478 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005479}
5480
Douglas Gregor05155d82009-08-21 23:19:43 +00005481/// \brief Add a C++ function template specialization as a candidate
5482/// in the candidate set, using template argument deduction to produce
5483/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005484void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005485Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005486 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005487 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005488 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005489 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005490 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005491 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5492 return;
5493
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005494 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005495 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005496 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005497 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005498 // candidate functions in the usual way.113) A given name can refer to one
5499 // or more function templates and also to a set of overloaded non-template
5500 // functions. In such a case, the candidate functions generated from each
5501 // function template are combined with the set of non-template candidate
5502 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005503 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005504 FunctionDecl *Specialization = 0;
5505 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005506 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5507 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005508 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005509 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005510 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5511 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005512 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005513 Candidate.IsSurrogate = false;
5514 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005515 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005516 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005517 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005518 return;
5519 }
Mike Stump11289f42009-09-09 15:08:12 +00005520
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005521 // Add the function template specialization produced by template argument
5522 // deduction as a candidate.
5523 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005524 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005525 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005526}
Mike Stump11289f42009-09-09 15:08:12 +00005527
Douglas Gregora1f013e2008-11-07 22:36:19 +00005528/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005529/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005530/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005531/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005532/// (which may or may not be the same type as the type that the
5533/// conversion function produces).
5534void
5535Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005536 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005537 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005538 Expr *From, QualType ToType,
5539 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005540 assert(!Conversion->getDescribedFunctionTemplate() &&
5541 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005542 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005543 if (!CandidateSet.isNewCandidate(Conversion))
5544 return;
5545
Douglas Gregor27381f32009-11-23 12:27:39 +00005546 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005547 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005548
Douglas Gregora1f013e2008-11-07 22:36:19 +00005549 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005550 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005551 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005552 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005553 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005554 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005555 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005556 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005557 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005558 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005559 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005560
Douglas Gregor6affc782010-08-19 15:37:02 +00005561 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562 // For conversion functions, the function is considered to be a member of
5563 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005564 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005565 //
5566 // Determine the implicit conversion sequence for the implicit
5567 // object parameter.
5568 QualType ImplicitParamType = From->getType();
5569 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5570 ImplicitParamType = FromPtrType->getPointeeType();
5571 CXXRecordDecl *ConversionContext
5572 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005574 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575 = TryObjectArgumentInitialization(*this, From->getType(),
5576 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005577 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578
John McCall0d1da222010-01-12 00:44:57 +00005579 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005580 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005581 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005582 return;
5583 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005584
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005585 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005586 // derived to base as such conversions are given Conversion Rank. They only
5587 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5588 QualType FromCanon
5589 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5590 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5591 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5592 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005593 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005594 return;
5595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Douglas Gregora1f013e2008-11-07 22:36:19 +00005597 // To determine what the conversion from the result of calling the
5598 // conversion function to the type we're eventually trying to
5599 // convert to (ToType), we need to synthesize a call to the
5600 // conversion function and attempt copy initialization from it. This
5601 // makes sure that we get the right semantics with respect to
5602 // lvalues/rvalues and the type. Fortunately, we can allocate this
5603 // call on the stack and we don't need its arguments to be
5604 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005605 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005606 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005607 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5608 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005609 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005610 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005611
Richard Smith48d24642011-07-13 22:53:21 +00005612 QualType ConversionType = Conversion->getConversionType();
5613 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005614 Candidate.Viable = false;
5615 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5616 return;
5617 }
5618
Richard Smith48d24642011-07-13 22:53:21 +00005619 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005620
Mike Stump11289f42009-09-09 15:08:12 +00005621 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005622 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5623 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005624 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005625 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005626 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005627 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005628 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005629 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005630 /*InOverloadResolution=*/false,
5631 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005632
John McCall0d1da222010-01-12 00:44:57 +00005633 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005634 case ImplicitConversionSequence::StandardConversion:
5635 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005636
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005637 // C++ [over.ics.user]p3:
5638 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005640 // shall have exact match rank.
5641 if (Conversion->getPrimaryTemplate() &&
5642 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5643 Candidate.Viable = false;
5644 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
Douglas Gregorcba72b12011-01-21 05:18:22 +00005647 // C++0x [dcl.init.ref]p5:
5648 // In the second case, if the reference is an rvalue reference and
5649 // the second standard conversion sequence of the user-defined
5650 // conversion sequence includes an lvalue-to-rvalue conversion, the
5651 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005653 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5654 Candidate.Viable = false;
5655 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5656 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005657 break;
5658
5659 case ImplicitConversionSequence::BadConversion:
5660 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005661 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005662 break;
5663
5664 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005665 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005666 "Can only end up with a standard conversion sequence or failure");
5667 }
5668}
5669
Douglas Gregor05155d82009-08-21 23:19:43 +00005670/// \brief Adds a conversion function template specialization
5671/// candidate to the overload set, using template argument deduction
5672/// to deduce the template arguments of the conversion function
5673/// template from the type that we are converting to (C++
5674/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005675void
Douglas Gregor05155d82009-08-21 23:19:43 +00005676Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005677 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005678 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005679 Expr *From, QualType ToType,
5680 OverloadCandidateSet &CandidateSet) {
5681 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5682 "Only conversion function templates permitted here");
5683
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005684 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5685 return;
5686
John McCallbc077cf2010-02-08 23:07:23 +00005687 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005688 CXXConversionDecl *Specialization = 0;
5689 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005690 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005691 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005692 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005693 Candidate.FoundDecl = FoundDecl;
5694 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5695 Candidate.Viable = false;
5696 Candidate.FailureKind = ovl_fail_bad_deduction;
5697 Candidate.IsSurrogate = false;
5698 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005699 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005700 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005701 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005702 return;
5703 }
Mike Stump11289f42009-09-09 15:08:12 +00005704
Douglas Gregor05155d82009-08-21 23:19:43 +00005705 // Add the conversion function template specialization produced by
5706 // template argument deduction as a candidate.
5707 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005708 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005709 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005710}
5711
Douglas Gregorab7897a2008-11-19 22:57:39 +00005712/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5713/// converts the given @c Object to a function pointer via the
5714/// conversion function @c Conversion, and then attempts to call it
5715/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5716/// the type of function that we'll eventually be calling.
5717void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005718 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005719 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005720 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005721 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005722 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005723 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005724 if (!CandidateSet.isNewCandidate(Conversion))
5725 return;
5726
Douglas Gregor27381f32009-11-23 12:27:39 +00005727 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005728 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005729
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005730 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005731 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005732 Candidate.Function = 0;
5733 Candidate.Surrogate = Conversion;
5734 Candidate.Viable = true;
5735 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005736 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005737 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005738
5739 // Determine the implicit conversion sequence for the implicit
5740 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005741 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005742 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005743 Object->Classify(Context),
5744 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005745 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005746 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005747 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005748 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005749 return;
5750 }
5751
5752 // The first conversion is actually a user-defined conversion whose
5753 // first conversion is ObjectInit's standard conversion (which is
5754 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005755 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005756 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005757 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005758 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005759 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005760 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005761 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005762 = Candidate.Conversions[0].UserDefined.Before;
5763 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5764
Mike Stump11289f42009-09-09 15:08:12 +00005765 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005766 unsigned NumArgsInProto = Proto->getNumArgs();
5767
5768 // (C++ 13.3.2p2): A candidate function having fewer than m
5769 // parameters is viable only if it has an ellipsis in its parameter
5770 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005771 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005772 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005773 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005774 return;
5775 }
5776
5777 // Function types don't have any default arguments, so just check if
5778 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005779 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005780 // Not enough arguments.
5781 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005782 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005783 return;
5784 }
5785
5786 // Determine the implicit conversion sequences for each of the
5787 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005788 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005789 if (ArgIdx < NumArgsInProto) {
5790 // (C++ 13.3.2p3): for F to be a viable function, there shall
5791 // exist for each argument an implicit conversion sequence
5792 // (13.3.3.1) that converts that argument to the corresponding
5793 // parameter of F.
5794 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005795 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005796 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005797 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005798 /*InOverloadResolution=*/false,
5799 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005800 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005801 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005802 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005803 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005804 break;
5805 }
5806 } else {
5807 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5808 // argument for which there is no corresponding parameter is
5809 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005810 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005811 }
5812 }
5813}
5814
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005815/// \brief Add overload candidates for overloaded operators that are
5816/// member functions.
5817///
5818/// Add the overloaded operator candidates that are member functions
5819/// for the operator Op that was used in an operator expression such
5820/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5821/// CandidateSet will store the added overload candidates. (C++
5822/// [over.match.oper]).
5823void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5824 SourceLocation OpLoc,
5825 Expr **Args, unsigned NumArgs,
5826 OverloadCandidateSet& CandidateSet,
5827 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005828 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5829
5830 // C++ [over.match.oper]p3:
5831 // For a unary operator @ with an operand of a type whose
5832 // cv-unqualified version is T1, and for a binary operator @ with
5833 // a left operand of a type whose cv-unqualified version is T1 and
5834 // a right operand of a type whose cv-unqualified version is T2,
5835 // three sets of candidate functions, designated member
5836 // candidates, non-member candidates and built-in candidates, are
5837 // constructed as follows:
5838 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005839
5840 // -- If T1 is a class type, the set of member candidates is the
5841 // result of the qualified lookup of T1::operator@
5842 // (13.3.1.1.1); otherwise, the set of member candidates is
5843 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005844 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005845 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005846 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005847 return;
Mike Stump11289f42009-09-09 15:08:12 +00005848
John McCall27b18f82009-11-17 02:14:36 +00005849 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5850 LookupQualifiedName(Operators, T1Rec->getDecl());
5851 Operators.suppressDiagnostics();
5852
Mike Stump11289f42009-09-09 15:08:12 +00005853 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005854 OperEnd = Operators.end();
5855 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005856 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005857 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005858 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005859 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005860 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005861 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005862}
5863
Douglas Gregora11693b2008-11-12 17:17:38 +00005864/// AddBuiltinCandidate - Add a candidate for a built-in
5865/// operator. ResultTy and ParamTys are the result and parameter types
5866/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005867/// arguments being passed to the candidate. IsAssignmentOperator
5868/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005869/// operator. NumContextualBoolArguments is the number of arguments
5870/// (at the beginning of the argument list) that will be contextually
5871/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005872void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005873 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005874 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005875 bool IsAssignmentOperator,
5876 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005877 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005878 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005879
Douglas Gregora11693b2008-11-12 17:17:38 +00005880 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005881 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005882 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005883 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005884 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005885 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005886 Candidate.BuiltinTypes.ResultTy = ResultTy;
5887 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5888 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5889
5890 // Determine the implicit conversion sequences for each of the
5891 // arguments.
5892 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005893 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005894 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005895 // C++ [over.match.oper]p4:
5896 // For the built-in assignment operators, conversions of the
5897 // left operand are restricted as follows:
5898 // -- no temporaries are introduced to hold the left operand, and
5899 // -- no user-defined conversions are applied to the left
5900 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005901 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005902 //
5903 // We block these conversions by turning off user-defined
5904 // conversions, since that is the only way that initialization of
5905 // a reference to a non-class type can occur from something that
5906 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005907 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005908 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005909 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005910 Candidate.Conversions[ArgIdx]
5911 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005912 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005913 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005914 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005915 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005916 /*InOverloadResolution=*/false,
5917 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005918 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005919 }
John McCall0d1da222010-01-12 00:44:57 +00005920 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005921 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005922 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005923 break;
5924 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005925 }
5926}
5927
5928/// BuiltinCandidateTypeSet - A set of types that will be used for the
5929/// candidate operator functions for built-in operators (C++
5930/// [over.built]). The types are separated into pointer types and
5931/// enumeration types.
5932class BuiltinCandidateTypeSet {
5933 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005934 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005935
5936 /// PointerTypes - The set of pointer types that will be used in the
5937 /// built-in candidates.
5938 TypeSet PointerTypes;
5939
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005940 /// MemberPointerTypes - The set of member pointer types that will be
5941 /// used in the built-in candidates.
5942 TypeSet MemberPointerTypes;
5943
Douglas Gregora11693b2008-11-12 17:17:38 +00005944 /// EnumerationTypes - The set of enumeration types that will be
5945 /// used in the built-in candidates.
5946 TypeSet EnumerationTypes;
5947
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005948 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005949 /// candidates.
5950 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005951
5952 /// \brief A flag indicating non-record types are viable candidates
5953 bool HasNonRecordTypes;
5954
5955 /// \brief A flag indicating whether either arithmetic or enumeration types
5956 /// were present in the candidate set.
5957 bool HasArithmeticOrEnumeralTypes;
5958
Douglas Gregor80af3132011-05-21 23:15:46 +00005959 /// \brief A flag indicating whether the nullptr type was present in the
5960 /// candidate set.
5961 bool HasNullPtrType;
5962
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005963 /// Sema - The semantic analysis instance where we are building the
5964 /// candidate type set.
5965 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005966
Douglas Gregora11693b2008-11-12 17:17:38 +00005967 /// Context - The AST context in which we will build the type sets.
5968 ASTContext &Context;
5969
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005970 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5971 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005972 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005973
5974public:
5975 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005976 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005977
Mike Stump11289f42009-09-09 15:08:12 +00005978 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005979 : HasNonRecordTypes(false),
5980 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005981 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005982 SemaRef(SemaRef),
5983 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005984
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005986 SourceLocation Loc,
5987 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005988 bool AllowExplicitConversions,
5989 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005990
5991 /// pointer_begin - First pointer type found;
5992 iterator pointer_begin() { return PointerTypes.begin(); }
5993
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005994 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005995 iterator pointer_end() { return PointerTypes.end(); }
5996
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005997 /// member_pointer_begin - First member pointer type found;
5998 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5999
6000 /// member_pointer_end - Past the last member pointer type found;
6001 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6002
Douglas Gregora11693b2008-11-12 17:17:38 +00006003 /// enumeration_begin - First enumeration type found;
6004 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6005
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006006 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006007 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006008
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006009 iterator vector_begin() { return VectorTypes.begin(); }
6010 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006011
6012 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6013 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006014 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006015};
6016
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006017/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006018/// the set of pointer types along with any more-qualified variants of
6019/// that type. For example, if @p Ty is "int const *", this routine
6020/// will add "int const *", "int const volatile *", "int const
6021/// restrict *", and "int const volatile restrict *" to the set of
6022/// pointer types. Returns true if the add of @p Ty itself succeeded,
6023/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006024///
6025/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006026bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006027BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6028 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006029
Douglas Gregora11693b2008-11-12 17:17:38 +00006030 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006031 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006032 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006033
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006034 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006035 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006036 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006037 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006038 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006039 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006040 buildObjCPtr = true;
6041 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006042 else
David Blaikie83d382b2011-09-23 05:06:16 +00006043 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006044 }
6045 else
6046 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006047
Sebastian Redl4990a632009-11-18 20:39:26 +00006048 // Don't add qualified variants of arrays. For one, they're not allowed
6049 // (the qualifier would sink to the element type), and for another, the
6050 // only overload situation where it matters is subscript or pointer +- int,
6051 // and those shouldn't have qualifier variants anyway.
6052 if (PointeeTy->isArrayType())
6053 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006054 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00006055 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00006056 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006057 bool hasVolatile = VisibleQuals.hasVolatile();
6058 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059
John McCall8ccfcb52009-09-24 19:53:00 +00006060 // Iterate through all strict supersets of BaseCVR.
6061 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6062 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006063 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6064 // in the types.
6065 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6066 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00006067 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006068 if (!buildObjCPtr)
6069 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6070 else
6071 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00006072 }
6073
6074 return true;
6075}
6076
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006077/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6078/// to the set of pointer types along with any more-qualified variants of
6079/// that type. For example, if @p Ty is "int const *", this routine
6080/// will add "int const *", "int const volatile *", "int const
6081/// restrict *", and "int const volatile restrict *" to the set of
6082/// pointer types. Returns true if the add of @p Ty itself succeeded,
6083/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006084///
6085/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006086bool
6087BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6088 QualType Ty) {
6089 // Insert this type.
6090 if (!MemberPointerTypes.insert(Ty))
6091 return false;
6092
John McCall8ccfcb52009-09-24 19:53:00 +00006093 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6094 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006095
John McCall8ccfcb52009-09-24 19:53:00 +00006096 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006097 // Don't add qualified variants of arrays. For one, they're not allowed
6098 // (the qualifier would sink to the element type), and for another, the
6099 // only overload situation where it matters is subscript or pointer +- int,
6100 // and those shouldn't have qualifier variants anyway.
6101 if (PointeeTy->isArrayType())
6102 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006103 const Type *ClassTy = PointerTy->getClass();
6104
6105 // Iterate through all strict supersets of the pointee type's CVR
6106 // qualifiers.
6107 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6108 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6109 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006110
John McCall8ccfcb52009-09-24 19:53:00 +00006111 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006112 MemberPointerTypes.insert(
6113 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006114 }
6115
6116 return true;
6117}
6118
Douglas Gregora11693b2008-11-12 17:17:38 +00006119/// AddTypesConvertedFrom - Add each of the types to which the type @p
6120/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006121/// primarily interested in pointer types and enumeration types. We also
6122/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006123/// AllowUserConversions is true if we should look at the conversion
6124/// functions of a class type, and AllowExplicitConversions if we
6125/// should also include the explicit conversion functions of a class
6126/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006127void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006128BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006129 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006130 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006131 bool AllowExplicitConversions,
6132 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006133 // Only deal with canonical types.
6134 Ty = Context.getCanonicalType(Ty);
6135
6136 // Look through reference types; they aren't part of the type of an
6137 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006138 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006139 Ty = RefTy->getPointeeType();
6140
John McCall33ddac02011-01-19 10:06:00 +00006141 // If we're dealing with an array type, decay to the pointer.
6142 if (Ty->isArrayType())
6143 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6144
6145 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006146 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006147
Chandler Carruth00a38332010-12-13 01:44:01 +00006148 // Flag if we ever add a non-record type.
6149 const RecordType *TyRec = Ty->getAs<RecordType>();
6150 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6151
Chandler Carruth00a38332010-12-13 01:44:01 +00006152 // Flag if we encounter an arithmetic type.
6153 HasArithmeticOrEnumeralTypes =
6154 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6155
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006156 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6157 PointerTypes.insert(Ty);
6158 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006159 // Insert our type, and its more-qualified variants, into the set
6160 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006161 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006162 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006163 } else if (Ty->isMemberPointerType()) {
6164 // Member pointers are far easier, since the pointee can't be converted.
6165 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6166 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006167 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006168 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006169 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006170 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006171 // We treat vector types as arithmetic types in many contexts as an
6172 // extension.
6173 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006174 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006175 } else if (Ty->isNullPtrType()) {
6176 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006177 } else if (AllowUserConversions && TyRec) {
6178 // No conversion functions in incomplete types.
6179 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6180 return;
Mike Stump11289f42009-09-09 15:08:12 +00006181
Chandler Carruth00a38332010-12-13 01:44:01 +00006182 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6183 const UnresolvedSetImpl *Conversions
6184 = ClassDecl->getVisibleConversionFunctions();
6185 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6186 E = Conversions->end(); I != E; ++I) {
6187 NamedDecl *D = I.getDecl();
6188 if (isa<UsingShadowDecl>(D))
6189 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006190
Chandler Carruth00a38332010-12-13 01:44:01 +00006191 // Skip conversion function templates; they don't tell us anything
6192 // about which builtin types we can convert to.
6193 if (isa<FunctionTemplateDecl>(D))
6194 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006195
Chandler Carruth00a38332010-12-13 01:44:01 +00006196 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6197 if (AllowExplicitConversions || !Conv->isExplicit()) {
6198 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6199 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006200 }
6201 }
6202 }
6203}
6204
Douglas Gregor84605ae2009-08-24 13:43:27 +00006205/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6206/// the volatile- and non-volatile-qualified assignment operators for the
6207/// given type to the candidate set.
6208static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6209 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006210 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006211 unsigned NumArgs,
6212 OverloadCandidateSet &CandidateSet) {
6213 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006214
Douglas Gregor84605ae2009-08-24 13:43:27 +00006215 // T& operator=(T&, T)
6216 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6217 ParamTypes[1] = T;
6218 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6219 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006220
Douglas Gregor84605ae2009-08-24 13:43:27 +00006221 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6222 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006223 ParamTypes[0]
6224 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006225 ParamTypes[1] = T;
6226 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006227 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006228 }
6229}
Mike Stump11289f42009-09-09 15:08:12 +00006230
Sebastian Redl1054fae2009-10-25 17:03:50 +00006231/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6232/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006233static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6234 Qualifiers VRQuals;
6235 const RecordType *TyRec;
6236 if (const MemberPointerType *RHSMPType =
6237 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006238 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006239 else
6240 TyRec = ArgExpr->getType()->getAs<RecordType>();
6241 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006242 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006243 VRQuals.addVolatile();
6244 VRQuals.addRestrict();
6245 return VRQuals;
6246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006247
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006248 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006249 if (!ClassDecl->hasDefinition())
6250 return VRQuals;
6251
John McCallad371252010-01-20 00:46:10 +00006252 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006253 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006254
John McCallad371252010-01-20 00:46:10 +00006255 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006256 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006257 NamedDecl *D = I.getDecl();
6258 if (isa<UsingShadowDecl>(D))
6259 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6260 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006261 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6262 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6263 CanTy = ResTypeRef->getPointeeType();
6264 // Need to go down the pointer/mempointer chain and add qualifiers
6265 // as see them.
6266 bool done = false;
6267 while (!done) {
6268 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6269 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006270 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006271 CanTy->getAs<MemberPointerType>())
6272 CanTy = ResTypeMPtr->getPointeeType();
6273 else
6274 done = true;
6275 if (CanTy.isVolatileQualified())
6276 VRQuals.addVolatile();
6277 if (CanTy.isRestrictQualified())
6278 VRQuals.addRestrict();
6279 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6280 return VRQuals;
6281 }
6282 }
6283 }
6284 return VRQuals;
6285}
John McCall52872982010-11-13 05:51:15 +00006286
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006287namespace {
John McCall52872982010-11-13 05:51:15 +00006288
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006289/// \brief Helper class to manage the addition of builtin operator overload
6290/// candidates. It provides shared state and utility methods used throughout
6291/// the process, as well as a helper method to add each group of builtin
6292/// operator overloads from the standard to a candidate set.
6293class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006294 // Common instance state available to all overload candidate addition methods.
6295 Sema &S;
6296 Expr **Args;
6297 unsigned NumArgs;
6298 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006299 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006300 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006301 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006302
Chandler Carruthc6586e52010-12-12 10:35:00 +00006303 // Define some constants used to index and iterate over the arithemetic types
6304 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006305 // The "promoted arithmetic types" are the arithmetic
6306 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006307 static const unsigned FirstIntegralType = 3;
6308 static const unsigned LastIntegralType = 18;
6309 static const unsigned FirstPromotedIntegralType = 3,
6310 LastPromotedIntegralType = 9;
6311 static const unsigned FirstPromotedArithmeticType = 0,
6312 LastPromotedArithmeticType = 9;
6313 static const unsigned NumArithmeticTypes = 18;
6314
Chandler Carruthc6586e52010-12-12 10:35:00 +00006315 /// \brief Get the canonical type for a given arithmetic type index.
6316 CanQualType getArithmeticType(unsigned index) {
6317 assert(index < NumArithmeticTypes);
6318 static CanQualType ASTContext::* const
6319 ArithmeticTypes[NumArithmeticTypes] = {
6320 // Start of promoted types.
6321 &ASTContext::FloatTy,
6322 &ASTContext::DoubleTy,
6323 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006324
Chandler Carruthc6586e52010-12-12 10:35:00 +00006325 // Start of integral types.
6326 &ASTContext::IntTy,
6327 &ASTContext::LongTy,
6328 &ASTContext::LongLongTy,
6329 &ASTContext::UnsignedIntTy,
6330 &ASTContext::UnsignedLongTy,
6331 &ASTContext::UnsignedLongLongTy,
6332 // End of promoted types.
6333
6334 &ASTContext::BoolTy,
6335 &ASTContext::CharTy,
6336 &ASTContext::WCharTy,
6337 &ASTContext::Char16Ty,
6338 &ASTContext::Char32Ty,
6339 &ASTContext::SignedCharTy,
6340 &ASTContext::ShortTy,
6341 &ASTContext::UnsignedCharTy,
6342 &ASTContext::UnsignedShortTy,
6343 // End of integral types.
6344 // FIXME: What about complex?
6345 };
6346 return S.Context.*ArithmeticTypes[index];
6347 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006348
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006349 /// \brief Gets the canonical type resulting from the usual arithemetic
6350 /// converions for the given arithmetic types.
6351 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6352 // Accelerator table for performing the usual arithmetic conversions.
6353 // The rules are basically:
6354 // - if either is floating-point, use the wider floating-point
6355 // - if same signedness, use the higher rank
6356 // - if same size, use unsigned of the higher rank
6357 // - use the larger type
6358 // These rules, together with the axiom that higher ranks are
6359 // never smaller, are sufficient to precompute all of these results
6360 // *except* when dealing with signed types of higher rank.
6361 // (we could precompute SLL x UI for all known platforms, but it's
6362 // better not to make any assumptions).
6363 enum PromotedType {
6364 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6365 };
6366 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6367 [LastPromotedArithmeticType] = {
6368 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6369 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6370 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6371 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6372 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6373 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6374 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6375 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6376 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6377 };
6378
6379 assert(L < LastPromotedArithmeticType);
6380 assert(R < LastPromotedArithmeticType);
6381 int Idx = ConversionsTable[L][R];
6382
6383 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006384 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006385
6386 // Slow path: we need to compare widths.
6387 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006388 CanQualType LT = getArithmeticType(L),
6389 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006390 unsigned LW = S.Context.getIntWidth(LT),
6391 RW = S.Context.getIntWidth(RT);
6392
6393 // If they're different widths, use the signed type.
6394 if (LW > RW) return LT;
6395 else if (LW < RW) return RT;
6396
6397 // Otherwise, use the unsigned type of the signed type's rank.
6398 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6399 assert(L == SLL || R == SLL);
6400 return S.Context.UnsignedLongLongTy;
6401 }
6402
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006403 /// \brief Helper method to factor out the common pattern of adding overloads
6404 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006405 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6406 bool HasVolatile) {
6407 QualType ParamTypes[2] = {
6408 S.Context.getLValueReferenceType(CandidateTy),
6409 S.Context.IntTy
6410 };
6411
6412 // Non-volatile version.
6413 if (NumArgs == 1)
6414 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6415 else
6416 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6417
6418 // Use a heuristic to reduce number of builtin candidates in the set:
6419 // add volatile version only if there are conversions to a volatile type.
6420 if (HasVolatile) {
6421 ParamTypes[0] =
6422 S.Context.getLValueReferenceType(
6423 S.Context.getVolatileType(CandidateTy));
6424 if (NumArgs == 1)
6425 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6426 else
6427 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6428 }
6429 }
6430
6431public:
6432 BuiltinOperatorOverloadBuilder(
6433 Sema &S, Expr **Args, unsigned NumArgs,
6434 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006435 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006436 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006437 OverloadCandidateSet &CandidateSet)
6438 : S(S), Args(Args), NumArgs(NumArgs),
6439 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006440 HasArithmeticOrEnumeralCandidateType(
6441 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006442 CandidateTypes(CandidateTypes),
6443 CandidateSet(CandidateSet) {
6444 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006445 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006446 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006447 assert(getArithmeticType(LastPromotedIntegralType - 1)
6448 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006449 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006450 assert(getArithmeticType(FirstPromotedArithmeticType)
6451 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006452 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006453 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6454 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006455 "Invalid last promoted arithmetic type");
6456 }
6457
6458 // C++ [over.built]p3:
6459 //
6460 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6461 // is either volatile or empty, there exist candidate operator
6462 // functions of the form
6463 //
6464 // VQ T& operator++(VQ T&);
6465 // T operator++(VQ T&, int);
6466 //
6467 // C++ [over.built]p4:
6468 //
6469 // For every pair (T, VQ), where T is an arithmetic type other
6470 // than bool, and VQ is either volatile or empty, there exist
6471 // candidate operator functions of the form
6472 //
6473 // VQ T& operator--(VQ T&);
6474 // T operator--(VQ T&, int);
6475 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006476 if (!HasArithmeticOrEnumeralCandidateType)
6477 return;
6478
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006479 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6480 Arith < NumArithmeticTypes; ++Arith) {
6481 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006482 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006483 VisibleTypeConversionsQuals.hasVolatile());
6484 }
6485 }
6486
6487 // C++ [over.built]p5:
6488 //
6489 // For every pair (T, VQ), where T is a cv-qualified or
6490 // cv-unqualified object type, and VQ is either volatile or
6491 // empty, there exist candidate operator functions of the form
6492 //
6493 // T*VQ& operator++(T*VQ&);
6494 // T*VQ& operator--(T*VQ&);
6495 // T* operator++(T*VQ&, int);
6496 // T* operator--(T*VQ&, int);
6497 void addPlusPlusMinusMinusPointerOverloads() {
6498 for (BuiltinCandidateTypeSet::iterator
6499 Ptr = CandidateTypes[0].pointer_begin(),
6500 PtrEnd = CandidateTypes[0].pointer_end();
6501 Ptr != PtrEnd; ++Ptr) {
6502 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006503 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006504 continue;
6505
6506 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6507 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6508 VisibleTypeConversionsQuals.hasVolatile()));
6509 }
6510 }
6511
6512 // C++ [over.built]p6:
6513 // For every cv-qualified or cv-unqualified object type T, there
6514 // exist candidate operator functions of the form
6515 //
6516 // T& operator*(T*);
6517 //
6518 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006520 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006521 // T& operator*(T*);
6522 void addUnaryStarPointerOverloads() {
6523 for (BuiltinCandidateTypeSet::iterator
6524 Ptr = CandidateTypes[0].pointer_begin(),
6525 PtrEnd = CandidateTypes[0].pointer_end();
6526 Ptr != PtrEnd; ++Ptr) {
6527 QualType ParamTy = *Ptr;
6528 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006529 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6530 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006531
Douglas Gregor02824322011-01-26 19:30:28 +00006532 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6533 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6534 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006536 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6537 &ParamTy, Args, 1, CandidateSet);
6538 }
6539 }
6540
6541 // C++ [over.built]p9:
6542 // For every promoted arithmetic type T, there exist candidate
6543 // operator functions of the form
6544 //
6545 // T operator+(T);
6546 // T operator-(T);
6547 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006548 if (!HasArithmeticOrEnumeralCandidateType)
6549 return;
6550
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006551 for (unsigned Arith = FirstPromotedArithmeticType;
6552 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006553 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006554 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6555 }
6556
6557 // Extension: We also add these operators for vector types.
6558 for (BuiltinCandidateTypeSet::iterator
6559 Vec = CandidateTypes[0].vector_begin(),
6560 VecEnd = CandidateTypes[0].vector_end();
6561 Vec != VecEnd; ++Vec) {
6562 QualType VecTy = *Vec;
6563 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6564 }
6565 }
6566
6567 // C++ [over.built]p8:
6568 // For every type T, there exist candidate operator functions of
6569 // the form
6570 //
6571 // T* operator+(T*);
6572 void addUnaryPlusPointerOverloads() {
6573 for (BuiltinCandidateTypeSet::iterator
6574 Ptr = CandidateTypes[0].pointer_begin(),
6575 PtrEnd = CandidateTypes[0].pointer_end();
6576 Ptr != PtrEnd; ++Ptr) {
6577 QualType ParamTy = *Ptr;
6578 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6579 }
6580 }
6581
6582 // C++ [over.built]p10:
6583 // For every promoted integral type T, there exist candidate
6584 // operator functions of the form
6585 //
6586 // T operator~(T);
6587 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006588 if (!HasArithmeticOrEnumeralCandidateType)
6589 return;
6590
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006591 for (unsigned Int = FirstPromotedIntegralType;
6592 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006593 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006594 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6595 }
6596
6597 // Extension: We also add this operator for vector types.
6598 for (BuiltinCandidateTypeSet::iterator
6599 Vec = CandidateTypes[0].vector_begin(),
6600 VecEnd = CandidateTypes[0].vector_end();
6601 Vec != VecEnd; ++Vec) {
6602 QualType VecTy = *Vec;
6603 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6604 }
6605 }
6606
6607 // C++ [over.match.oper]p16:
6608 // For every pointer to member type T, there exist candidate operator
6609 // functions of the form
6610 //
6611 // bool operator==(T,T);
6612 // bool operator!=(T,T);
6613 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6614 /// Set of (canonical) types that we've already handled.
6615 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6616
6617 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6618 for (BuiltinCandidateTypeSet::iterator
6619 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6620 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6621 MemPtr != MemPtrEnd;
6622 ++MemPtr) {
6623 // Don't add the same builtin candidate twice.
6624 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6625 continue;
6626
6627 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6628 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6629 CandidateSet);
6630 }
6631 }
6632 }
6633
6634 // C++ [over.built]p15:
6635 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006636 // For every T, where T is an enumeration type, a pointer type, or
6637 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006638 //
6639 // bool operator<(T, T);
6640 // bool operator>(T, T);
6641 // bool operator<=(T, T);
6642 // bool operator>=(T, T);
6643 // bool operator==(T, T);
6644 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006645 void addRelationalPointerOrEnumeralOverloads() {
6646 // C++ [over.built]p1:
6647 // If there is a user-written candidate with the same name and parameter
6648 // types as a built-in candidate operator function, the built-in operator
6649 // function is hidden and is not included in the set of candidate
6650 // functions.
6651 //
6652 // The text is actually in a note, but if we don't implement it then we end
6653 // up with ambiguities when the user provides an overloaded operator for
6654 // an enumeration type. Note that only enumeration types have this problem,
6655 // so we track which enumeration types we've seen operators for. Also, the
6656 // only other overloaded operator with enumeration argumenst, operator=,
6657 // cannot be overloaded for enumeration types, so this is the only place
6658 // where we must suppress candidates like this.
6659 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6660 UserDefinedBinaryOperators;
6661
6662 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6663 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6664 CandidateTypes[ArgIdx].enumeration_end()) {
6665 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6666 CEnd = CandidateSet.end();
6667 C != CEnd; ++C) {
6668 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6669 continue;
6670
6671 QualType FirstParamType =
6672 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6673 QualType SecondParamType =
6674 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6675
6676 // Skip if either parameter isn't of enumeral type.
6677 if (!FirstParamType->isEnumeralType() ||
6678 !SecondParamType->isEnumeralType())
6679 continue;
6680
6681 // Add this operator to the set of known user-defined operators.
6682 UserDefinedBinaryOperators.insert(
6683 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6684 S.Context.getCanonicalType(SecondParamType)));
6685 }
6686 }
6687 }
6688
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006689 /// Set of (canonical) types that we've already handled.
6690 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6691
6692 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6693 for (BuiltinCandidateTypeSet::iterator
6694 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6695 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6696 Ptr != PtrEnd; ++Ptr) {
6697 // Don't add the same builtin candidate twice.
6698 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6699 continue;
6700
6701 QualType ParamTypes[2] = { *Ptr, *Ptr };
6702 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6703 CandidateSet);
6704 }
6705 for (BuiltinCandidateTypeSet::iterator
6706 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6707 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6708 Enum != EnumEnd; ++Enum) {
6709 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6710
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006711 // Don't add the same builtin candidate twice, or if a user defined
6712 // candidate exists.
6713 if (!AddedTypes.insert(CanonType) ||
6714 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6715 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006716 continue;
6717
6718 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006719 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6720 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006721 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006722
6723 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6724 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6725 if (AddedTypes.insert(NullPtrTy) &&
6726 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6727 NullPtrTy))) {
6728 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6729 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6730 CandidateSet);
6731 }
6732 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006733 }
6734 }
6735
6736 // C++ [over.built]p13:
6737 //
6738 // For every cv-qualified or cv-unqualified object type T
6739 // there exist candidate operator functions of the form
6740 //
6741 // T* operator+(T*, ptrdiff_t);
6742 // T& operator[](T*, ptrdiff_t); [BELOW]
6743 // T* operator-(T*, ptrdiff_t);
6744 // T* operator+(ptrdiff_t, T*);
6745 // T& operator[](ptrdiff_t, T*); [BELOW]
6746 //
6747 // C++ [over.built]p14:
6748 //
6749 // For every T, where T is a pointer to object type, there
6750 // exist candidate operator functions of the form
6751 //
6752 // ptrdiff_t operator-(T, T);
6753 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6754 /// Set of (canonical) types that we've already handled.
6755 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6756
6757 for (int Arg = 0; Arg < 2; ++Arg) {
6758 QualType AsymetricParamTypes[2] = {
6759 S.Context.getPointerDiffType(),
6760 S.Context.getPointerDiffType(),
6761 };
6762 for (BuiltinCandidateTypeSet::iterator
6763 Ptr = CandidateTypes[Arg].pointer_begin(),
6764 PtrEnd = CandidateTypes[Arg].pointer_end();
6765 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006766 QualType PointeeTy = (*Ptr)->getPointeeType();
6767 if (!PointeeTy->isObjectType())
6768 continue;
6769
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006770 AsymetricParamTypes[Arg] = *Ptr;
6771 if (Arg == 0 || Op == OO_Plus) {
6772 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6773 // T* operator+(ptrdiff_t, T*);
6774 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6775 CandidateSet);
6776 }
6777 if (Op == OO_Minus) {
6778 // ptrdiff_t operator-(T, T);
6779 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6780 continue;
6781
6782 QualType ParamTypes[2] = { *Ptr, *Ptr };
6783 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6784 Args, 2, CandidateSet);
6785 }
6786 }
6787 }
6788 }
6789
6790 // C++ [over.built]p12:
6791 //
6792 // For every pair of promoted arithmetic types L and R, there
6793 // exist candidate operator functions of the form
6794 //
6795 // LR operator*(L, R);
6796 // LR operator/(L, R);
6797 // LR operator+(L, R);
6798 // LR operator-(L, R);
6799 // bool operator<(L, R);
6800 // bool operator>(L, R);
6801 // bool operator<=(L, R);
6802 // bool operator>=(L, R);
6803 // bool operator==(L, R);
6804 // bool operator!=(L, R);
6805 //
6806 // where LR is the result of the usual arithmetic conversions
6807 // between types L and R.
6808 //
6809 // C++ [over.built]p24:
6810 //
6811 // For every pair of promoted arithmetic types L and R, there exist
6812 // candidate operator functions of the form
6813 //
6814 // LR operator?(bool, L, R);
6815 //
6816 // where LR is the result of the usual arithmetic conversions
6817 // between types L and R.
6818 // Our candidates ignore the first parameter.
6819 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006820 if (!HasArithmeticOrEnumeralCandidateType)
6821 return;
6822
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006823 for (unsigned Left = FirstPromotedArithmeticType;
6824 Left < LastPromotedArithmeticType; ++Left) {
6825 for (unsigned Right = FirstPromotedArithmeticType;
6826 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006827 QualType LandR[2] = { getArithmeticType(Left),
6828 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006829 QualType Result =
6830 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006831 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006832 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6833 }
6834 }
6835
6836 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6837 // conditional operator for vector types.
6838 for (BuiltinCandidateTypeSet::iterator
6839 Vec1 = CandidateTypes[0].vector_begin(),
6840 Vec1End = CandidateTypes[0].vector_end();
6841 Vec1 != Vec1End; ++Vec1) {
6842 for (BuiltinCandidateTypeSet::iterator
6843 Vec2 = CandidateTypes[1].vector_begin(),
6844 Vec2End = CandidateTypes[1].vector_end();
6845 Vec2 != Vec2End; ++Vec2) {
6846 QualType LandR[2] = { *Vec1, *Vec2 };
6847 QualType Result = S.Context.BoolTy;
6848 if (!isComparison) {
6849 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6850 Result = *Vec1;
6851 else
6852 Result = *Vec2;
6853 }
6854
6855 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6856 }
6857 }
6858 }
6859
6860 // C++ [over.built]p17:
6861 //
6862 // For every pair of promoted integral types L and R, there
6863 // exist candidate operator functions of the form
6864 //
6865 // LR operator%(L, R);
6866 // LR operator&(L, R);
6867 // LR operator^(L, R);
6868 // LR operator|(L, R);
6869 // L operator<<(L, R);
6870 // L operator>>(L, R);
6871 //
6872 // where LR is the result of the usual arithmetic conversions
6873 // between types L and R.
6874 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006875 if (!HasArithmeticOrEnumeralCandidateType)
6876 return;
6877
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006878 for (unsigned Left = FirstPromotedIntegralType;
6879 Left < LastPromotedIntegralType; ++Left) {
6880 for (unsigned Right = FirstPromotedIntegralType;
6881 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006882 QualType LandR[2] = { getArithmeticType(Left),
6883 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006884 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6885 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006886 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006887 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6888 }
6889 }
6890 }
6891
6892 // C++ [over.built]p20:
6893 //
6894 // For every pair (T, VQ), where T is an enumeration or
6895 // pointer to member type and VQ is either volatile or
6896 // empty, there exist candidate operator functions of the form
6897 //
6898 // VQ T& operator=(VQ T&, T);
6899 void addAssignmentMemberPointerOrEnumeralOverloads() {
6900 /// Set of (canonical) types that we've already handled.
6901 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6902
6903 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6904 for (BuiltinCandidateTypeSet::iterator
6905 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6906 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6907 Enum != EnumEnd; ++Enum) {
6908 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6909 continue;
6910
6911 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6912 CandidateSet);
6913 }
6914
6915 for (BuiltinCandidateTypeSet::iterator
6916 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6917 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6918 MemPtr != MemPtrEnd; ++MemPtr) {
6919 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6920 continue;
6921
6922 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6923 CandidateSet);
6924 }
6925 }
6926 }
6927
6928 // C++ [over.built]p19:
6929 //
6930 // For every pair (T, VQ), where T is any type and VQ is either
6931 // volatile or empty, there exist candidate operator functions
6932 // of the form
6933 //
6934 // T*VQ& operator=(T*VQ&, T*);
6935 //
6936 // C++ [over.built]p21:
6937 //
6938 // For every pair (T, VQ), where T is a cv-qualified or
6939 // cv-unqualified object type and VQ is either volatile or
6940 // empty, there exist candidate operator functions of the form
6941 //
6942 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6943 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6944 void addAssignmentPointerOverloads(bool isEqualOp) {
6945 /// Set of (canonical) types that we've already handled.
6946 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6947
6948 for (BuiltinCandidateTypeSet::iterator
6949 Ptr = CandidateTypes[0].pointer_begin(),
6950 PtrEnd = CandidateTypes[0].pointer_end();
6951 Ptr != PtrEnd; ++Ptr) {
6952 // If this is operator=, keep track of the builtin candidates we added.
6953 if (isEqualOp)
6954 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006955 else if (!(*Ptr)->getPointeeType()->isObjectType())
6956 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006957
6958 // non-volatile version
6959 QualType ParamTypes[2] = {
6960 S.Context.getLValueReferenceType(*Ptr),
6961 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6962 };
6963 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6964 /*IsAssigmentOperator=*/ isEqualOp);
6965
6966 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6967 VisibleTypeConversionsQuals.hasVolatile()) {
6968 // volatile version
6969 ParamTypes[0] =
6970 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6971 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6972 /*IsAssigmentOperator=*/isEqualOp);
6973 }
6974 }
6975
6976 if (isEqualOp) {
6977 for (BuiltinCandidateTypeSet::iterator
6978 Ptr = CandidateTypes[1].pointer_begin(),
6979 PtrEnd = CandidateTypes[1].pointer_end();
6980 Ptr != PtrEnd; ++Ptr) {
6981 // Make sure we don't add the same candidate twice.
6982 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6983 continue;
6984
Chandler Carruth8e543b32010-12-12 08:17:55 +00006985 QualType ParamTypes[2] = {
6986 S.Context.getLValueReferenceType(*Ptr),
6987 *Ptr,
6988 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006989
6990 // non-volatile version
6991 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6992 /*IsAssigmentOperator=*/true);
6993
6994 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6995 VisibleTypeConversionsQuals.hasVolatile()) {
6996 // volatile version
6997 ParamTypes[0] =
6998 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006999 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7000 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007001 }
7002 }
7003 }
7004 }
7005
7006 // C++ [over.built]p18:
7007 //
7008 // For every triple (L, VQ, R), where L is an arithmetic type,
7009 // VQ is either volatile or empty, and R is a promoted
7010 // arithmetic type, there exist candidate operator functions of
7011 // the form
7012 //
7013 // VQ L& operator=(VQ L&, R);
7014 // VQ L& operator*=(VQ L&, R);
7015 // VQ L& operator/=(VQ L&, R);
7016 // VQ L& operator+=(VQ L&, R);
7017 // VQ L& operator-=(VQ L&, R);
7018 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007019 if (!HasArithmeticOrEnumeralCandidateType)
7020 return;
7021
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007022 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7023 for (unsigned Right = FirstPromotedArithmeticType;
7024 Right < LastPromotedArithmeticType; ++Right) {
7025 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007026 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007027
7028 // Add this built-in operator as a candidate (VQ is empty).
7029 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007030 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007031 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7032 /*IsAssigmentOperator=*/isEqualOp);
7033
7034 // Add this built-in operator as a candidate (VQ is 'volatile').
7035 if (VisibleTypeConversionsQuals.hasVolatile()) {
7036 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007037 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007038 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007039 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7040 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007041 /*IsAssigmentOperator=*/isEqualOp);
7042 }
7043 }
7044 }
7045
7046 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7047 for (BuiltinCandidateTypeSet::iterator
7048 Vec1 = CandidateTypes[0].vector_begin(),
7049 Vec1End = CandidateTypes[0].vector_end();
7050 Vec1 != Vec1End; ++Vec1) {
7051 for (BuiltinCandidateTypeSet::iterator
7052 Vec2 = CandidateTypes[1].vector_begin(),
7053 Vec2End = CandidateTypes[1].vector_end();
7054 Vec2 != Vec2End; ++Vec2) {
7055 QualType ParamTypes[2];
7056 ParamTypes[1] = *Vec2;
7057 // Add this built-in operator as a candidate (VQ is empty).
7058 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7059 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7060 /*IsAssigmentOperator=*/isEqualOp);
7061
7062 // Add this built-in operator as a candidate (VQ is 'volatile').
7063 if (VisibleTypeConversionsQuals.hasVolatile()) {
7064 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7065 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007066 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7067 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007068 /*IsAssigmentOperator=*/isEqualOp);
7069 }
7070 }
7071 }
7072 }
7073
7074 // C++ [over.built]p22:
7075 //
7076 // For every triple (L, VQ, R), where L is an integral type, VQ
7077 // is either volatile or empty, and R is a promoted integral
7078 // type, there exist candidate operator functions of the form
7079 //
7080 // VQ L& operator%=(VQ L&, R);
7081 // VQ L& operator<<=(VQ L&, R);
7082 // VQ L& operator>>=(VQ L&, R);
7083 // VQ L& operator&=(VQ L&, R);
7084 // VQ L& operator^=(VQ L&, R);
7085 // VQ L& operator|=(VQ L&, R);
7086 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007087 if (!HasArithmeticOrEnumeralCandidateType)
7088 return;
7089
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007090 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7091 for (unsigned Right = FirstPromotedIntegralType;
7092 Right < LastPromotedIntegralType; ++Right) {
7093 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007094 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007095
7096 // Add this built-in operator as a candidate (VQ is empty).
7097 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007098 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7100 if (VisibleTypeConversionsQuals.hasVolatile()) {
7101 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007102 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007103 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7104 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7105 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7106 CandidateSet);
7107 }
7108 }
7109 }
7110 }
7111
7112 // C++ [over.operator]p23:
7113 //
7114 // There also exist candidate operator functions of the form
7115 //
7116 // bool operator!(bool);
7117 // bool operator&&(bool, bool);
7118 // bool operator||(bool, bool);
7119 void addExclaimOverload() {
7120 QualType ParamTy = S.Context.BoolTy;
7121 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7122 /*IsAssignmentOperator=*/false,
7123 /*NumContextualBoolArguments=*/1);
7124 }
7125 void addAmpAmpOrPipePipeOverload() {
7126 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7127 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7128 /*IsAssignmentOperator=*/false,
7129 /*NumContextualBoolArguments=*/2);
7130 }
7131
7132 // C++ [over.built]p13:
7133 //
7134 // For every cv-qualified or cv-unqualified object type T there
7135 // exist candidate operator functions of the form
7136 //
7137 // T* operator+(T*, ptrdiff_t); [ABOVE]
7138 // T& operator[](T*, ptrdiff_t);
7139 // T* operator-(T*, ptrdiff_t); [ABOVE]
7140 // T* operator+(ptrdiff_t, T*); [ABOVE]
7141 // T& operator[](ptrdiff_t, T*);
7142 void addSubscriptOverloads() {
7143 for (BuiltinCandidateTypeSet::iterator
7144 Ptr = CandidateTypes[0].pointer_begin(),
7145 PtrEnd = CandidateTypes[0].pointer_end();
7146 Ptr != PtrEnd; ++Ptr) {
7147 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7148 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007149 if (!PointeeType->isObjectType())
7150 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007151
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007152 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7153
7154 // T& operator[](T*, ptrdiff_t)
7155 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7156 }
7157
7158 for (BuiltinCandidateTypeSet::iterator
7159 Ptr = CandidateTypes[1].pointer_begin(),
7160 PtrEnd = CandidateTypes[1].pointer_end();
7161 Ptr != PtrEnd; ++Ptr) {
7162 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7163 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007164 if (!PointeeType->isObjectType())
7165 continue;
7166
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007167 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7168
7169 // T& operator[](ptrdiff_t, T*)
7170 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7171 }
7172 }
7173
7174 // C++ [over.built]p11:
7175 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7176 // C1 is the same type as C2 or is a derived class of C2, T is an object
7177 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7178 // there exist candidate operator functions of the form
7179 //
7180 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7181 //
7182 // where CV12 is the union of CV1 and CV2.
7183 void addArrowStarOverloads() {
7184 for (BuiltinCandidateTypeSet::iterator
7185 Ptr = CandidateTypes[0].pointer_begin(),
7186 PtrEnd = CandidateTypes[0].pointer_end();
7187 Ptr != PtrEnd; ++Ptr) {
7188 QualType C1Ty = (*Ptr);
7189 QualType C1;
7190 QualifierCollector Q1;
7191 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7192 if (!isa<RecordType>(C1))
7193 continue;
7194 // heuristic to reduce number of builtin candidates in the set.
7195 // Add volatile/restrict version only if there are conversions to a
7196 // volatile/restrict type.
7197 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7198 continue;
7199 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7200 continue;
7201 for (BuiltinCandidateTypeSet::iterator
7202 MemPtr = CandidateTypes[1].member_pointer_begin(),
7203 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7204 MemPtr != MemPtrEnd; ++MemPtr) {
7205 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7206 QualType C2 = QualType(mptr->getClass(), 0);
7207 C2 = C2.getUnqualifiedType();
7208 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7209 break;
7210 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7211 // build CV12 T&
7212 QualType T = mptr->getPointeeType();
7213 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7214 T.isVolatileQualified())
7215 continue;
7216 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7217 T.isRestrictQualified())
7218 continue;
7219 T = Q1.apply(S.Context, T);
7220 QualType ResultTy = S.Context.getLValueReferenceType(T);
7221 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7222 }
7223 }
7224 }
7225
7226 // Note that we don't consider the first argument, since it has been
7227 // contextually converted to bool long ago. The candidates below are
7228 // therefore added as binary.
7229 //
7230 // C++ [over.built]p25:
7231 // For every type T, where T is a pointer, pointer-to-member, or scoped
7232 // enumeration type, there exist candidate operator functions of the form
7233 //
7234 // T operator?(bool, T, T);
7235 //
7236 void addConditionalOperatorOverloads() {
7237 /// Set of (canonical) types that we've already handled.
7238 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7239
7240 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7241 for (BuiltinCandidateTypeSet::iterator
7242 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7243 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7244 Ptr != PtrEnd; ++Ptr) {
7245 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7246 continue;
7247
7248 QualType ParamTypes[2] = { *Ptr, *Ptr };
7249 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7250 }
7251
7252 for (BuiltinCandidateTypeSet::iterator
7253 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7254 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7255 MemPtr != MemPtrEnd; ++MemPtr) {
7256 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7257 continue;
7258
7259 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7260 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7261 }
7262
David Blaikiebbafb8a2012-03-11 07:00:24 +00007263 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007264 for (BuiltinCandidateTypeSet::iterator
7265 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7266 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7267 Enum != EnumEnd; ++Enum) {
7268 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7269 continue;
7270
7271 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7272 continue;
7273
7274 QualType ParamTypes[2] = { *Enum, *Enum };
7275 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7276 }
7277 }
7278 }
7279 }
7280};
7281
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007282} // end anonymous namespace
7283
7284/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7285/// operator overloads to the candidate set (C++ [over.built]), based
7286/// on the operator @p Op and the arguments given. For example, if the
7287/// operator is a binary '+', this routine might add "int
7288/// operator+(int, int)" to cover integer addition.
7289void
7290Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7291 SourceLocation OpLoc,
7292 Expr **Args, unsigned NumArgs,
7293 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007294 // Find all of the types that the arguments can convert to, but only
7295 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007296 // that make use of these types. Also record whether we encounter non-record
7297 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007298 Qualifiers VisibleTypeConversionsQuals;
7299 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007300 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7301 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007302
7303 bool HasNonRecordCandidateType = false;
7304 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007305 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007306 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7307 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7308 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7309 OpLoc,
7310 true,
7311 (Op == OO_Exclaim ||
7312 Op == OO_AmpAmp ||
7313 Op == OO_PipePipe),
7314 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007315 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7316 CandidateTypes[ArgIdx].hasNonRecordTypes();
7317 HasArithmeticOrEnumeralCandidateType =
7318 HasArithmeticOrEnumeralCandidateType ||
7319 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007320 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007321
Chandler Carruth00a38332010-12-13 01:44:01 +00007322 // Exit early when no non-record types have been added to the candidate set
7323 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007324 //
7325 // We can't exit early for !, ||, or &&, since there we have always have
7326 // 'bool' overloads.
7327 if (!HasNonRecordCandidateType &&
7328 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007329 return;
7330
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007331 // Setup an object to manage the common state for building overloads.
7332 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7333 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007334 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007335 CandidateTypes, CandidateSet);
7336
7337 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007338 switch (Op) {
7339 case OO_None:
7340 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007341 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007342
Chandler Carruth5184de02010-12-12 08:51:33 +00007343 case OO_New:
7344 case OO_Delete:
7345 case OO_Array_New:
7346 case OO_Array_Delete:
7347 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007348 llvm_unreachable(
7349 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007350
7351 case OO_Comma:
7352 case OO_Arrow:
7353 // C++ [over.match.oper]p3:
7354 // -- For the operator ',', the unary operator '&', or the
7355 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007356 break;
7357
7358 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007359 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007360 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007361 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007362
7363 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007364 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007365 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007366 } else {
7367 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7368 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7369 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007370 break;
7371
Chandler Carruth5184de02010-12-12 08:51:33 +00007372 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007373 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007374 OpBuilder.addUnaryStarPointerOverloads();
7375 else
7376 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7377 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007378
Chandler Carruth5184de02010-12-12 08:51:33 +00007379 case OO_Slash:
7380 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007381 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007382
7383 case OO_PlusPlus:
7384 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007385 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7386 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007387 break;
7388
Douglas Gregor84605ae2009-08-24 13:43:27 +00007389 case OO_EqualEqual:
7390 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007391 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007392 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007393
Douglas Gregora11693b2008-11-12 17:17:38 +00007394 case OO_Less:
7395 case OO_Greater:
7396 case OO_LessEqual:
7397 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007398 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007399 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7400 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007401
Douglas Gregora11693b2008-11-12 17:17:38 +00007402 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007403 case OO_Caret:
7404 case OO_Pipe:
7405 case OO_LessLess:
7406 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007407 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007408 break;
7409
Chandler Carruth5184de02010-12-12 08:51:33 +00007410 case OO_Amp: // '&' is either unary or binary
7411 if (NumArgs == 1)
7412 // C++ [over.match.oper]p3:
7413 // -- For the operator ',', the unary operator '&', or the
7414 // operator '->', the built-in candidates set is empty.
7415 break;
7416
7417 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7418 break;
7419
7420 case OO_Tilde:
7421 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7422 break;
7423
Douglas Gregora11693b2008-11-12 17:17:38 +00007424 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007425 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007426 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007427
7428 case OO_PlusEqual:
7429 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007430 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007431 // Fall through.
7432
7433 case OO_StarEqual:
7434 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007435 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007436 break;
7437
7438 case OO_PercentEqual:
7439 case OO_LessLessEqual:
7440 case OO_GreaterGreaterEqual:
7441 case OO_AmpEqual:
7442 case OO_CaretEqual:
7443 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007444 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007445 break;
7446
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007447 case OO_Exclaim:
7448 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007449 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007450
Douglas Gregora11693b2008-11-12 17:17:38 +00007451 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007452 case OO_PipePipe:
7453 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007454 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007455
7456 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007457 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007458 break;
7459
7460 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007461 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007462 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007463
7464 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007465 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007466 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7467 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007468 }
7469}
7470
Douglas Gregore254f902009-02-04 00:32:51 +00007471/// \brief Add function candidates found via argument-dependent lookup
7472/// to the set of overloading candidates.
7473///
7474/// This routine performs argument-dependent name lookup based on the
7475/// given function name (which may also be an operator name) and adds
7476/// all of the overload candidates found by ADL to the overload
7477/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007478void
Douglas Gregore254f902009-02-04 00:32:51 +00007479Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007480 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007481 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007482 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007483 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007484 bool PartialOverloading,
7485 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007486 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007487
John McCall91f61fc2010-01-26 06:04:06 +00007488 // FIXME: This approach for uniquing ADL results (and removing
7489 // redundant candidates from the set) relies on pointer-equality,
7490 // which means we need to key off the canonical decl. However,
7491 // always going back to the canonical decl might not get us the
7492 // right set of default arguments. What default arguments are
7493 // we supposed to consider on ADL candidates, anyway?
7494
Douglas Gregorcabea402009-09-22 15:41:20 +00007495 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007496 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007497 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007498
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007499 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007500 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7501 CandEnd = CandidateSet.end();
7502 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007503 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007504 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007505 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007506 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007507 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007508
7509 // For each of the ADL candidates we found, add it to the overload
7510 // set.
John McCall8fe68082010-01-26 07:16:45 +00007511 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007512 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007513 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007514 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007515 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007516
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007517 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7518 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007519 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007520 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007521 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007522 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007523 }
Douglas Gregore254f902009-02-04 00:32:51 +00007524}
7525
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007526/// isBetterOverloadCandidate - Determines whether the first overload
7527/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007528bool
John McCall5c32be02010-08-24 20:38:10 +00007529isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007530 const OverloadCandidate &Cand1,
7531 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007532 SourceLocation Loc,
7533 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007534 // Define viable functions to be better candidates than non-viable
7535 // functions.
7536 if (!Cand2.Viable)
7537 return Cand1.Viable;
7538 else if (!Cand1.Viable)
7539 return false;
7540
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007541 // C++ [over.match.best]p1:
7542 //
7543 // -- if F is a static member function, ICS1(F) is defined such
7544 // that ICS1(F) is neither better nor worse than ICS1(G) for
7545 // any function G, and, symmetrically, ICS1(G) is neither
7546 // better nor worse than ICS1(F).
7547 unsigned StartArg = 0;
7548 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7549 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007550
Douglas Gregord3cb3562009-07-07 23:38:56 +00007551 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007552 // A viable function F1 is defined to be a better function than another
7553 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007554 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007555 unsigned NumArgs = Cand1.NumConversions;
7556 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007557 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007558 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007559 switch (CompareImplicitConversionSequences(S,
7560 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007561 Cand2.Conversions[ArgIdx])) {
7562 case ImplicitConversionSequence::Better:
7563 // Cand1 has a better conversion sequence.
7564 HasBetterConversion = true;
7565 break;
7566
7567 case ImplicitConversionSequence::Worse:
7568 // Cand1 can't be better than Cand2.
7569 return false;
7570
7571 case ImplicitConversionSequence::Indistinguishable:
7572 // Do nothing.
7573 break;
7574 }
7575 }
7576
Mike Stump11289f42009-09-09 15:08:12 +00007577 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007578 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007579 if (HasBetterConversion)
7580 return true;
7581
Mike Stump11289f42009-09-09 15:08:12 +00007582 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007583 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007584 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007585 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7586 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007587
7588 // -- F1 and F2 are function template specializations, and the function
7589 // template for F1 is more specialized than the template for F2
7590 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007591 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007592 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007593 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007594 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007595 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7596 Cand2.Function->getPrimaryTemplate(),
7597 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007598 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007599 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007600 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007601 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007603
Douglas Gregora1f013e2008-11-07 22:36:19 +00007604 // -- the context is an initialization by user-defined conversion
7605 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7606 // from the return type of F1 to the destination type (i.e.,
7607 // the type of the entity being initialized) is a better
7608 // conversion sequence than the standard conversion sequence
7609 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007610 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007611 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007612 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007613 // First check whether we prefer one of the conversion functions over the
7614 // other. This only distinguishes the results in non-standard, extension
7615 // cases such as the conversion from a lambda closure type to a function
7616 // pointer or block.
7617 ImplicitConversionSequence::CompareKind FuncResult
7618 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7619 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7620 return FuncResult;
7621
John McCall5c32be02010-08-24 20:38:10 +00007622 switch (CompareStandardConversionSequences(S,
7623 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007624 Cand2.FinalConversion)) {
7625 case ImplicitConversionSequence::Better:
7626 // Cand1 has a better conversion sequence.
7627 return true;
7628
7629 case ImplicitConversionSequence::Worse:
7630 // Cand1 can't be better than Cand2.
7631 return false;
7632
7633 case ImplicitConversionSequence::Indistinguishable:
7634 // Do nothing
7635 break;
7636 }
7637 }
7638
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007639 return false;
7640}
7641
Mike Stump11289f42009-09-09 15:08:12 +00007642/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007643/// within an overload candidate set.
7644///
7645/// \param CandidateSet the set of candidate functions.
7646///
7647/// \param Loc the location of the function name (or operator symbol) for
7648/// which overload resolution occurs.
7649///
Mike Stump11289f42009-09-09 15:08:12 +00007650/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007651/// function, Best points to the candidate function found.
7652///
7653/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007654OverloadingResult
7655OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007656 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007657 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007658 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007659 Best = end();
7660 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7661 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007662 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007663 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007664 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007665 }
7666
7667 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007668 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007669 return OR_No_Viable_Function;
7670
7671 // Make sure that this function is better than every other viable
7672 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007673 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007674 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007675 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007677 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007678 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007679 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007680 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007681 }
Mike Stump11289f42009-09-09 15:08:12 +00007682
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007683 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007684 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007685 (Best->Function->isDeleted() ||
7686 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007687 return OR_Deleted;
7688
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007689 return OR_Success;
7690}
7691
John McCall53262c92010-01-12 02:15:36 +00007692namespace {
7693
7694enum OverloadCandidateKind {
7695 oc_function,
7696 oc_method,
7697 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007698 oc_function_template,
7699 oc_method_template,
7700 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007701 oc_implicit_default_constructor,
7702 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007703 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007704 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007705 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007706 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007707};
7708
John McCalle1ac8d12010-01-13 00:25:19 +00007709OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7710 FunctionDecl *Fn,
7711 std::string &Description) {
7712 bool isTemplate = false;
7713
7714 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7715 isTemplate = true;
7716 Description = S.getTemplateArgumentBindingsText(
7717 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7718 }
John McCallfd0b2f82010-01-06 09:43:14 +00007719
7720 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007721 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007722 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007723
Sebastian Redl08905022011-02-05 19:23:19 +00007724 if (Ctor->getInheritedConstructor())
7725 return oc_implicit_inherited_constructor;
7726
Alexis Hunt119c10e2011-05-25 23:16:36 +00007727 if (Ctor->isDefaultConstructor())
7728 return oc_implicit_default_constructor;
7729
7730 if (Ctor->isMoveConstructor())
7731 return oc_implicit_move_constructor;
7732
7733 assert(Ctor->isCopyConstructor() &&
7734 "unexpected sort of implicit constructor");
7735 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007736 }
7737
7738 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7739 // This actually gets spelled 'candidate function' for now, but
7740 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007741 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007742 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007743
Alexis Hunt119c10e2011-05-25 23:16:36 +00007744 if (Meth->isMoveAssignmentOperator())
7745 return oc_implicit_move_assignment;
7746
Douglas Gregor12695102012-02-10 08:36:38 +00007747 if (Meth->isCopyAssignmentOperator())
7748 return oc_implicit_copy_assignment;
7749
7750 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7751 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007752 }
7753
John McCalle1ac8d12010-01-13 00:25:19 +00007754 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007755}
7756
Sebastian Redl08905022011-02-05 19:23:19 +00007757void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7758 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7759 if (!Ctor) return;
7760
7761 Ctor = Ctor->getInheritedConstructor();
7762 if (!Ctor) return;
7763
7764 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7765}
7766
John McCall53262c92010-01-12 02:15:36 +00007767} // end anonymous namespace
7768
7769// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007770void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007771 std::string FnDesc;
7772 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007773 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7774 << (unsigned) K << FnDesc;
7775 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7776 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007777 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007778}
7779
Douglas Gregorb491ed32011-02-19 21:32:49 +00007780//Notes the location of all overload candidates designated through
7781// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007782void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007783 assert(OverloadedExpr->getType() == Context.OverloadTy);
7784
7785 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7786 OverloadExpr *OvlExpr = Ovl.Expression;
7787
7788 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7789 IEnd = OvlExpr->decls_end();
7790 I != IEnd; ++I) {
7791 if (FunctionTemplateDecl *FunTmpl =
7792 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007793 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007794 } else if (FunctionDecl *Fun
7795 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007796 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007797 }
7798 }
7799}
7800
John McCall0d1da222010-01-12 00:44:57 +00007801/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7802/// "lead" diagnostic; it will be given two arguments, the source and
7803/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007804void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7805 Sema &S,
7806 SourceLocation CaretLoc,
7807 const PartialDiagnostic &PDiag) const {
7808 S.Diag(CaretLoc, PDiag)
7809 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007810 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007811 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7812 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007813 }
John McCall12f97bc2010-01-08 04:41:39 +00007814}
7815
John McCall0d1da222010-01-12 00:44:57 +00007816namespace {
7817
John McCall6a61b522010-01-13 09:16:55 +00007818void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7819 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7820 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007821 assert(Cand->Function && "for now, candidate must be a function");
7822 FunctionDecl *Fn = Cand->Function;
7823
7824 // There's a conversion slot for the object argument if this is a
7825 // non-constructor method. Note that 'I' corresponds the
7826 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007827 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007828 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007829 if (I == 0)
7830 isObjectArgument = true;
7831 else
7832 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007833 }
7834
John McCalle1ac8d12010-01-13 00:25:19 +00007835 std::string FnDesc;
7836 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7837
John McCall6a61b522010-01-13 09:16:55 +00007838 Expr *FromExpr = Conv.Bad.FromExpr;
7839 QualType FromTy = Conv.Bad.getFromType();
7840 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007841
John McCallfb7ad0f2010-02-02 02:42:52 +00007842 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007843 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007844 Expr *E = FromExpr->IgnoreParens();
7845 if (isa<UnaryOperator>(E))
7846 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007847 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007848
7849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7850 << (unsigned) FnKind << FnDesc
7851 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7852 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007853 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007854 return;
7855 }
7856
John McCall6d174642010-01-23 08:10:49 +00007857 // Do some hand-waving analysis to see if the non-viability is due
7858 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007859 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7860 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7861 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7862 CToTy = RT->getPointeeType();
7863 else {
7864 // TODO: detect and diagnose the full richness of const mismatches.
7865 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7866 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7867 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7868 }
7869
7870 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7871 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00007872 Qualifiers FromQs = CFromTy.getQualifiers();
7873 Qualifiers ToQs = CToTy.getQualifiers();
7874
7875 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7876 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7877 << (unsigned) FnKind << FnDesc
7878 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7879 << FromTy
7880 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7881 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007882 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007883 return;
7884 }
7885
John McCall31168b02011-06-15 23:02:42 +00007886 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007888 << (unsigned) FnKind << FnDesc
7889 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7890 << FromTy
7891 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7892 << (unsigned) isObjectArgument << I+1;
7893 MaybeEmitInheritedConstructorNote(S, Fn);
7894 return;
7895 }
7896
Douglas Gregoraec25842011-04-26 23:16:46 +00007897 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7898 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7899 << (unsigned) FnKind << FnDesc
7900 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7901 << FromTy
7902 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7903 << (unsigned) isObjectArgument << I+1;
7904 MaybeEmitInheritedConstructorNote(S, Fn);
7905 return;
7906 }
7907
John McCall47000992010-01-14 03:28:57 +00007908 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7909 assert(CVR && "unexpected qualifiers mismatch");
7910
7911 if (isObjectArgument) {
7912 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7913 << (unsigned) FnKind << FnDesc
7914 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7915 << FromTy << (CVR - 1);
7916 } else {
7917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7918 << (unsigned) FnKind << FnDesc
7919 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7920 << FromTy << (CVR - 1) << I+1;
7921 }
Sebastian Redl08905022011-02-05 19:23:19 +00007922 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007923 return;
7924 }
7925
Sebastian Redla72462c2011-09-24 17:48:32 +00007926 // Special diagnostic for failure to convert an initializer list, since
7927 // telling the user that it has type void is not useful.
7928 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7929 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7930 << (unsigned) FnKind << FnDesc
7931 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7932 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7933 MaybeEmitInheritedConstructorNote(S, Fn);
7934 return;
7935 }
7936
John McCall6d174642010-01-23 08:10:49 +00007937 // Diagnose references or pointers to incomplete types differently,
7938 // since it's far from impossible that the incompleteness triggered
7939 // the failure.
7940 QualType TempFromTy = FromTy.getNonReferenceType();
7941 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7942 TempFromTy = PTy->getPointeeType();
7943 if (TempFromTy->isIncompleteType()) {
7944 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7945 << (unsigned) FnKind << FnDesc
7946 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7947 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007948 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007949 return;
7950 }
7951
Douglas Gregor56f2e342010-06-30 23:01:39 +00007952 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007953 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007954 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7955 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7956 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7957 FromPtrTy->getPointeeType()) &&
7958 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7959 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007961 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007962 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007963 }
7964 } else if (const ObjCObjectPointerType *FromPtrTy
7965 = FromTy->getAs<ObjCObjectPointerType>()) {
7966 if (const ObjCObjectPointerType *ToPtrTy
7967 = ToTy->getAs<ObjCObjectPointerType>())
7968 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7969 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7970 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7971 FromPtrTy->getPointeeType()) &&
7972 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007973 BaseToDerivedConversion = 2;
7974 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7975 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7976 !FromTy->isIncompleteType() &&
7977 !ToRefTy->getPointeeType()->isIncompleteType() &&
7978 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7979 BaseToDerivedConversion = 3;
7980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007981
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007982 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007983 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007984 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007985 << (unsigned) FnKind << FnDesc
7986 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007987 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007988 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007989 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007990 return;
7991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007992
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007993 if (isa<ObjCObjectPointerType>(CFromTy) &&
7994 isa<PointerType>(CToTy)) {
7995 Qualifiers FromQs = CFromTy.getQualifiers();
7996 Qualifiers ToQs = CToTy.getQualifiers();
7997 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7998 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7999 << (unsigned) FnKind << FnDesc
8000 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8001 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8002 MaybeEmitInheritedConstructorNote(S, Fn);
8003 return;
8004 }
8005 }
8006
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008007 // Emit the generic diagnostic and, optionally, add the hints to it.
8008 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8009 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008010 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008011 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8012 << (unsigned) (Cand->Fix.Kind);
8013
8014 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008015 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8016 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008017 FDiag << *HI;
8018 S.Diag(Fn->getLocation(), FDiag);
8019
Sebastian Redl08905022011-02-05 19:23:19 +00008020 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008021}
8022
8023void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8024 unsigned NumFormalArgs) {
8025 // TODO: treat calls to a missing default constructor as a special case
8026
8027 FunctionDecl *Fn = Cand->Function;
8028 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8029
8030 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008031
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008032 // With invalid overloaded operators, it's possible that we think we
8033 // have an arity mismatch when it fact it looks like we have the
8034 // right number of arguments, because only overloaded operators have
8035 // the weird behavior of overloading member and non-member functions.
8036 // Just don't report anything.
8037 if (Fn->isInvalidDecl() &&
8038 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8039 return;
8040
John McCall6a61b522010-01-13 09:16:55 +00008041 // at least / at most / exactly
8042 unsigned mode, modeCount;
8043 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008044 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8045 (Cand->FailureKind == ovl_fail_bad_deduction &&
8046 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008047 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008048 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008049 mode = 0; // "at least"
8050 else
8051 mode = 2; // "exactly"
8052 modeCount = MinParams;
8053 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008054 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8055 (Cand->FailureKind == ovl_fail_bad_deduction &&
8056 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008057 if (MinParams != FnTy->getNumArgs())
8058 mode = 1; // "at most"
8059 else
8060 mode = 2; // "exactly"
8061 modeCount = FnTy->getNumArgs();
8062 }
8063
8064 std::string Description;
8065 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8066
8067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008068 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00008069 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008070 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008071}
8072
John McCall8b9ed552010-02-01 18:53:26 +00008073/// Diagnose a failed template-argument deduction.
8074void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008075 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008076 FunctionDecl *Fn = Cand->Function; // pattern
8077
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008078 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008079 NamedDecl *ParamD;
8080 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8081 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8082 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008083 switch (Cand->DeductionFailure.Result) {
8084 case Sema::TDK_Success:
8085 llvm_unreachable("TDK_success while diagnosing bad deduction");
8086
8087 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008088 assert(ParamD && "no parameter found for incomplete deduction result");
8089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8090 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008091 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008092 return;
8093 }
8094
John McCall42d7d192010-08-05 09:05:08 +00008095 case Sema::TDK_Underqualified: {
8096 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8097 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8098
8099 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8100
8101 // Param will have been canonicalized, but it should just be a
8102 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008103 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008104 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008105 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008106 assert(S.Context.hasSameType(Param, NonCanonParam));
8107
8108 // Arg has also been canonicalized, but there's nothing we can do
8109 // about that. It also doesn't matter as much, because it won't
8110 // have any template parameters in it (because deduction isn't
8111 // done on dependent types).
8112 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8113
8114 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8115 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008116 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008117 return;
8118 }
8119
8120 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008121 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008122 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008123 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008124 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008125 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008126 which = 1;
8127 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008128 which = 2;
8129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008130
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008131 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008133 << *Cand->DeductionFailure.getFirstArg()
8134 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008135 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008136 return;
8137 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008138
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008139 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008140 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008141 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008142 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008143 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8144 << ParamD->getDeclName();
8145 else {
8146 int index = 0;
8147 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8148 index = TTP->getIndex();
8149 else if (NonTypeTemplateParmDecl *NTTP
8150 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8151 index = NTTP->getIndex();
8152 else
8153 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008154 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008155 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8156 << (index + 1);
8157 }
Sebastian Redl08905022011-02-05 19:23:19 +00008158 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008159 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008160
Douglas Gregor02eb4832010-05-08 18:13:28 +00008161 case Sema::TDK_TooManyArguments:
8162 case Sema::TDK_TooFewArguments:
8163 DiagnoseArityMismatch(S, Cand, NumArgs);
8164 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008165
8166 case Sema::TDK_InstantiationDepth:
8167 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008168 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008169 return;
8170
8171 case Sema::TDK_SubstitutionFailure: {
8172 std::string ArgString;
8173 if (TemplateArgumentList *Args
8174 = Cand->DeductionFailure.getTemplateArgumentList())
8175 ArgString = S.getTemplateArgumentBindingsText(
8176 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8177 *Args);
8178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8179 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00008180 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008181 return;
8182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008183
John McCall8b9ed552010-02-01 18:53:26 +00008184 // TODO: diagnose these individually, then kill off
8185 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008186 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008187 case Sema::TDK_FailedOverloadResolution:
8188 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008189 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008190 return;
8191 }
8192}
8193
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008194/// CUDA: diagnose an invalid call across targets.
8195void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8196 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8197 FunctionDecl *Callee = Cand->Function;
8198
8199 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8200 CalleeTarget = S.IdentifyCUDATarget(Callee);
8201
8202 std::string FnDesc;
8203 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8204
8205 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8206 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8207}
8208
John McCall8b9ed552010-02-01 18:53:26 +00008209/// Generates a 'note' diagnostic for an overload candidate. We've
8210/// already generated a primary error at the call site.
8211///
8212/// It really does need to be a single diagnostic with its caret
8213/// pointed at the candidate declaration. Yes, this creates some
8214/// major challenges of technical writing. Yes, this makes pointing
8215/// out problems with specific arguments quite awkward. It's still
8216/// better than generating twenty screens of text for every failed
8217/// overload.
8218///
8219/// It would be great to be able to express per-candidate problems
8220/// more richly for those diagnostic clients that cared, but we'd
8221/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008222void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008223 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008224 FunctionDecl *Fn = Cand->Function;
8225
John McCall12f97bc2010-01-08 04:41:39 +00008226 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008227 if (Cand->Viable && (Fn->isDeleted() ||
8228 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008229 std::string FnDesc;
8230 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008231
8232 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00008233 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00008234 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008235 return;
John McCall12f97bc2010-01-08 04:41:39 +00008236 }
8237
John McCalle1ac8d12010-01-13 00:25:19 +00008238 // We don't really have anything else to say about viable candidates.
8239 if (Cand->Viable) {
8240 S.NoteOverloadCandidate(Fn);
8241 return;
8242 }
John McCall0d1da222010-01-12 00:44:57 +00008243
John McCall6a61b522010-01-13 09:16:55 +00008244 switch (Cand->FailureKind) {
8245 case ovl_fail_too_many_arguments:
8246 case ovl_fail_too_few_arguments:
8247 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008248
John McCall6a61b522010-01-13 09:16:55 +00008249 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008250 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008251
John McCallfe796dd2010-01-23 05:17:32 +00008252 case ovl_fail_trivial_conversion:
8253 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008254 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008255 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008256
John McCall65eb8792010-02-25 01:37:24 +00008257 case ovl_fail_bad_conversion: {
8258 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008259 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008260 if (Cand->Conversions[I].isBad())
8261 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008262
John McCall6a61b522010-01-13 09:16:55 +00008263 // FIXME: this currently happens when we're called from SemaInit
8264 // when user-conversion overload fails. Figure out how to handle
8265 // those conditions and diagnose them well.
8266 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008267 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008268
8269 case ovl_fail_bad_target:
8270 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008271 }
John McCalld3224162010-01-08 00:58:21 +00008272}
8273
8274void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8275 // Desugar the type of the surrogate down to a function type,
8276 // retaining as many typedefs as possible while still showing
8277 // the function type (and, therefore, its parameter types).
8278 QualType FnType = Cand->Surrogate->getConversionType();
8279 bool isLValueReference = false;
8280 bool isRValueReference = false;
8281 bool isPointer = false;
8282 if (const LValueReferenceType *FnTypeRef =
8283 FnType->getAs<LValueReferenceType>()) {
8284 FnType = FnTypeRef->getPointeeType();
8285 isLValueReference = true;
8286 } else if (const RValueReferenceType *FnTypeRef =
8287 FnType->getAs<RValueReferenceType>()) {
8288 FnType = FnTypeRef->getPointeeType();
8289 isRValueReference = true;
8290 }
8291 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8292 FnType = FnTypePtr->getPointeeType();
8293 isPointer = true;
8294 }
8295 // Desugar down to a function type.
8296 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8297 // Reconstruct the pointer/reference as appropriate.
8298 if (isPointer) FnType = S.Context.getPointerType(FnType);
8299 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8300 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8301
8302 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8303 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008304 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008305}
8306
8307void NoteBuiltinOperatorCandidate(Sema &S,
8308 const char *Opc,
8309 SourceLocation OpLoc,
8310 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008311 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008312 std::string TypeStr("operator");
8313 TypeStr += Opc;
8314 TypeStr += "(";
8315 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008316 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008317 TypeStr += ")";
8318 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8319 } else {
8320 TypeStr += ", ";
8321 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8322 TypeStr += ")";
8323 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8324 }
8325}
8326
8327void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8328 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008329 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008330 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8331 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008332 if (ICS.isBad()) break; // all meaningless after first invalid
8333 if (!ICS.isAmbiguous()) continue;
8334
John McCall5c32be02010-08-24 20:38:10 +00008335 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008336 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008337 }
8338}
8339
John McCall3712d9e2010-01-15 23:32:50 +00008340SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8341 if (Cand->Function)
8342 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008343 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008344 return Cand->Surrogate->getLocation();
8345 return SourceLocation();
8346}
8347
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008348static unsigned
8349RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008350 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008351 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008352 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008353
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008354 case Sema::TDK_Incomplete:
8355 return 1;
8356
8357 case Sema::TDK_Underqualified:
8358 case Sema::TDK_Inconsistent:
8359 return 2;
8360
8361 case Sema::TDK_SubstitutionFailure:
8362 case Sema::TDK_NonDeducedMismatch:
8363 return 3;
8364
8365 case Sema::TDK_InstantiationDepth:
8366 case Sema::TDK_FailedOverloadResolution:
8367 return 4;
8368
8369 case Sema::TDK_InvalidExplicitArguments:
8370 return 5;
8371
8372 case Sema::TDK_TooManyArguments:
8373 case Sema::TDK_TooFewArguments:
8374 return 6;
8375 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008376 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008377}
8378
John McCallad2587a2010-01-12 00:48:53 +00008379struct CompareOverloadCandidatesForDisplay {
8380 Sema &S;
8381 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008382
8383 bool operator()(const OverloadCandidate *L,
8384 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008385 // Fast-path this check.
8386 if (L == R) return false;
8387
John McCall12f97bc2010-01-08 04:41:39 +00008388 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008389 if (L->Viable) {
8390 if (!R->Viable) return true;
8391
8392 // TODO: introduce a tri-valued comparison for overload
8393 // candidates. Would be more worthwhile if we had a sort
8394 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008395 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8396 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008397 } else if (R->Viable)
8398 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008399
John McCall3712d9e2010-01-15 23:32:50 +00008400 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008401
John McCall3712d9e2010-01-15 23:32:50 +00008402 // Criteria by which we can sort non-viable candidates:
8403 if (!L->Viable) {
8404 // 1. Arity mismatches come after other candidates.
8405 if (L->FailureKind == ovl_fail_too_many_arguments ||
8406 L->FailureKind == ovl_fail_too_few_arguments)
8407 return false;
8408 if (R->FailureKind == ovl_fail_too_many_arguments ||
8409 R->FailureKind == ovl_fail_too_few_arguments)
8410 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008411
John McCallfe796dd2010-01-23 05:17:32 +00008412 // 2. Bad conversions come first and are ordered by the number
8413 // of bad conversions and quality of good conversions.
8414 if (L->FailureKind == ovl_fail_bad_conversion) {
8415 if (R->FailureKind != ovl_fail_bad_conversion)
8416 return true;
8417
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008418 // The conversion that can be fixed with a smaller number of changes,
8419 // comes first.
8420 unsigned numLFixes = L->Fix.NumConversionsFixed;
8421 unsigned numRFixes = R->Fix.NumConversionsFixed;
8422 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8423 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008424 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008425 if (numLFixes < numRFixes)
8426 return true;
8427 else
8428 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008429 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008430
John McCallfe796dd2010-01-23 05:17:32 +00008431 // If there's any ordering between the defined conversions...
8432 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008433 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008434
8435 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008436 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008437 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008438 switch (CompareImplicitConversionSequences(S,
8439 L->Conversions[I],
8440 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008441 case ImplicitConversionSequence::Better:
8442 leftBetter++;
8443 break;
8444
8445 case ImplicitConversionSequence::Worse:
8446 leftBetter--;
8447 break;
8448
8449 case ImplicitConversionSequence::Indistinguishable:
8450 break;
8451 }
8452 }
8453 if (leftBetter > 0) return true;
8454 if (leftBetter < 0) return false;
8455
8456 } else if (R->FailureKind == ovl_fail_bad_conversion)
8457 return false;
8458
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008459 if (L->FailureKind == ovl_fail_bad_deduction) {
8460 if (R->FailureKind != ovl_fail_bad_deduction)
8461 return true;
8462
8463 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8464 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008465 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008466 } else if (R->FailureKind == ovl_fail_bad_deduction)
8467 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008468
John McCall3712d9e2010-01-15 23:32:50 +00008469 // TODO: others?
8470 }
8471
8472 // Sort everything else by location.
8473 SourceLocation LLoc = GetLocationForCandidate(L);
8474 SourceLocation RLoc = GetLocationForCandidate(R);
8475
8476 // Put candidates without locations (e.g. builtins) at the end.
8477 if (LLoc.isInvalid()) return false;
8478 if (RLoc.isInvalid()) return true;
8479
8480 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008481 }
8482};
8483
John McCallfe796dd2010-01-23 05:17:32 +00008484/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008485/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008486void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008487 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008488 assert(!Cand->Viable);
8489
8490 // Don't do anything on failures other than bad conversion.
8491 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8492
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008493 // We only want the FixIts if all the arguments can be corrected.
8494 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008495 // Use a implicit copy initialization to check conversion fixes.
8496 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008497
John McCallfe796dd2010-01-23 05:17:32 +00008498 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008499 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008500 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008501 while (true) {
8502 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8503 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008504 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008505 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008506 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008507 }
John McCallfe796dd2010-01-23 05:17:32 +00008508 }
8509
8510 if (ConvIdx == ConvCount)
8511 return;
8512
John McCall65eb8792010-02-25 01:37:24 +00008513 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8514 "remaining conversion is initialized?");
8515
Douglas Gregoradc7a702010-04-16 17:45:54 +00008516 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008517 // operation somehow.
8518 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008519
8520 const FunctionProtoType* Proto;
8521 unsigned ArgIdx = ConvIdx;
8522
8523 if (Cand->IsSurrogate) {
8524 QualType ConvType
8525 = Cand->Surrogate->getConversionType().getNonReferenceType();
8526 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8527 ConvType = ConvPtrType->getPointeeType();
8528 Proto = ConvType->getAs<FunctionProtoType>();
8529 ArgIdx--;
8530 } else if (Cand->Function) {
8531 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8532 if (isa<CXXMethodDecl>(Cand->Function) &&
8533 !isa<CXXConstructorDecl>(Cand->Function))
8534 ArgIdx--;
8535 } else {
8536 // Builtin binary operator with a bad first conversion.
8537 assert(ConvCount <= 3);
8538 for (; ConvIdx != ConvCount; ++ConvIdx)
8539 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008540 = TryCopyInitialization(S, Args[ConvIdx],
8541 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008542 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008543 /*InOverloadResolution*/ true,
8544 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008545 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008546 return;
8547 }
8548
8549 // Fill in the rest of the conversions.
8550 unsigned NumArgsInProto = Proto->getNumArgs();
8551 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008552 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008553 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008554 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008555 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008556 /*InOverloadResolution=*/true,
8557 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008558 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008559 // Store the FixIt in the candidate if it exists.
8560 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008561 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008562 }
John McCallfe796dd2010-01-23 05:17:32 +00008563 else
8564 Cand->Conversions[ConvIdx].setEllipsis();
8565 }
8566}
8567
John McCalld3224162010-01-08 00:58:21 +00008568} // end anonymous namespace
8569
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008570/// PrintOverloadCandidates - When overload resolution fails, prints
8571/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008572/// set.
John McCall5c32be02010-08-24 20:38:10 +00008573void OverloadCandidateSet::NoteCandidates(Sema &S,
8574 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008575 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008576 const char *Opc,
8577 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008578 // Sort the candidates by viability and position. Sorting directly would
8579 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008580 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008581 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8582 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008583 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008584 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008585 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008586 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008587 if (Cand->Function || Cand->IsSurrogate)
8588 Cands.push_back(Cand);
8589 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8590 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008591 }
8592 }
8593
John McCallad2587a2010-01-12 00:48:53 +00008594 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008595 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008596
John McCall0d1da222010-01-12 00:44:57 +00008597 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008598
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008599 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008600 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8601 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008602 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008603 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8604 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008605
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008606 // Set an arbitrary limit on the number of candidate functions we'll spam
8607 // the user with. FIXME: This limit should depend on details of the
8608 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008609 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008610 break;
8611 }
8612 ++CandsShown;
8613
John McCalld3224162010-01-08 00:58:21 +00008614 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008615 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008616 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008617 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008618 else {
8619 assert(Cand->Viable &&
8620 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008621 // Generally we only see ambiguities including viable builtin
8622 // operators if overload resolution got screwed up by an
8623 // ambiguous user-defined conversion.
8624 //
8625 // FIXME: It's quite possible for different conversions to see
8626 // different ambiguities, though.
8627 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008628 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008629 ReportedAmbiguousConversions = true;
8630 }
John McCalld3224162010-01-08 00:58:21 +00008631
John McCall0d1da222010-01-12 00:44:57 +00008632 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008633 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008634 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008635 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008636
8637 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008638 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008639}
8640
Douglas Gregorb491ed32011-02-19 21:32:49 +00008641// [PossiblyAFunctionType] --> [Return]
8642// NonFunctionType --> NonFunctionType
8643// R (A) --> R(A)
8644// R (*)(A) --> R (A)
8645// R (&)(A) --> R (A)
8646// R (S::*)(A) --> R (A)
8647QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8648 QualType Ret = PossiblyAFunctionType;
8649 if (const PointerType *ToTypePtr =
8650 PossiblyAFunctionType->getAs<PointerType>())
8651 Ret = ToTypePtr->getPointeeType();
8652 else if (const ReferenceType *ToTypeRef =
8653 PossiblyAFunctionType->getAs<ReferenceType>())
8654 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008655 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008656 PossiblyAFunctionType->getAs<MemberPointerType>())
8657 Ret = MemTypePtr->getPointeeType();
8658 Ret =
8659 Context.getCanonicalType(Ret).getUnqualifiedType();
8660 return Ret;
8661}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008662
Douglas Gregorb491ed32011-02-19 21:32:49 +00008663// A helper class to help with address of function resolution
8664// - allows us to avoid passing around all those ugly parameters
8665class AddressOfFunctionResolver
8666{
8667 Sema& S;
8668 Expr* SourceExpr;
8669 const QualType& TargetType;
8670 QualType TargetFunctionType; // Extracted function type from target type
8671
8672 bool Complain;
8673 //DeclAccessPair& ResultFunctionAccessPair;
8674 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008675
Douglas Gregorb491ed32011-02-19 21:32:49 +00008676 bool TargetTypeIsNonStaticMemberFunction;
8677 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008678
Douglas Gregorb491ed32011-02-19 21:32:49 +00008679 OverloadExpr::FindResult OvlExprInfo;
8680 OverloadExpr *OvlExpr;
8681 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008682 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008683
Douglas Gregorb491ed32011-02-19 21:32:49 +00008684public:
8685 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8686 const QualType& TargetType, bool Complain)
8687 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8688 Complain(Complain), Context(S.getASTContext()),
8689 TargetTypeIsNonStaticMemberFunction(
8690 !!TargetType->getAs<MemberPointerType>()),
8691 FoundNonTemplateFunction(false),
8692 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8693 OvlExpr(OvlExprInfo.Expression)
8694 {
8695 ExtractUnqualifiedFunctionTypeFromTargetType();
8696
8697 if (!TargetFunctionType->isFunctionType()) {
8698 if (OvlExpr->hasExplicitTemplateArgs()) {
8699 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008700 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008701 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008702
8703 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8704 if (!Method->isStatic()) {
8705 // If the target type is a non-function type and the function
8706 // found is a non-static member function, pretend as if that was
8707 // the target, it's the only possible type to end up with.
8708 TargetTypeIsNonStaticMemberFunction = true;
8709
8710 // And skip adding the function if its not in the proper form.
8711 // We'll diagnose this due to an empty set of functions.
8712 if (!OvlExprInfo.HasFormOfMemberPointer)
8713 return;
8714 }
8715 }
8716
Douglas Gregorb491ed32011-02-19 21:32:49 +00008717 Matches.push_back(std::make_pair(dap,Fn));
8718 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008719 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008720 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008721 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008722
8723 if (OvlExpr->hasExplicitTemplateArgs())
8724 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008725
Douglas Gregorb491ed32011-02-19 21:32:49 +00008726 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8727 // C++ [over.over]p4:
8728 // If more than one function is selected, [...]
8729 if (Matches.size() > 1) {
8730 if (FoundNonTemplateFunction)
8731 EliminateAllTemplateMatches();
8732 else
8733 EliminateAllExceptMostSpecializedTemplate();
8734 }
8735 }
8736 }
8737
8738private:
8739 bool isTargetTypeAFunction() const {
8740 return TargetFunctionType->isFunctionType();
8741 }
8742
8743 // [ToType] [Return]
8744
8745 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8746 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8747 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8748 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8749 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8750 }
8751
8752 // return true if any matching specializations were found
8753 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8754 const DeclAccessPair& CurAccessFunPair) {
8755 if (CXXMethodDecl *Method
8756 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8757 // Skip non-static function templates when converting to pointer, and
8758 // static when converting to member pointer.
8759 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8760 return false;
8761 }
8762 else if (TargetTypeIsNonStaticMemberFunction)
8763 return false;
8764
8765 // C++ [over.over]p2:
8766 // If the name is a function template, template argument deduction is
8767 // done (14.8.2.2), and if the argument deduction succeeds, the
8768 // resulting template argument list is used to generate a single
8769 // function template specialization, which is added to the set of
8770 // overloaded functions considered.
8771 FunctionDecl *Specialization = 0;
8772 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8773 if (Sema::TemplateDeductionResult Result
8774 = S.DeduceTemplateArguments(FunctionTemplate,
8775 &OvlExplicitTemplateArgs,
8776 TargetFunctionType, Specialization,
8777 Info)) {
8778 // FIXME: make a note of the failed deduction for diagnostics.
8779 (void)Result;
8780 return false;
8781 }
8782
8783 // Template argument deduction ensures that we have an exact match.
8784 // This function template specicalization works.
8785 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8786 assert(TargetFunctionType
8787 == Context.getCanonicalType(Specialization->getType()));
8788 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8789 return true;
8790 }
8791
8792 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8793 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008794 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008795 // Skip non-static functions when converting to pointer, and static
8796 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008797 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8798 return false;
8799 }
8800 else if (TargetTypeIsNonStaticMemberFunction)
8801 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008802
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008803 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008804 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008805 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8806 if (S.CheckCUDATarget(Caller, FunDecl))
8807 return false;
8808
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008809 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008810 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8811 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008812 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8813 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008814 Matches.push_back(std::make_pair(CurAccessFunPair,
8815 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008816 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008817 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008818 }
Mike Stump11289f42009-09-09 15:08:12 +00008819 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008820
8821 return false;
8822 }
8823
8824 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8825 bool Ret = false;
8826
8827 // If the overload expression doesn't have the form of a pointer to
8828 // member, don't try to convert it to a pointer-to-member type.
8829 if (IsInvalidFormOfPointerToMemberFunction())
8830 return false;
8831
8832 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8833 E = OvlExpr->decls_end();
8834 I != E; ++I) {
8835 // Look through any using declarations to find the underlying function.
8836 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8837
8838 // C++ [over.over]p3:
8839 // Non-member functions and static member functions match
8840 // targets of type "pointer-to-function" or "reference-to-function."
8841 // Nonstatic member functions match targets of
8842 // type "pointer-to-member-function."
8843 // Note that according to DR 247, the containing class does not matter.
8844 if (FunctionTemplateDecl *FunctionTemplate
8845 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8846 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8847 Ret = true;
8848 }
8849 // If we have explicit template arguments supplied, skip non-templates.
8850 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8851 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8852 Ret = true;
8853 }
8854 assert(Ret || Matches.empty());
8855 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008856 }
8857
Douglas Gregorb491ed32011-02-19 21:32:49 +00008858 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008859 // [...] and any given function template specialization F1 is
8860 // eliminated if the set contains a second function template
8861 // specialization whose function template is more specialized
8862 // than the function template of F1 according to the partial
8863 // ordering rules of 14.5.5.2.
8864
8865 // The algorithm specified above is quadratic. We instead use a
8866 // two-pass algorithm (similar to the one used to identify the
8867 // best viable function in an overload set) that identifies the
8868 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008869
8870 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8871 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8872 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008873
John McCall58cc69d2010-01-27 01:50:18 +00008874 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008875 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8876 TPOC_Other, 0, SourceExpr->getLocStart(),
8877 S.PDiag(),
8878 S.PDiag(diag::err_addr_ovl_ambiguous)
8879 << Matches[0].second->getDeclName(),
8880 S.PDiag(diag::note_ovl_candidate)
8881 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008882 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008883
Douglas Gregorb491ed32011-02-19 21:32:49 +00008884 if (Result != MatchesCopy.end()) {
8885 // Make it the first and only element
8886 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8887 Matches[0].second = cast<FunctionDecl>(*Result);
8888 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008889 }
8890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008891
Douglas Gregorb491ed32011-02-19 21:32:49 +00008892 void EliminateAllTemplateMatches() {
8893 // [...] any function template specializations in the set are
8894 // eliminated if the set also contains a non-template function, [...]
8895 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8896 if (Matches[I].second->getPrimaryTemplate() == 0)
8897 ++I;
8898 else {
8899 Matches[I] = Matches[--N];
8900 Matches.set_size(N);
8901 }
8902 }
8903 }
8904
8905public:
8906 void ComplainNoMatchesFound() const {
8907 assert(Matches.empty());
8908 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8909 << OvlExpr->getName() << TargetFunctionType
8910 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008911 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008912 }
8913
8914 bool IsInvalidFormOfPointerToMemberFunction() const {
8915 return TargetTypeIsNonStaticMemberFunction &&
8916 !OvlExprInfo.HasFormOfMemberPointer;
8917 }
8918
8919 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8920 // TODO: Should we condition this on whether any functions might
8921 // have matched, or is it more appropriate to do that in callers?
8922 // TODO: a fixit wouldn't hurt.
8923 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8924 << TargetType << OvlExpr->getSourceRange();
8925 }
8926
8927 void ComplainOfInvalidConversion() const {
8928 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8929 << OvlExpr->getName() << TargetType;
8930 }
8931
8932 void ComplainMultipleMatchesFound() const {
8933 assert(Matches.size() > 1);
8934 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8935 << OvlExpr->getName()
8936 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008937 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008938 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008939
8940 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8941
Douglas Gregorb491ed32011-02-19 21:32:49 +00008942 int getNumMatches() const { return Matches.size(); }
8943
8944 FunctionDecl* getMatchingFunctionDecl() const {
8945 if (Matches.size() != 1) return 0;
8946 return Matches[0].second;
8947 }
8948
8949 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8950 if (Matches.size() != 1) return 0;
8951 return &Matches[0].first;
8952 }
8953};
8954
8955/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8956/// an overloaded function (C++ [over.over]), where @p From is an
8957/// expression with overloaded function type and @p ToType is the type
8958/// we're trying to resolve to. For example:
8959///
8960/// @code
8961/// int f(double);
8962/// int f(int);
8963///
8964/// int (*pfd)(double) = f; // selects f(double)
8965/// @endcode
8966///
8967/// This routine returns the resulting FunctionDecl if it could be
8968/// resolved, and NULL otherwise. When @p Complain is true, this
8969/// routine will emit diagnostics if there is an error.
8970FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008971Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8972 QualType TargetType,
8973 bool Complain,
8974 DeclAccessPair &FoundResult,
8975 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008976 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008977
8978 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8979 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008980 int NumMatches = Resolver.getNumMatches();
8981 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008982 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008983 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8984 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8985 else
8986 Resolver.ComplainNoMatchesFound();
8987 }
8988 else if (NumMatches > 1 && Complain)
8989 Resolver.ComplainMultipleMatchesFound();
8990 else if (NumMatches == 1) {
8991 Fn = Resolver.getMatchingFunctionDecl();
8992 assert(Fn);
8993 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00008994 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008995 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008996 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008997 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008998
8999 if (pHadMultipleCandidates)
9000 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009001 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009002}
9003
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009004/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009005/// resolve that overloaded function expression down to a single function.
9006///
9007/// This routine can only resolve template-ids that refer to a single function
9008/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009009/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009010/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009011FunctionDecl *
9012Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9013 bool Complain,
9014 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009015 // C++ [over.over]p1:
9016 // [...] [Note: any redundant set of parentheses surrounding the
9017 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009018 // C++ [over.over]p1:
9019 // [...] The overloaded function name can be preceded by the &
9020 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009021
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009022 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009023 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009024 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009025
9026 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009027 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009028
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009029 // Look through all of the overloaded functions, searching for one
9030 // whose type matches exactly.
9031 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009032 for (UnresolvedSetIterator I = ovl->decls_begin(),
9033 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009034 // C++0x [temp.arg.explicit]p3:
9035 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009036 // where deduction is not done, if a template argument list is
9037 // specified and it, along with any default template arguments,
9038 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009039 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009040 FunctionTemplateDecl *FunctionTemplate
9041 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009042
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009043 // C++ [over.over]p2:
9044 // If the name is a function template, template argument deduction is
9045 // done (14.8.2.2), and if the argument deduction succeeds, the
9046 // resulting template argument list is used to generate a single
9047 // function template specialization, which is added to the set of
9048 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009049 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009050 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009051 if (TemplateDeductionResult Result
9052 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9053 Specialization, Info)) {
9054 // FIXME: make a note of the failed deduction for diagnostics.
9055 (void)Result;
9056 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009057 }
9058
John McCall0009fcc2011-04-26 20:42:42 +00009059 assert(Specialization && "no specialization and no error?");
9060
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009061 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009062 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009063 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009064 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9065 << ovl->getName();
9066 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009067 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009068 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009069 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009070
John McCall0009fcc2011-04-26 20:42:42 +00009071 Matched = Specialization;
9072 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009074
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009075 return Matched;
9076}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009077
Douglas Gregor1beec452011-03-12 01:48:56 +00009078
9079
9080
John McCall50a2c2c2011-10-11 23:14:30 +00009081// Resolve and fix an overloaded expression that can be resolved
9082// because it identifies a single function template specialization.
9083//
Douglas Gregor1beec452011-03-12 01:48:56 +00009084// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009085//
9086// Return true if it was logically possible to so resolve the
9087// expression, regardless of whether or not it succeeded. Always
9088// returns true if 'complain' is set.
9089bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9090 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9091 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009092 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009093 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009094 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009095
John McCall50a2c2c2011-10-11 23:14:30 +00009096 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009097
John McCall0009fcc2011-04-26 20:42:42 +00009098 DeclAccessPair found;
9099 ExprResult SingleFunctionExpression;
9100 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9101 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009102 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009103 SrcExpr = ExprError();
9104 return true;
9105 }
John McCall0009fcc2011-04-26 20:42:42 +00009106
9107 // It is only correct to resolve to an instance method if we're
9108 // resolving a form that's permitted to be a pointer to member.
9109 // Otherwise we'll end up making a bound member expression, which
9110 // is illegal in all the contexts we resolve like this.
9111 if (!ovl.HasFormOfMemberPointer &&
9112 isa<CXXMethodDecl>(fn) &&
9113 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009114 if (!complain) return false;
9115
9116 Diag(ovl.Expression->getExprLoc(),
9117 diag::err_bound_member_function)
9118 << 0 << ovl.Expression->getSourceRange();
9119
9120 // TODO: I believe we only end up here if there's a mix of
9121 // static and non-static candidates (otherwise the expression
9122 // would have 'bound member' type, not 'overload' type).
9123 // Ideally we would note which candidate was chosen and why
9124 // the static candidates were rejected.
9125 SrcExpr = ExprError();
9126 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009127 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009128
John McCall0009fcc2011-04-26 20:42:42 +00009129 // Fix the expresion to refer to 'fn'.
9130 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009131 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009132
9133 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009134 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009135 SingleFunctionExpression =
9136 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009137 if (SingleFunctionExpression.isInvalid()) {
9138 SrcExpr = ExprError();
9139 return true;
9140 }
9141 }
John McCall0009fcc2011-04-26 20:42:42 +00009142 }
9143
9144 if (!SingleFunctionExpression.isUsable()) {
9145 if (complain) {
9146 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9147 << ovl.Expression->getName()
9148 << DestTypeForComplaining
9149 << OpRangeForComplaining
9150 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009151 NoteAllOverloadCandidates(SrcExpr.get());
9152
9153 SrcExpr = ExprError();
9154 return true;
9155 }
9156
9157 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009158 }
9159
John McCall50a2c2c2011-10-11 23:14:30 +00009160 SrcExpr = SingleFunctionExpression;
9161 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009162}
9163
Douglas Gregorcabea402009-09-22 15:41:20 +00009164/// \brief Add a single candidate to the overload set.
9165static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009166 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009167 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009168 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009169 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009170 bool PartialOverloading,
9171 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009172 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009173 if (isa<UsingShadowDecl>(Callee))
9174 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9175
Douglas Gregorcabea402009-09-22 15:41:20 +00009176 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009177 if (ExplicitTemplateArgs) {
9178 assert(!KnownValid && "Explicit template arguments?");
9179 return;
9180 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009181 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9182 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009183 return;
John McCalld14a8642009-11-21 08:51:07 +00009184 }
9185
9186 if (FunctionTemplateDecl *FuncTemplate
9187 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009188 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009189 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009190 return;
9191 }
9192
Richard Smith95ce4f62011-06-26 22:19:54 +00009193 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009194}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009195
Douglas Gregorcabea402009-09-22 15:41:20 +00009196/// \brief Add the overload candidates named by callee and/or found by argument
9197/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009198void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009199 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009200 OverloadCandidateSet &CandidateSet,
9201 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009202
9203#ifndef NDEBUG
9204 // Verify that ArgumentDependentLookup is consistent with the rules
9205 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009206 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009207 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9208 // and let Y be the lookup set produced by argument dependent
9209 // lookup (defined as follows). If X contains
9210 //
9211 // -- a declaration of a class member, or
9212 //
9213 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009214 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009215 //
9216 // -- a declaration that is neither a function or a function
9217 // template
9218 //
9219 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009220
John McCall57500772009-12-16 12:17:52 +00009221 if (ULE->requiresADL()) {
9222 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9223 E = ULE->decls_end(); I != E; ++I) {
9224 assert(!(*I)->getDeclContext()->isRecord());
9225 assert(isa<UsingShadowDecl>(*I) ||
9226 !(*I)->getDeclContext()->isFunctionOrMethod());
9227 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009228 }
9229 }
9230#endif
9231
John McCall57500772009-12-16 12:17:52 +00009232 // It would be nice to avoid this copy.
9233 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009234 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009235 if (ULE->hasExplicitTemplateArgs()) {
9236 ULE->copyTemplateArgumentsInto(TABuffer);
9237 ExplicitTemplateArgs = &TABuffer;
9238 }
9239
9240 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9241 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009242 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9243 CandidateSet, PartialOverloading,
9244 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009245
John McCall57500772009-12-16 12:17:52 +00009246 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009247 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009248 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009249 Args, ExplicitTemplateArgs,
9250 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009251 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009252}
John McCalld681c392009-12-16 08:11:27 +00009253
Richard Smith998a5912011-06-05 22:42:48 +00009254/// Attempt to recover from an ill-formed use of a non-dependent name in a
9255/// template, where the non-dependent name was declared after the template
9256/// was defined. This is common in code written for a compilers which do not
9257/// correctly implement two-stage name lookup.
9258///
9259/// Returns true if a viable candidate was found and a diagnostic was issued.
9260static bool
9261DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9262 const CXXScopeSpec &SS, LookupResult &R,
9263 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009264 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009265 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9266 return false;
9267
9268 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009269 if (DC->isTransparentContext())
9270 continue;
9271
Richard Smith998a5912011-06-05 22:42:48 +00009272 SemaRef.LookupQualifiedName(R, DC);
9273
9274 if (!R.empty()) {
9275 R.suppressDiagnostics();
9276
9277 if (isa<CXXRecordDecl>(DC)) {
9278 // Don't diagnose names we find in classes; we get much better
9279 // diagnostics for these from DiagnoseEmptyLookup.
9280 R.clear();
9281 return false;
9282 }
9283
9284 OverloadCandidateSet Candidates(FnLoc);
9285 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9286 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009287 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009288 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009289
9290 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009291 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009292 // No viable functions. Don't bother the user with notes for functions
9293 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009294 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009295 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009296 }
Richard Smith998a5912011-06-05 22:42:48 +00009297
9298 // Find the namespaces where ADL would have looked, and suggest
9299 // declaring the function there instead.
9300 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9301 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009302 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009303 AssociatedNamespaces,
9304 AssociatedClasses);
9305 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009306 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009307 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009308 for (Sema::AssociatedNamespaceSet::iterator
9309 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009310 end = AssociatedNamespaces.end(); it != end; ++it) {
9311 if (!Std->Encloses(*it))
9312 SuggestedNamespaces.insert(*it);
9313 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009314 } else {
9315 // Lacking the 'std::' namespace, use all of the associated namespaces.
9316 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009317 }
9318
9319 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9320 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009321 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009322 SemaRef.Diag(Best->Function->getLocation(),
9323 diag::note_not_found_by_two_phase_lookup)
9324 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009325 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009326 SemaRef.Diag(Best->Function->getLocation(),
9327 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009328 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009329 } else {
9330 // FIXME: It would be useful to list the associated namespaces here,
9331 // but the diagnostics infrastructure doesn't provide a way to produce
9332 // a localized representation of a list of items.
9333 SemaRef.Diag(Best->Function->getLocation(),
9334 diag::note_not_found_by_two_phase_lookup)
9335 << R.getLookupName() << 2;
9336 }
9337
9338 // Try to recover by calling this function.
9339 return true;
9340 }
9341
9342 R.clear();
9343 }
9344
9345 return false;
9346}
9347
9348/// Attempt to recover from ill-formed use of a non-dependent operator in a
9349/// template, where the non-dependent operator was declared after the template
9350/// was defined.
9351///
9352/// Returns true if a viable candidate was found and a diagnostic was issued.
9353static bool
9354DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9355 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009356 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009357 DeclarationName OpName =
9358 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9359 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9360 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009361 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009362}
9363
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009364namespace {
9365// Callback to limit the allowed keywords and to only accept typo corrections
9366// that are keywords or whose decls refer to functions (or template functions)
9367// that accept the given number of arguments.
9368class RecoveryCallCCC : public CorrectionCandidateCallback {
9369 public:
9370 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9371 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009372 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009373 WantRemainingKeywords = false;
9374 }
9375
9376 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9377 if (!candidate.getCorrectionDecl())
9378 return candidate.isKeyword();
9379
9380 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9381 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9382 FunctionDecl *FD = 0;
9383 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9384 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9385 FD = FTD->getTemplatedDecl();
9386 if (!HasExplicitTemplateArgs && !FD) {
9387 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9388 // If the Decl is neither a function nor a template function,
9389 // determine if it is a pointer or reference to a function. If so,
9390 // check against the number of arguments expected for the pointee.
9391 QualType ValType = cast<ValueDecl>(ND)->getType();
9392 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9393 ValType = ValType->getPointeeType();
9394 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9395 if (FPT->getNumArgs() == NumArgs)
9396 return true;
9397 }
9398 }
9399 if (FD && FD->getNumParams() >= NumArgs &&
9400 FD->getMinRequiredArguments() <= NumArgs)
9401 return true;
9402 }
9403 return false;
9404 }
9405
9406 private:
9407 unsigned NumArgs;
9408 bool HasExplicitTemplateArgs;
9409};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009410
9411// Callback that effectively disabled typo correction
9412class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9413 public:
9414 NoTypoCorrectionCCC() {
9415 WantTypeSpecifiers = false;
9416 WantExpressionKeywords = false;
9417 WantCXXNamedCasts = false;
9418 WantRemainingKeywords = false;
9419 }
9420
9421 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9422 return false;
9423 }
9424};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009425}
9426
John McCalld681c392009-12-16 08:11:27 +00009427/// Attempts to recover from a call where no functions were found.
9428///
9429/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009430static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009431BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009432 UnresolvedLookupExpr *ULE,
9433 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009434 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009435 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009436 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009437
9438 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009439 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009440 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009441
John McCall57500772009-12-16 12:17:52 +00009442 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009443 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009444 if (ULE->hasExplicitTemplateArgs()) {
9445 ULE->copyTemplateArgumentsInto(TABuffer);
9446 ExplicitTemplateArgs = &TABuffer;
9447 }
9448
John McCalld681c392009-12-16 08:11:27 +00009449 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9450 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009451 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009452 NoTypoCorrectionCCC RejectAll;
9453 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9454 (CorrectionCandidateCallback*)&Validator :
9455 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009456 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009457 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009458 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009459 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009460 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009461 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009462
John McCall57500772009-12-16 12:17:52 +00009463 assert(!R.empty() && "lookup results empty despite recovery");
9464
9465 // Build an implicit member call if appropriate. Just drop the
9466 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009467 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009468 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009469 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9470 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009471 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009472 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009473 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009474 else
9475 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9476
9477 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009478 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009479
9480 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009481 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009482 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009483 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009484 MultiExprArg(Args.data(), Args.size()),
9485 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009486}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009487
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009488/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009489/// (which eventually refers to the declaration Func) and the call
9490/// arguments Args/NumArgs, attempt to resolve the function call down
9491/// to a specific function. If overload resolution succeeds, returns
9492/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009493/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009494/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009495ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009496Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009497 SourceLocation LParenLoc,
9498 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009499 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009500 Expr *ExecConfig,
9501 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009502#ifndef NDEBUG
9503 if (ULE->requiresADL()) {
9504 // To do ADL, we must have found an unqualified name.
9505 assert(!ULE->getQualifier() && "qualified name with ADL");
9506
9507 // We don't perform ADL for implicit declarations of builtins.
9508 // Verify that this was correctly set up.
9509 FunctionDecl *F;
9510 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9511 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9512 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009513 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009514
John McCall57500772009-12-16 12:17:52 +00009515 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009516 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009517 } else
9518 assert(!ULE->isStdAssociatedNamespace() &&
9519 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009520#endif
9521
John McCall4124c492011-10-17 18:40:02 +00009522 UnbridgedCastsSet UnbridgedCasts;
9523 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9524 return ExprError();
9525
John McCallbc077cf2010-02-08 23:07:23 +00009526 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009527
John McCall57500772009-12-16 12:17:52 +00009528 // Add the functions denoted by the callee to the set of candidate
9529 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009530 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9531 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009532
9533 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009534 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9535 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009536 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009537 // In Microsoft mode, if we are inside a template class member function then
9538 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009539 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009540 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009541 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009542 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009543 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9544 Context.DependentTy, VK_RValue,
9545 RParenLoc);
9546 CE->setTypeDependent(true);
9547 return Owned(CE);
9548 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009549 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9550 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009551 RParenLoc, /*EmptyLookup=*/true,
9552 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009553 }
John McCalld681c392009-12-16 08:11:27 +00009554
John McCall4124c492011-10-17 18:40:02 +00009555 UnbridgedCasts.restore();
9556
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009557 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009558 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009559 case OR_Success: {
9560 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009561 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009562 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009563 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009564 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009565 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9566 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009567 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009568
Richard Smith998a5912011-06-05 22:42:48 +00009569 case OR_No_Viable_Function: {
9570 // Try to recover by looking for viable functions which the user might
9571 // have meant to call.
9572 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009573 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9574 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009575 /*EmptyLookup=*/false,
9576 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009577 if (!Recovery.isInvalid())
9578 return Recovery;
9579
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009580 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009581 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009582 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009583 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9584 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009585 break;
Richard Smith998a5912011-06-05 22:42:48 +00009586 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009587
9588 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009589 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009590 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009591 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9592 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009593 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009594
9595 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009596 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009597 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009598 << Best->Function->isDeleted()
9599 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009600 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009601 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009602 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9603 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009604
9605 // We emitted an error for the unvailable/deleted function call but keep
9606 // the call in the AST.
9607 FunctionDecl *FDecl = Best->Function;
9608 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9609 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9610 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009611 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009612 }
9613
Douglas Gregorb412e172010-07-25 18:17:45 +00009614 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009615 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009616}
9617
John McCall4c4c1df2010-01-26 03:27:55 +00009618static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009619 return Functions.size() > 1 ||
9620 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9621}
9622
Douglas Gregor084d8552009-03-13 23:49:33 +00009623/// \brief Create a unary operation that may resolve to an overloaded
9624/// operator.
9625///
9626/// \param OpLoc The location of the operator itself (e.g., '*').
9627///
9628/// \param OpcIn The UnaryOperator::Opcode that describes this
9629/// operator.
9630///
9631/// \param Functions The set of non-member functions that will be
9632/// considered by overload resolution. The caller needs to build this
9633/// set based on the context using, e.g.,
9634/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9635/// set should not contain any member functions; those will be added
9636/// by CreateOverloadedUnaryOp().
9637///
9638/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009639ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009640Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9641 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009642 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009643 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009644
9645 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9646 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9647 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009648 // TODO: provide better source location info.
9649 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009650
John McCall4124c492011-10-17 18:40:02 +00009651 if (checkPlaceholderForOverload(*this, Input))
9652 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009653
Douglas Gregor084d8552009-03-13 23:49:33 +00009654 Expr *Args[2] = { Input, 0 };
9655 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009656
Douglas Gregor084d8552009-03-13 23:49:33 +00009657 // For post-increment and post-decrement, add the implicit '0' as
9658 // the second argument, so that we know this is a post-increment or
9659 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009660 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009661 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009662 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9663 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009664 NumArgs = 2;
9665 }
9666
9667 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009668 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009669 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009670 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009671 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009672 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009673 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009674
John McCall58cc69d2010-01-27 01:50:18 +00009675 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009676 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009677 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009678 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009679 /*ADL*/ true, IsOverloaded(Fns),
9680 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009681 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009682 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009683 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009684 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009685 OpLoc));
9686 }
9687
9688 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009689 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009690
9691 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009692 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9693 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009694
9695 // Add operator candidates that are member functions.
9696 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9697
John McCall4c4c1df2010-01-26 03:27:55 +00009698 // Add candidates from ADL.
9699 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009700 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009701 /*ExplicitTemplateArgs*/ 0,
9702 CandidateSet);
9703
Douglas Gregor084d8552009-03-13 23:49:33 +00009704 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009705 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009706
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009707 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9708
Douglas Gregor084d8552009-03-13 23:49:33 +00009709 // Perform overload resolution.
9710 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009711 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009712 case OR_Success: {
9713 // We found a built-in operator or an overloaded operator.
9714 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009715
Douglas Gregor084d8552009-03-13 23:49:33 +00009716 if (FnDecl) {
9717 // We matched an overloaded operator. Build a call to that
9718 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009719
Eli Friedmanfa0df832012-02-02 03:46:19 +00009720 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009721
Douglas Gregor084d8552009-03-13 23:49:33 +00009722 // Convert the arguments.
9723 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009724 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009725
John Wiegley01296292011-04-08 18:41:53 +00009726 ExprResult InputRes =
9727 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9728 Best->FoundDecl, Method);
9729 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009730 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009731 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009732 } else {
9733 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009734 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009735 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009736 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009737 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009738 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009739 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009740 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009741 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009742 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009743 }
9744
John McCall4fa0d5f2010-05-06 18:15:07 +00009745 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9746
John McCall7decc9e2010-11-18 06:31:45 +00009747 // Determine the result type.
9748 QualType ResultTy = FnDecl->getResultType();
9749 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9750 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009751
Douglas Gregor084d8552009-03-13 23:49:33 +00009752 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009753 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009754 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009755 if (FnExpr.isInvalid())
9756 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009757
Eli Friedman030eee42009-11-18 03:58:17 +00009758 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009759 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009760 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009761 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009762
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009763 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009764 FnDecl))
9765 return ExprError();
9766
John McCallb268a282010-08-23 23:25:46 +00009767 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009768 } else {
9769 // We matched a built-in operator. Convert the arguments, then
9770 // break out so that we will build the appropriate built-in
9771 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009772 ExprResult InputRes =
9773 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9774 Best->Conversions[0], AA_Passing);
9775 if (InputRes.isInvalid())
9776 return ExprError();
9777 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009778 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009779 }
John Wiegley01296292011-04-08 18:41:53 +00009780 }
9781
9782 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009783 // This is an erroneous use of an operator which can be overloaded by
9784 // a non-member function. Check for non-member operators which were
9785 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009786 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9787 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +00009788 // FIXME: Recover by calling the found function.
9789 return ExprError();
9790
John Wiegley01296292011-04-08 18:41:53 +00009791 // No viable function; fall through to handling this as a
9792 // built-in operator, which will produce an error message for us.
9793 break;
9794
9795 case OR_Ambiguous:
9796 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9797 << UnaryOperator::getOpcodeStr(Opc)
9798 << Input->getType()
9799 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009800 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9801 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +00009802 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9803 return ExprError();
9804
9805 case OR_Deleted:
9806 Diag(OpLoc, diag::err_ovl_deleted_oper)
9807 << Best->Function->isDeleted()
9808 << UnaryOperator::getOpcodeStr(Opc)
9809 << getDeletedOrUnavailableSuffix(Best->Function)
9810 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009811 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9812 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009813 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009814 return ExprError();
9815 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009816
9817 // Either we found no viable overloaded operator or we matched a
9818 // built-in operator. In either case, fall through to trying to
9819 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009820 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009821}
9822
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009823/// \brief Create a binary operation that may resolve to an overloaded
9824/// operator.
9825///
9826/// \param OpLoc The location of the operator itself (e.g., '+').
9827///
9828/// \param OpcIn The BinaryOperator::Opcode that describes this
9829/// operator.
9830///
9831/// \param Functions The set of non-member functions that will be
9832/// considered by overload resolution. The caller needs to build this
9833/// set based on the context using, e.g.,
9834/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9835/// set should not contain any member functions; those will be added
9836/// by CreateOverloadedBinOp().
9837///
9838/// \param LHS Left-hand argument.
9839/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009840ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009841Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009842 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009843 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009844 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009845 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009846 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009847
9848 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9849 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9850 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9851
9852 // If either side is type-dependent, create an appropriate dependent
9853 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009854 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009855 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009856 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009857 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009858 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009859 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009860 Context.DependentTy,
9861 VK_RValue, OK_Ordinary,
9862 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009863
Douglas Gregor5287f092009-11-05 00:51:44 +00009864 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9865 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009866 VK_LValue,
9867 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009868 Context.DependentTy,
9869 Context.DependentTy,
9870 OpLoc));
9871 }
John McCall4c4c1df2010-01-26 03:27:55 +00009872
9873 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009874 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009875 // TODO: provide better source location info in DNLoc component.
9876 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009877 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009878 = UnresolvedLookupExpr::Create(Context, NamingClass,
9879 NestedNameSpecifierLoc(), OpNameInfo,
9880 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009881 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009882 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009883 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009884 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009885 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009886 OpLoc));
9887 }
9888
John McCall4124c492011-10-17 18:40:02 +00009889 // Always do placeholder-like conversions on the RHS.
9890 if (checkPlaceholderForOverload(*this, Args[1]))
9891 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009892
John McCall526ab472011-10-25 17:37:35 +00009893 // Do placeholder-like conversion on the LHS; note that we should
9894 // not get here with a PseudoObject LHS.
9895 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009896 if (checkPlaceholderForOverload(*this, Args[0]))
9897 return ExprError();
9898
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009899 // If this is the assignment operator, we only perform overload resolution
9900 // if the left-hand side is a class or enumeration type. This is actually
9901 // a hack. The standard requires that we do overload resolution between the
9902 // various built-in candidates, but as DR507 points out, this can lead to
9903 // problems. So we do it this way, which pretty much follows what GCC does.
9904 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009905 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009906 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009907
John McCalle26a8722010-12-04 08:14:53 +00009908 // If this is the .* operator, which is not overloadable, just
9909 // create a built-in binary operator.
9910 if (Opc == BO_PtrMemD)
9911 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9912
Douglas Gregor084d8552009-03-13 23:49:33 +00009913 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009914 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009915
9916 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009917 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009918
9919 // Add operator candidates that are member functions.
9920 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9921
John McCall4c4c1df2010-01-26 03:27:55 +00009922 // Add candidates from ADL.
9923 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009924 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +00009925 /*ExplicitTemplateArgs*/ 0,
9926 CandidateSet);
9927
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009928 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009929 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009930
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009931 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9932
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009933 // Perform overload resolution.
9934 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009935 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009936 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009937 // We found a built-in operator or an overloaded operator.
9938 FunctionDecl *FnDecl = Best->Function;
9939
9940 if (FnDecl) {
9941 // We matched an overloaded operator. Build a call to that
9942 // operator.
9943
Eli Friedmanfa0df832012-02-02 03:46:19 +00009944 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009945
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009946 // Convert the arguments.
9947 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009948 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009949 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009950
Chandler Carruth8e543b32010-12-12 08:17:55 +00009951 ExprResult Arg1 =
9952 PerformCopyInitialization(
9953 InitializedEntity::InitializeParameter(Context,
9954 FnDecl->getParamDecl(0)),
9955 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009956 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009957 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009958
John Wiegley01296292011-04-08 18:41:53 +00009959 ExprResult Arg0 =
9960 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9961 Best->FoundDecl, Method);
9962 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009963 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009964 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009965 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009966 } else {
9967 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009968 ExprResult Arg0 = PerformCopyInitialization(
9969 InitializedEntity::InitializeParameter(Context,
9970 FnDecl->getParamDecl(0)),
9971 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009972 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009973 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009974
Chandler Carruth8e543b32010-12-12 08:17:55 +00009975 ExprResult Arg1 =
9976 PerformCopyInitialization(
9977 InitializedEntity::InitializeParameter(Context,
9978 FnDecl->getParamDecl(1)),
9979 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009980 if (Arg1.isInvalid())
9981 return ExprError();
9982 Args[0] = LHS = Arg0.takeAs<Expr>();
9983 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009984 }
9985
John McCall4fa0d5f2010-05-06 18:15:07 +00009986 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9987
John McCall7decc9e2010-11-18 06:31:45 +00009988 // Determine the result type.
9989 QualType ResultTy = FnDecl->getResultType();
9990 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9991 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009992
9993 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009994 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9995 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009996 if (FnExpr.isInvalid())
9997 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009998
John McCallb268a282010-08-23 23:25:46 +00009999 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010000 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010001 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010002
10003 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010004 FnDecl))
10005 return ExprError();
10006
John McCallb268a282010-08-23 23:25:46 +000010007 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010008 } else {
10009 // We matched a built-in operator. Convert the arguments, then
10010 // break out so that we will build the appropriate built-in
10011 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010012 ExprResult ArgsRes0 =
10013 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10014 Best->Conversions[0], AA_Passing);
10015 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010016 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010017 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010018
John Wiegley01296292011-04-08 18:41:53 +000010019 ExprResult ArgsRes1 =
10020 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10021 Best->Conversions[1], AA_Passing);
10022 if (ArgsRes1.isInvalid())
10023 return ExprError();
10024 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010025 break;
10026 }
10027 }
10028
Douglas Gregor66950a32009-09-30 21:46:01 +000010029 case OR_No_Viable_Function: {
10030 // C++ [over.match.oper]p9:
10031 // If the operator is the operator , [...] and there are no
10032 // viable functions, then the operator is assumed to be the
10033 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010034 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010035 break;
10036
Chandler Carruth8e543b32010-12-12 08:17:55 +000010037 // For class as left operand for assignment or compound assigment
10038 // operator do not fall through to handling in built-in, but report that
10039 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010040 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010041 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010042 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010043 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10044 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010045 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010046 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010047 // This is an erroneous use of an operator which can be overloaded by
10048 // a non-member function. Check for non-member operators which were
10049 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010050 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010051 // FIXME: Recover by calling the found function.
10052 return ExprError();
10053
Douglas Gregor66950a32009-09-30 21:46:01 +000010054 // No viable function; try to create a built-in operation, which will
10055 // produce an error. Then, show the non-viable candidates.
10056 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010058 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010059 "C++ binary operator overloading is missing candidates!");
10060 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010061 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010062 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010063 return move(Result);
10064 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010065
10066 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010067 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010068 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010069 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010070 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010071 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010072 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010073 return ExprError();
10074
10075 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010076 if (isImplicitlyDeleted(Best->Function)) {
10077 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10078 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10079 << getSpecialMember(Method)
10080 << BinaryOperator::getOpcodeStr(Opc)
10081 << getDeletedOrUnavailableSuffix(Best->Function);
10082
10083 if (Method->getParent()->isLambda()) {
10084 Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
10085 return ExprError();
10086 }
10087 } else {
10088 Diag(OpLoc, diag::err_ovl_deleted_oper)
10089 << Best->Function->isDeleted()
10090 << BinaryOperator::getOpcodeStr(Opc)
10091 << getDeletedOrUnavailableSuffix(Best->Function)
10092 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10093 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010094 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010095 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010096 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010097 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010098
Douglas Gregor66950a32009-09-30 21:46:01 +000010099 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010100 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010101}
10102
John McCalldadc5752010-08-24 06:29:42 +000010103ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010104Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10105 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010106 Expr *Base, Expr *Idx) {
10107 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010108 DeclarationName OpName =
10109 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10110
10111 // If either side is type-dependent, create an appropriate dependent
10112 // expression.
10113 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10114
John McCall58cc69d2010-01-27 01:50:18 +000010115 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010116 // CHECKME: no 'operator' keyword?
10117 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10118 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010119 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010120 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010121 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010122 /*ADL*/ true, /*Overloaded*/ false,
10123 UnresolvedSetIterator(),
10124 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010125 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010126
Sebastian Redladba46e2009-10-29 20:17:01 +000010127 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10128 Args, 2,
10129 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010130 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010131 RLoc));
10132 }
10133
John McCall4124c492011-10-17 18:40:02 +000010134 // Handle placeholders on both operands.
10135 if (checkPlaceholderForOverload(*this, Args[0]))
10136 return ExprError();
10137 if (checkPlaceholderForOverload(*this, Args[1]))
10138 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010139
Sebastian Redladba46e2009-10-29 20:17:01 +000010140 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010141 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010142
10143 // Subscript can only be overloaded as a member function.
10144
10145 // Add operator candidates that are member functions.
10146 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10147
10148 // Add builtin operator candidates.
10149 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10150
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010151 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10152
Sebastian Redladba46e2009-10-29 20:17:01 +000010153 // Perform overload resolution.
10154 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010155 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010156 case OR_Success: {
10157 // We found a built-in operator or an overloaded operator.
10158 FunctionDecl *FnDecl = Best->Function;
10159
10160 if (FnDecl) {
10161 // We matched an overloaded operator. Build a call to that
10162 // operator.
10163
Eli Friedmanfa0df832012-02-02 03:46:19 +000010164 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010165
John McCalla0296f72010-03-19 07:35:19 +000010166 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010167 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010168
Sebastian Redladba46e2009-10-29 20:17:01 +000010169 // Convert the arguments.
10170 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010171 ExprResult Arg0 =
10172 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10173 Best->FoundDecl, Method);
10174 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010175 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010176 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010177
Anders Carlssona68e51e2010-01-29 18:37:50 +000010178 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010179 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010180 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010181 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010182 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010183 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010184 Owned(Args[1]));
10185 if (InputInit.isInvalid())
10186 return ExprError();
10187
10188 Args[1] = InputInit.takeAs<Expr>();
10189
Sebastian Redladba46e2009-10-29 20:17:01 +000010190 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010191 QualType ResultTy = FnDecl->getResultType();
10192 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10193 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010194
10195 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010196 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10197 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010198 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10199 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010200 OpLocInfo.getLoc(),
10201 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010202 if (FnExpr.isInvalid())
10203 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010204
John McCallb268a282010-08-23 23:25:46 +000010205 CXXOperatorCallExpr *TheCall =
10206 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010207 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010208 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010209
John McCallb268a282010-08-23 23:25:46 +000010210 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010211 FnDecl))
10212 return ExprError();
10213
John McCallb268a282010-08-23 23:25:46 +000010214 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010215 } else {
10216 // We matched a built-in operator. Convert the arguments, then
10217 // break out so that we will build the appropriate built-in
10218 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010219 ExprResult ArgsRes0 =
10220 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10221 Best->Conversions[0], AA_Passing);
10222 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010223 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010224 Args[0] = ArgsRes0.take();
10225
10226 ExprResult ArgsRes1 =
10227 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10228 Best->Conversions[1], AA_Passing);
10229 if (ArgsRes1.isInvalid())
10230 return ExprError();
10231 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010232
10233 break;
10234 }
10235 }
10236
10237 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010238 if (CandidateSet.empty())
10239 Diag(LLoc, diag::err_ovl_no_oper)
10240 << Args[0]->getType() << /*subscript*/ 0
10241 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10242 else
10243 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10244 << Args[0]->getType()
10245 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010246 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010247 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010248 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010249 }
10250
10251 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010252 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010253 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010254 << Args[0]->getType() << Args[1]->getType()
10255 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010256 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010257 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010258 return ExprError();
10259
10260 case OR_Deleted:
10261 Diag(LLoc, diag::err_ovl_deleted_oper)
10262 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010263 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010264 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010265 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010266 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010267 return ExprError();
10268 }
10269
10270 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010271 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010272}
10273
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010274/// BuildCallToMemberFunction - Build a call to a member
10275/// function. MemExpr is the expression that refers to the member
10276/// function (and includes the object parameter), Args/NumArgs are the
10277/// arguments to the function call (not including the object
10278/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010279/// expression refers to a non-static member function or an overloaded
10280/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010281ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010282Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10283 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010284 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010285 assert(MemExprE->getType() == Context.BoundMemberTy ||
10286 MemExprE->getType() == Context.OverloadTy);
10287
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010288 // Dig out the member expression. This holds both the object
10289 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010290 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010291
John McCall0009fcc2011-04-26 20:42:42 +000010292 // Determine whether this is a call to a pointer-to-member function.
10293 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10294 assert(op->getType() == Context.BoundMemberTy);
10295 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10296
10297 QualType fnType =
10298 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10299
10300 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10301 QualType resultType = proto->getCallResultType(Context);
10302 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10303
10304 // Check that the object type isn't more qualified than the
10305 // member function we're calling.
10306 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10307
10308 QualType objectType = op->getLHS()->getType();
10309 if (op->getOpcode() == BO_PtrMemI)
10310 objectType = objectType->castAs<PointerType>()->getPointeeType();
10311 Qualifiers objectQuals = objectType.getQualifiers();
10312
10313 Qualifiers difference = objectQuals - funcQuals;
10314 difference.removeObjCGCAttr();
10315 difference.removeAddressSpace();
10316 if (difference) {
10317 std::string qualsString = difference.getAsString();
10318 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10319 << fnType.getUnqualifiedType()
10320 << qualsString
10321 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10322 }
10323
10324 CXXMemberCallExpr *call
10325 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10326 resultType, valueKind, RParenLoc);
10327
10328 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010329 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010330 call, 0))
10331 return ExprError();
10332
10333 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10334 return ExprError();
10335
10336 return MaybeBindToTemporary(call);
10337 }
10338
John McCall4124c492011-10-17 18:40:02 +000010339 UnbridgedCastsSet UnbridgedCasts;
10340 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10341 return ExprError();
10342
John McCall10eae182009-11-30 22:42:35 +000010343 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010344 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010345 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010346 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010347 if (isa<MemberExpr>(NakedMemExpr)) {
10348 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010349 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010350 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010351 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010352 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010353 } else {
10354 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010355 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010356
John McCall6e9f8f62009-12-03 04:06:58 +000010357 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010358 Expr::Classification ObjectClassification
10359 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10360 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010361
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010362 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010363 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010364
John McCall2d74de92009-12-01 22:10:20 +000010365 // FIXME: avoid copy.
10366 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10367 if (UnresExpr->hasExplicitTemplateArgs()) {
10368 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10369 TemplateArgs = &TemplateArgsBuffer;
10370 }
10371
John McCall10eae182009-11-30 22:42:35 +000010372 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10373 E = UnresExpr->decls_end(); I != E; ++I) {
10374
John McCall6e9f8f62009-12-03 04:06:58 +000010375 NamedDecl *Func = *I;
10376 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10377 if (isa<UsingShadowDecl>(Func))
10378 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10379
Douglas Gregor02824322011-01-26 19:30:28 +000010380
Francois Pichet64225792011-01-18 05:04:39 +000010381 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010382 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010383 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10384 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010385 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010386 // If explicit template arguments were provided, we can't call a
10387 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010388 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010389 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010390
John McCalla0296f72010-03-19 07:35:19 +000010391 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010392 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010393 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010394 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010395 } else {
John McCall10eae182009-11-30 22:42:35 +000010396 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010397 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010398 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010399 llvm::makeArrayRef(Args, NumArgs),
10400 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010401 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010402 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010403 }
Mike Stump11289f42009-09-09 15:08:12 +000010404
John McCall10eae182009-11-30 22:42:35 +000010405 DeclarationName DeclName = UnresExpr->getMemberName();
10406
John McCall4124c492011-10-17 18:40:02 +000010407 UnbridgedCasts.restore();
10408
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010409 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010410 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010411 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010412 case OR_Success:
10413 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010414 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010415 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010416 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010417 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010418 break;
10419
10420 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010421 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010422 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010423 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010424 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10425 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010426 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010427 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010428
10429 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010430 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010431 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010432 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10433 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010434 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010435 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010436
10437 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010438 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010439 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010440 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010441 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010442 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010443 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10444 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010445 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010446 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010447 }
10448
John McCall16df1e52010-03-30 21:47:33 +000010449 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010450
John McCall2d74de92009-12-01 22:10:20 +000010451 // If overload resolution picked a static member, build a
10452 // non-member call based on that function.
10453 if (Method->isStatic()) {
10454 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10455 Args, NumArgs, RParenLoc);
10456 }
10457
John McCall10eae182009-11-30 22:42:35 +000010458 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010459 }
10460
John McCall7decc9e2010-11-18 06:31:45 +000010461 QualType ResultType = Method->getResultType();
10462 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10463 ResultType = ResultType.getNonLValueExprType(Context);
10464
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010465 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010466 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010467 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010468 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010469
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010470 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010471 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010472 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010473 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010474
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010475 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010476 // We only need to do this if there was actually an overload; otherwise
10477 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010478 if (!Method->isStatic()) {
10479 ExprResult ObjectArg =
10480 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10481 FoundDecl, Method);
10482 if (ObjectArg.isInvalid())
10483 return ExprError();
10484 MemExpr->setBase(ObjectArg.take());
10485 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010486
10487 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010488 const FunctionProtoType *Proto =
10489 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010490 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010491 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010492 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010493
Eli Friedmanff4b4072012-02-18 04:48:30 +000010494 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10495
John McCallb268a282010-08-23 23:25:46 +000010496 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010497 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010498
Anders Carlsson47061ee2011-05-06 14:25:31 +000010499 if ((isa<CXXConstructorDecl>(CurContext) ||
10500 isa<CXXDestructorDecl>(CurContext)) &&
10501 TheCall->getMethodDecl()->isPure()) {
10502 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10503
Chandler Carruth59259262011-06-27 08:31:58 +000010504 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010505 Diag(MemExpr->getLocStart(),
10506 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10507 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10508 << MD->getParent()->getDeclName();
10509
10510 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010511 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010512 }
John McCallb268a282010-08-23 23:25:46 +000010513 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010514}
10515
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010516/// BuildCallToObjectOfClassType - Build a call to an object of class
10517/// type (C++ [over.call.object]), which can end up invoking an
10518/// overloaded function call operator (@c operator()) or performing a
10519/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010520ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010521Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010522 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010523 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010524 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010525 if (checkPlaceholderForOverload(*this, Obj))
10526 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010527 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010528
10529 UnbridgedCastsSet UnbridgedCasts;
10530 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10531 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010532
John Wiegley01296292011-04-08 18:41:53 +000010533 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10534 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010535
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010536 // C++ [over.call.object]p1:
10537 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010538 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010539 // candidate functions includes at least the function call
10540 // operators of T. The function call operators of T are obtained by
10541 // ordinary lookup of the name operator() in the context of
10542 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010543 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010544 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010545
John Wiegley01296292011-04-08 18:41:53 +000010546 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +000010547 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010548 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010549 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010550
John McCall27b18f82009-11-17 02:14:36 +000010551 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10552 LookupQualifiedName(R, Record->getDecl());
10553 R.suppressDiagnostics();
10554
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010555 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010556 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010557 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10558 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010559 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010561
Douglas Gregorab7897a2008-11-19 22:57:39 +000010562 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010563 // In addition, for each (non-explicit in C++0x) conversion function
10564 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010565 //
10566 // operator conversion-type-id () cv-qualifier;
10567 //
10568 // where cv-qualifier is the same cv-qualification as, or a
10569 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010570 // denotes the type "pointer to function of (P1,...,Pn) returning
10571 // R", or the type "reference to pointer to function of
10572 // (P1,...,Pn) returning R", or the type "reference to function
10573 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010574 // is also considered as a candidate function. Similarly,
10575 // surrogate call functions are added to the set of candidate
10576 // functions for each conversion function declared in an
10577 // accessible base class provided the function is not hidden
10578 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010579 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010580 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010581 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010582 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010583 NamedDecl *D = *I;
10584 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10585 if (isa<UsingShadowDecl>(D))
10586 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010587
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010588 // Skip over templated conversion functions; they aren't
10589 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010590 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010591 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010592
John McCall6e9f8f62009-12-03 04:06:58 +000010593 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010594 if (!Conv->isExplicit()) {
10595 // Strip the reference type (if any) and then the pointer type (if
10596 // any) to get down to what might be a function type.
10597 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10598 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10599 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010600
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010601 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10602 {
10603 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010604 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10605 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010606 }
10607 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010608 }
Mike Stump11289f42009-09-09 15:08:12 +000010609
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010610 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10611
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010612 // Perform overload resolution.
10613 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010614 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010615 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010616 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010617 // Overload resolution succeeded; we'll build the appropriate call
10618 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010619 break;
10620
10621 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010622 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010623 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010624 << Object.get()->getType() << /*call*/ 1
10625 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010626 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010627 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010628 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010629 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010630 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10631 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010632 break;
10633
10634 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010635 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010636 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010637 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010638 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10639 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010640 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010641
10642 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010643 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010644 diag::err_ovl_deleted_object_call)
10645 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010646 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010647 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010648 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010649 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10650 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010651 break;
Mike Stump11289f42009-09-09 15:08:12 +000010652 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010653
Douglas Gregorb412e172010-07-25 18:17:45 +000010654 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010655 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010656
John McCall4124c492011-10-17 18:40:02 +000010657 UnbridgedCasts.restore();
10658
Douglas Gregorab7897a2008-11-19 22:57:39 +000010659 if (Best->Function == 0) {
10660 // Since there is no function declaration, this is one of the
10661 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010662 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010663 = cast<CXXConversionDecl>(
10664 Best->Conversions[0].UserDefined.ConversionFunction);
10665
John Wiegley01296292011-04-08 18:41:53 +000010666 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010667 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010668
Douglas Gregorab7897a2008-11-19 22:57:39 +000010669 // We selected one of the surrogate functions that converts the
10670 // object parameter to a function pointer. Perform the conversion
10671 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010672
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010673 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010674 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010675 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10676 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010677 if (Call.isInvalid())
10678 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010679 // Record usage of conversion in an implicit cast.
10680 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10681 CK_UserDefinedConversion,
10682 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010683
Douglas Gregor668443e2011-01-20 00:18:04 +000010684 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010685 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010686 }
10687
Eli Friedmanfa0df832012-02-02 03:46:19 +000010688 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010689 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010690 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010691
Douglas Gregorab7897a2008-11-19 22:57:39 +000010692 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10693 // that calls this method, using Object for the implicit object
10694 // parameter and passing along the remaining arguments.
10695 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010696 const FunctionProtoType *Proto =
10697 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010698
10699 unsigned NumArgsInProto = Proto->getNumArgs();
10700 unsigned NumArgsToCheck = NumArgs;
10701
10702 // Build the full argument list for the method call (the
10703 // implicit object parameter is placed at the beginning of the
10704 // list).
10705 Expr **MethodArgs;
10706 if (NumArgs < NumArgsInProto) {
10707 NumArgsToCheck = NumArgsInProto;
10708 MethodArgs = new Expr*[NumArgsInProto + 1];
10709 } else {
10710 MethodArgs = new Expr*[NumArgs + 1];
10711 }
John Wiegley01296292011-04-08 18:41:53 +000010712 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010713 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10714 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010715
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010716 DeclarationNameInfo OpLocInfo(
10717 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10718 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010719 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010720 HadMultipleCandidates,
10721 OpLocInfo.getLoc(),
10722 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010723 if (NewFn.isInvalid())
10724 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010725
10726 // Once we've built TheCall, all of the expressions are properly
10727 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010728 QualType ResultTy = Method->getResultType();
10729 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10730 ResultTy = ResultTy.getNonLValueExprType(Context);
10731
John McCallb268a282010-08-23 23:25:46 +000010732 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010733 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010734 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010735 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010736 delete [] MethodArgs;
10737
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010738 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010739 Method))
10740 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010741
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010742 // We may have default arguments. If so, we need to allocate more
10743 // slots in the call for them.
10744 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010745 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010746 else if (NumArgs > NumArgsInProto)
10747 NumArgsToCheck = NumArgsInProto;
10748
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010749 bool IsError = false;
10750
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010751 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010752 ExprResult ObjRes =
10753 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10754 Best->FoundDecl, Method);
10755 if (ObjRes.isInvalid())
10756 IsError = true;
10757 else
10758 Object = move(ObjRes);
10759 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010760
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010761 // Check the argument types.
10762 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010763 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010764 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010765 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010766
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010767 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010768
John McCalldadc5752010-08-24 06:29:42 +000010769 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010770 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010771 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010772 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010773 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010774
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010775 IsError |= InputInit.isInvalid();
10776 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010777 } else {
John McCalldadc5752010-08-24 06:29:42 +000010778 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010779 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10780 if (DefArg.isInvalid()) {
10781 IsError = true;
10782 break;
10783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010784
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010785 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010786 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010787
10788 TheCall->setArg(i + 1, Arg);
10789 }
10790
10791 // If this is a variadic call, handle args passed through "...".
10792 if (Proto->isVariadic()) {
10793 // Promote the arguments (C99 6.5.2.2p7).
10794 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010795 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10796 IsError |= Arg.isInvalid();
10797 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010798 }
10799 }
10800
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010801 if (IsError) return true;
10802
Eli Friedmanff4b4072012-02-18 04:48:30 +000010803 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10804
John McCallb268a282010-08-23 23:25:46 +000010805 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010806 return true;
10807
John McCalle172be52010-08-24 06:09:16 +000010808 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010809}
10810
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010811/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010812/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010813/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010814ExprResult
John McCallb268a282010-08-23 23:25:46 +000010815Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010816 assert(Base->getType()->isRecordType() &&
10817 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010818
John McCall4124c492011-10-17 18:40:02 +000010819 if (checkPlaceholderForOverload(*this, Base))
10820 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010821
John McCallbc077cf2010-02-08 23:07:23 +000010822 SourceLocation Loc = Base->getExprLoc();
10823
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010824 // C++ [over.ref]p1:
10825 //
10826 // [...] An expression x->m is interpreted as (x.operator->())->m
10827 // for a class object x of type T if T::operator->() exists and if
10828 // the operator is selected as the best match function by the
10829 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010830 DeclarationName OpName =
10831 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010832 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010833 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010834
John McCallbc077cf2010-02-08 23:07:23 +000010835 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010836 PDiag(diag::err_typecheck_incomplete_tag)
10837 << Base->getSourceRange()))
10838 return ExprError();
10839
John McCall27b18f82009-11-17 02:14:36 +000010840 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10841 LookupQualifiedName(R, BaseRecord->getDecl());
10842 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010843
10844 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010845 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010846 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10847 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010848 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010849
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010850 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10851
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010852 // Perform overload resolution.
10853 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010854 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010855 case OR_Success:
10856 // Overload resolution succeeded; we'll build the call below.
10857 break;
10858
10859 case OR_No_Viable_Function:
10860 if (CandidateSet.empty())
10861 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010862 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010863 else
10864 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010865 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010866 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010867 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010868
10869 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010870 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10871 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010872 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010873 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010874
10875 case OR_Deleted:
10876 Diag(OpLoc, diag::err_ovl_deleted_oper)
10877 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010878 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010879 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010880 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010881 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010882 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010883 }
10884
Eli Friedmanfa0df832012-02-02 03:46:19 +000010885 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010886 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010887 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010888
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010889 // Convert the object parameter.
10890 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010891 ExprResult BaseResult =
10892 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10893 Best->FoundDecl, Method);
10894 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010895 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010896 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010897
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010898 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010899 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010900 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010901 if (FnExpr.isInvalid())
10902 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010903
John McCall7decc9e2010-11-18 06:31:45 +000010904 QualType ResultTy = Method->getResultType();
10905 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10906 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010907 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010908 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010909 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010910
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010911 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010912 Method))
10913 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010914
10915 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010916}
10917
Richard Smithbcc22fc2012-03-09 08:00:36 +000010918/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10919/// a literal operator described by the provided lookup results.
10920ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10921 DeclarationNameInfo &SuffixInfo,
10922 ArrayRef<Expr*> Args,
10923 SourceLocation LitEndLoc,
10924 TemplateArgumentListInfo *TemplateArgs) {
10925 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000010926
Richard Smithbcc22fc2012-03-09 08:00:36 +000010927 OverloadCandidateSet CandidateSet(UDSuffixLoc);
10928 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10929 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000010930
Richard Smithbcc22fc2012-03-09 08:00:36 +000010931 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10932
Richard Smithbcc22fc2012-03-09 08:00:36 +000010933 // Perform overload resolution. This will usually be trivial, but might need
10934 // to perform substitutions for a literal operator template.
10935 OverloadCandidateSet::iterator Best;
10936 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
10937 case OR_Success:
10938 case OR_Deleted:
10939 break;
10940
10941 case OR_No_Viable_Function:
10942 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
10943 << R.getLookupName();
10944 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
10945 return ExprError();
10946
10947 case OR_Ambiguous:
10948 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
10949 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
10950 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000010951 }
10952
Richard Smithbcc22fc2012-03-09 08:00:36 +000010953 FunctionDecl *FD = Best->Function;
10954 MarkFunctionReferenced(UDSuffixLoc, FD);
10955 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000010956
Richard Smithbcc22fc2012-03-09 08:00:36 +000010957 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
10958 SuffixInfo.getLoc(),
10959 SuffixInfo.getInfo());
10960 if (Fn.isInvalid())
10961 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000010962
10963 // Check the argument types. This should almost always be a no-op, except
10964 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000010965 Expr *ConvArgs[2];
10966 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
10967 ExprResult InputInit = PerformCopyInitialization(
10968 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
10969 SourceLocation(), Args[ArgIdx]);
10970 if (InputInit.isInvalid())
10971 return true;
10972 ConvArgs[ArgIdx] = InputInit.take();
10973 }
10974
Richard Smithc67fdd42012-03-07 08:35:16 +000010975 QualType ResultTy = FD->getResultType();
10976 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10977 ResultTy = ResultTy.getNonLValueExprType(Context);
10978
Richard Smithc67fdd42012-03-07 08:35:16 +000010979 UserDefinedLiteral *UDL =
10980 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
10981 ResultTy, VK, LitEndLoc, UDSuffixLoc);
10982
10983 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
10984 return ExprError();
10985
10986 if (CheckFunctionCall(FD, UDL))
10987 return ExprError();
10988
10989 return MaybeBindToTemporary(UDL);
10990}
10991
Douglas Gregorcd695e52008-11-10 20:40:00 +000010992/// FixOverloadedFunctionReference - E is an expression that refers to
10993/// a C++ overloaded function (possibly with some parentheses and
10994/// perhaps a '&' around it). We have resolved the overloaded function
10995/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010996/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010997Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010998 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010999 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011000 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11001 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011002 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011003 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011004
Douglas Gregor51c538b2009-11-20 19:42:02 +000011005 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011006 }
11007
Douglas Gregor51c538b2009-11-20 19:42:02 +000011008 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011009 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11010 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011011 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011012 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011013 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011014 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011015 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011016 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011017
11018 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011019 ICE->getCastKind(),
11020 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011021 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011022 }
11023
Douglas Gregor51c538b2009-11-20 19:42:02 +000011024 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011025 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011026 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11028 if (Method->isStatic()) {
11029 // Do nothing: static member functions aren't any different
11030 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011031 } else {
John McCalle66edc12009-11-24 19:00:30 +000011032 // Fix the sub expression, which really has to be an
11033 // UnresolvedLookupExpr holding an overloaded member function
11034 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011035 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11036 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011037 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011038 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011039
John McCalld14a8642009-11-21 08:51:07 +000011040 assert(isa<DeclRefExpr>(SubExpr)
11041 && "fixed to something other than a decl ref");
11042 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11043 && "fixed to a member ref with no nested name qualifier");
11044
11045 // We have taken the address of a pointer to member
11046 // function. Perform the computation here so that we get the
11047 // appropriate pointer to member type.
11048 QualType ClassType
11049 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11050 QualType MemPtrType
11051 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11052
John McCall7decc9e2010-11-18 06:31:45 +000011053 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11054 VK_RValue, OK_Ordinary,
11055 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011056 }
11057 }
John McCall16df1e52010-03-30 21:47:33 +000011058 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11059 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011060 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011061 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011062
John McCalle3027922010-08-25 11:45:40 +000011063 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011064 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011065 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011066 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011067 }
John McCalld14a8642009-11-21 08:51:07 +000011068
11069 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011070 // FIXME: avoid copy.
11071 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011072 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011073 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11074 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011075 }
11076
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011077 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11078 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011079 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011080 Fn,
John McCall113bee02012-03-10 09:33:50 +000011081 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011082 ULE->getNameLoc(),
11083 Fn->getType(),
11084 VK_LValue,
11085 Found.getDecl(),
11086 TemplateArgs);
11087 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11088 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011089 }
11090
John McCall10eae182009-11-30 22:42:35 +000011091 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011092 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011093 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11094 if (MemExpr->hasExplicitTemplateArgs()) {
11095 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11096 TemplateArgs = &TemplateArgsBuffer;
11097 }
John McCall6b51f282009-11-23 01:53:49 +000011098
John McCall2d74de92009-12-01 22:10:20 +000011099 Expr *Base;
11100
John McCall7decc9e2010-11-18 06:31:45 +000011101 // If we're filling in a static method where we used to have an
11102 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011103 if (MemExpr->isImplicitAccess()) {
11104 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011105 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11106 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011107 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011108 Fn,
John McCall113bee02012-03-10 09:33:50 +000011109 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011110 MemExpr->getMemberLoc(),
11111 Fn->getType(),
11112 VK_LValue,
11113 Found.getDecl(),
11114 TemplateArgs);
11115 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11116 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011117 } else {
11118 SourceLocation Loc = MemExpr->getMemberLoc();
11119 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011120 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011121 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011122 Base = new (Context) CXXThisExpr(Loc,
11123 MemExpr->getBaseType(),
11124 /*isImplicit=*/true);
11125 }
John McCall2d74de92009-12-01 22:10:20 +000011126 } else
John McCallc3007a22010-10-26 07:05:15 +000011127 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011128
John McCall4adb38c2011-04-27 00:36:17 +000011129 ExprValueKind valueKind;
11130 QualType type;
11131 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11132 valueKind = VK_LValue;
11133 type = Fn->getType();
11134 } else {
11135 valueKind = VK_RValue;
11136 type = Context.BoundMemberTy;
11137 }
11138
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011139 MemberExpr *ME = MemberExpr::Create(Context, Base,
11140 MemExpr->isArrow(),
11141 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011142 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011143 Fn,
11144 Found,
11145 MemExpr->getMemberNameInfo(),
11146 TemplateArgs,
11147 type, valueKind, OK_Ordinary);
11148 ME->setHadMultipleCandidates(true);
11149 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011151
John McCallc3007a22010-10-26 07:05:15 +000011152 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011153}
11154
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011155ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011156 DeclAccessPair Found,
11157 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011158 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011159}
11160
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011161} // end namespace clang