blob: 40fb01ac30d78ba41ee4132f86467dcba48dc1ac [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;
David Chisnallf6e07b92012-04-11 16:08:14 +00001523 } else if (const AtomicType *ToAtomicType = ToType->getAs<AtomicType>()) {
1524 // Allow conversion to _Atomic types. These are C11 and are provided as an
1525 // extension in C++ mode.
1526 if (S.Context.hasSameUnqualifiedType(ToAtomicType->getValueType(),
1527 FromType))
1528 SCS.Second = ICK_Identity;
1529 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530 } else {
1531 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001532 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001534 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001535
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001536 QualType CanonFrom;
1537 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001538 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001539 bool ObjCLifetimeConversion;
1540 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1541 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001543 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001544 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001545 CanonFrom = S.Context.getCanonicalType(FromType);
1546 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547 } else {
1548 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001549 SCS.Third = ICK_Identity;
1550
Mike Stump11289f42009-09-09 15:08:12 +00001551 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 // [...] Any difference in top-level cv-qualification is
1553 // subsumed by the initialization itself and does not constitute
1554 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001555 CanonFrom = S.Context.getCanonicalType(FromType);
1556 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001558 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001559 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001560 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1561 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001562 FromType = ToType;
1563 CanonFrom = CanonTo;
1564 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001566 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567
1568 // If we have not converted the argument type to the parameter type,
1569 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001570 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001571 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001573 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001575
1576static bool
1577IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1578 QualType &ToType,
1579 bool InOverloadResolution,
1580 StandardConversionSequence &SCS,
1581 bool CStyle) {
1582
1583 const RecordType *UT = ToType->getAsUnionType();
1584 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1585 return false;
1586 // The field to initialize within the transparent union.
1587 RecordDecl *UD = UT->getDecl();
1588 // It's compatible if the expression matches any of the fields.
1589 for (RecordDecl::field_iterator it = UD->field_begin(),
1590 itend = UD->field_end();
1591 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001592 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1593 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001594 ToType = it->getType();
1595 return true;
1596 }
1597 }
1598 return false;
1599}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001600
1601/// IsIntegralPromotion - Determines whether the conversion from the
1602/// expression From (whose potentially-adjusted type is FromType) to
1603/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1604/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001605bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001606 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001607 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001608 if (!To) {
1609 return false;
1610 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611
1612 // An rvalue of type char, signed char, unsigned char, short int, or
1613 // unsigned short int can be converted to an rvalue of type int if
1614 // int can represent all the values of the source type; otherwise,
1615 // the source rvalue can be converted to an rvalue of type unsigned
1616 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001617 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1618 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 if (// We can promote any signed, promotable integer type to an int
1620 (FromType->isSignedIntegerType() ||
1621 // We can promote any unsigned integer type whose size is
1622 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001623 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001624 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001626 }
1627
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 return To->getKind() == BuiltinType::UInt;
1629 }
1630
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631 // C++0x [conv.prom]p3:
1632 // A prvalue of an unscoped enumeration type whose underlying type is not
1633 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1634 // following types that can represent all the values of the enumeration
1635 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1636 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001637 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001639 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640 // with lowest integer conversion rank (4.13) greater than the rank of long
1641 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001642 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001643 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1644 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1645 // provided for a scoped enumeration.
1646 if (FromEnumType->getDecl()->isScoped())
1647 return false;
1648
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001649 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001651 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001652 return Context.hasSameUnqualifiedType(ToType,
1653 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001654 }
John McCall56774992009-12-09 09:09:27 +00001655
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001656 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001657 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1658 // to an rvalue a prvalue of the first of the following types that can
1659 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001660 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001661 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001662 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001663 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001664 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001666 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667 // Determine whether the type we're converting from is signed or
1668 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001669 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001671
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672 // The types we'll try to promote to, in the appropriate
1673 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001674 QualType PromoteTypes[6] = {
1675 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001676 Context.LongTy, Context.UnsignedLongTy ,
1677 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001679 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001680 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1681 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001682 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1684 // We found the type that we can promote to. If this is the
1685 // type we wanted, we have a promotion. Otherwise, no
1686 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001687 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688 }
1689 }
1690 }
1691
1692 // An rvalue for an integral bit-field (9.6) can be converted to an
1693 // rvalue of type int if int can represent all the values of the
1694 // bit-field; otherwise, it can be converted to unsigned int if
1695 // unsigned int can represent all the values of the bit-field. If
1696 // the bit-field is larger yet, no integral promotion applies to
1697 // it. If the bit-field has an enumerated type, it is treated as any
1698 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001699 // FIXME: We should delay checking of bit-fields until we actually perform the
1700 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001701 using llvm::APSInt;
1702 if (From)
1703 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001704 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001705 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001706 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1707 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1708 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001710 // Are we promoting to an int from a bitfield that fits in an int?
1711 if (BitWidth < ToSize ||
1712 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1713 return To->getKind() == BuiltinType::Int;
1714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001716 // Are we promoting to an unsigned int from an unsigned bitfield
1717 // that fits into an unsigned int?
1718 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1719 return To->getKind() == BuiltinType::UInt;
1720 }
Mike Stump11289f42009-09-09 15:08:12 +00001721
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001722 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001723 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001726 // An rvalue of type bool can be converted to an rvalue of type int,
1727 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001728 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001729 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001730 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001731
1732 return false;
1733}
1734
1735/// IsFloatingPointPromotion - Determines whether the conversion from
1736/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1737/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001738bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001739 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1740 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001741 /// An rvalue of type float can be converted to an rvalue of type
1742 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743 if (FromBuiltin->getKind() == BuiltinType::Float &&
1744 ToBuiltin->getKind() == BuiltinType::Double)
1745 return true;
1746
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001747 // C99 6.3.1.5p1:
1748 // When a float is promoted to double or long double, or a
1749 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001750 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001751 (FromBuiltin->getKind() == BuiltinType::Float ||
1752 FromBuiltin->getKind() == BuiltinType::Double) &&
1753 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1754 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001755
1756 // Half can be promoted to float.
1757 if (FromBuiltin->getKind() == BuiltinType::Half &&
1758 ToBuiltin->getKind() == BuiltinType::Float)
1759 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001760 }
1761
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001762 return false;
1763}
1764
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001765/// \brief Determine if a conversion is a complex promotion.
1766///
1767/// A complex promotion is defined as a complex -> complex conversion
1768/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001769/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001770bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001771 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001772 if (!FromComplex)
1773 return false;
1774
John McCall9dd450b2009-09-21 23:43:11 +00001775 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001776 if (!ToComplex)
1777 return false;
1778
1779 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001780 ToComplex->getElementType()) ||
1781 IsIntegralPromotion(0, FromComplex->getElementType(),
1782 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001783}
1784
Douglas Gregor237f96c2008-11-26 23:31:11 +00001785/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1786/// the pointer type FromPtr to a pointer to type ToPointee, with the
1787/// same type qualifiers as FromPtr has on its pointee type. ToType,
1788/// if non-empty, will be a pointer to ToType that may or may not have
1789/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001790///
Mike Stump11289f42009-09-09 15:08:12 +00001791static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001792BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001793 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001794 ASTContext &Context,
1795 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001796 assert((FromPtr->getTypeClass() == Type::Pointer ||
1797 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1798 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001799
John McCall31168b02011-06-15 23:02:42 +00001800 /// Conversions to 'id' subsume cv-qualifier conversions.
1801 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001802 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803
1804 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001805 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001806 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001807 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001808
John McCall31168b02011-06-15 23:02:42 +00001809 if (StripObjCLifetime)
1810 Quals.removeObjCLifetime();
1811
Mike Stump11289f42009-09-09 15:08:12 +00001812 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001813 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001814 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001815 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001816 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001817
1818 // Build a pointer to ToPointee. It has the right qualifiers
1819 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001820 if (isa<ObjCObjectPointerType>(ToType))
1821 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001822 return Context.getPointerType(ToPointee);
1823 }
1824
1825 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001826 QualType QualifiedCanonToPointee
1827 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001828
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001829 if (isa<ObjCObjectPointerType>(ToType))
1830 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1831 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001832}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001833
Mike Stump11289f42009-09-09 15:08:12 +00001834static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001835 bool InOverloadResolution,
1836 ASTContext &Context) {
1837 // Handle value-dependent integral null pointer constants correctly.
1838 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1839 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001840 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001841 return !InOverloadResolution;
1842
Douglas Gregor56751b52009-09-25 04:25:58 +00001843 return Expr->isNullPointerConstant(Context,
1844 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1845 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001846}
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001848/// IsPointerConversion - Determines whether the conversion of the
1849/// expression From, which has the (possibly adjusted) type FromType,
1850/// can be converted to the type ToType via a pointer conversion (C++
1851/// 4.10). If so, returns true and places the converted type (that
1852/// might differ from ToType in its cv-qualifiers at some level) into
1853/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001854///
Douglas Gregora29dc052008-11-27 01:19:21 +00001855/// This routine also supports conversions to and from block pointers
1856/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1857/// pointers to interfaces. FIXME: Once we've determined the
1858/// appropriate overloading rules for Objective-C, we may want to
1859/// split the Objective-C checks into a different routine; however,
1860/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001861/// conversions, so for now they live here. IncompatibleObjC will be
1862/// set if the conversion is an allowed Objective-C conversion that
1863/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001864bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001865 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001866 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001867 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001868 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001869 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1870 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001871 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001872
Mike Stump11289f42009-09-09 15:08:12 +00001873 // Conversion from a null pointer constant to any Objective-C pointer type.
1874 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001875 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001876 ConvertedType = ToType;
1877 return true;
1878 }
1879
Douglas Gregor231d1c62008-11-27 00:15:41 +00001880 // Blocks: Block pointers can be converted to void*.
1881 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001882 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001883 ConvertedType = ToType;
1884 return true;
1885 }
1886 // Blocks: A null pointer constant can be converted to a block
1887 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001888 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001889 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001890 ConvertedType = ToType;
1891 return true;
1892 }
1893
Sebastian Redl576fd422009-05-10 18:38:11 +00001894 // If the left-hand-side is nullptr_t, the right side can be a null
1895 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001896 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001897 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001898 ConvertedType = ToType;
1899 return true;
1900 }
1901
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001902 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001903 if (!ToTypePtr)
1904 return false;
1905
1906 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001907 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001908 ConvertedType = ToType;
1909 return true;
1910 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001911
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001913 // , including objective-c pointers.
1914 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001915 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001916 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001917 ConvertedType = BuildSimilarlyQualifiedPointerType(
1918 FromType->getAs<ObjCObjectPointerType>(),
1919 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001920 ToType, Context);
1921 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001922 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001923 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001924 if (!FromTypePtr)
1925 return false;
1926
1927 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001928
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001929 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001930 // pointer conversion, so don't do all of the work below.
1931 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1932 return false;
1933
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934 // An rvalue of type "pointer to cv T," where T is an object type,
1935 // can be converted to an rvalue of type "pointer to cv void" (C++
1936 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001937 if (FromPointeeType->isIncompleteOrObjectType() &&
1938 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001939 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001940 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001941 ToType, Context,
1942 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001943 return true;
1944 }
1945
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001946 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001947 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001948 ToPointeeType->isVoidType()) {
1949 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1950 ToPointeeType,
1951 ToType, Context);
1952 return true;
1953 }
1954
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001955 // When we're overloading in C, we allow a special kind of pointer
1956 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001957 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001958 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001959 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001960 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001961 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001962 return true;
1963 }
1964
Douglas Gregor5c407d92008-10-23 00:40:37 +00001965 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001966 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001967 // An rvalue of type "pointer to cv D," where D is a class type,
1968 // can be converted to an rvalue of type "pointer to cv B," where
1969 // B is a base class (clause 10) of D. If B is an inaccessible
1970 // (clause 11) or ambiguous (10.2) base class of D, a program that
1971 // necessitates this conversion is ill-formed. The result of the
1972 // conversion is a pointer to the base class sub-object of the
1973 // derived class object. The null pointer value is converted to
1974 // the null pointer value of the destination type.
1975 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001976 // Note that we do not check for ambiguity or inaccessibility
1977 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001978 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001979 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001980 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001981 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001982 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001984 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001985 ToType, Context);
1986 return true;
1987 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001988
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001989 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1990 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1991 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1992 ToPointeeType,
1993 ToType, Context);
1994 return true;
1995 }
1996
Douglas Gregora119f102008-12-19 19:13:09 +00001997 return false;
1998}
Douglas Gregoraec25842011-04-26 23:16:46 +00001999
2000/// \brief Adopt the given qualifiers for the given type.
2001static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2002 Qualifiers TQs = T.getQualifiers();
2003
2004 // Check whether qualifiers already match.
2005 if (TQs == Qs)
2006 return T;
2007
2008 if (Qs.compatiblyIncludes(TQs))
2009 return Context.getQualifiedType(T, Qs);
2010
2011 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2012}
Douglas Gregora119f102008-12-19 19:13:09 +00002013
2014/// isObjCPointerConversion - Determines whether this is an
2015/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2016/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002017bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002018 QualType& ConvertedType,
2019 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002020 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002021 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022
Douglas Gregoraec25842011-04-26 23:16:46 +00002023 // The set of qualifiers on the type we're converting from.
2024 Qualifiers FromQualifiers = FromType.getQualifiers();
2025
Steve Naroff7cae42b2009-07-10 23:34:53 +00002026 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002027 const ObjCObjectPointerType* ToObjCPtr =
2028 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002029 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002030 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002031
Steve Naroff7cae42b2009-07-10 23:34:53 +00002032 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002033 // If the pointee types are the same (ignoring qualifications),
2034 // then this is not a pointer conversion.
2035 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2036 FromObjCPtr->getPointeeType()))
2037 return false;
2038
Douglas Gregoraec25842011-04-26 23:16:46 +00002039 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002040 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002041 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002042 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002043 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002044 return true;
2045 }
2046 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002047 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002048 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002049 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002050 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002051 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002052 return true;
2053 }
2054 // Objective C++: We're able to convert from a pointer to an
2055 // interface to a pointer to a different interface.
2056 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002057 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2058 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002059 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002060 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2061 FromObjCPtr->getPointeeType()))
2062 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002064 ToObjCPtr->getPointeeType(),
2065 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002066 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002067 return true;
2068 }
2069
2070 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2071 // Okay: this is some kind of implicit downcast of Objective-C
2072 // interfaces, which is permitted. However, we're going to
2073 // complain about it.
2074 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002076 ToObjCPtr->getPointeeType(),
2077 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002078 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002079 return true;
2080 }
Mike Stump11289f42009-09-09 15:08:12 +00002081 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002082 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002083 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002085 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002087 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002088 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002089 // to a block pointer type.
2090 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002091 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002092 return true;
2093 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002094 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002096 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002097 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002099 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002100 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002101 return true;
2102 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002103 else
Douglas Gregora119f102008-12-19 19:13:09 +00002104 return false;
2105
Douglas Gregor033f56d2008-12-23 00:53:59 +00002106 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002107 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002108 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002109 else if (const BlockPointerType *FromBlockPtr =
2110 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002111 FromPointeeType = FromBlockPtr->getPointeeType();
2112 else
Douglas Gregora119f102008-12-19 19:13:09 +00002113 return false;
2114
Douglas Gregora119f102008-12-19 19:13:09 +00002115 // If we have pointers to pointers, recursively check whether this
2116 // is an Objective-C conversion.
2117 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2118 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2119 IncompatibleObjC)) {
2120 // We always complain about this conversion.
2121 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002122 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002123 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002124 return true;
2125 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002126 // Allow conversion of pointee being objective-c pointer to another one;
2127 // as in I* to id.
2128 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2129 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2130 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2131 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002132
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002133 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002134 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002135 return true;
2136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137
Douglas Gregor033f56d2008-12-23 00:53:59 +00002138 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002139 // differences in the argument and result types are in Objective-C
2140 // pointer conversions. If so, we permit the conversion (but
2141 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002142 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002143 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002144 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002145 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002146 if (FromFunctionType && ToFunctionType) {
2147 // If the function types are exactly the same, this isn't an
2148 // Objective-C pointer conversion.
2149 if (Context.getCanonicalType(FromPointeeType)
2150 == Context.getCanonicalType(ToPointeeType))
2151 return false;
2152
2153 // Perform the quick checks that will tell us whether these
2154 // function types are obviously different.
2155 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2156 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2157 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2158 return false;
2159
2160 bool HasObjCConversion = false;
2161 if (Context.getCanonicalType(FromFunctionType->getResultType())
2162 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2163 // Okay, the types match exactly. Nothing to do.
2164 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2165 ToFunctionType->getResultType(),
2166 ConvertedType, IncompatibleObjC)) {
2167 // Okay, we have an Objective-C pointer conversion.
2168 HasObjCConversion = true;
2169 } else {
2170 // Function types are too different. Abort.
2171 return false;
2172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Douglas Gregora119f102008-12-19 19:13:09 +00002174 // Check argument types.
2175 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2176 ArgIdx != NumArgs; ++ArgIdx) {
2177 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2178 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2179 if (Context.getCanonicalType(FromArgType)
2180 == Context.getCanonicalType(ToArgType)) {
2181 // Okay, the types match exactly. Nothing to do.
2182 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2183 ConvertedType, IncompatibleObjC)) {
2184 // Okay, we have an Objective-C pointer conversion.
2185 HasObjCConversion = true;
2186 } else {
2187 // Argument types are too different. Abort.
2188 return false;
2189 }
2190 }
2191
2192 if (HasObjCConversion) {
2193 // We had an Objective-C conversion. Allow this pointer
2194 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002195 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002196 IncompatibleObjC = true;
2197 return true;
2198 }
2199 }
2200
Sebastian Redl72b597d2009-01-25 19:43:20 +00002201 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002202}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203
John McCall31168b02011-06-15 23:02:42 +00002204/// \brief Determine whether this is an Objective-C writeback conversion,
2205/// used for parameter passing when performing automatic reference counting.
2206///
2207/// \param FromType The type we're converting form.
2208///
2209/// \param ToType The type we're converting to.
2210///
2211/// \param ConvertedType The type that will be produced after applying
2212/// this conversion.
2213bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2214 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002215 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002216 Context.hasSameUnqualifiedType(FromType, ToType))
2217 return false;
2218
2219 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2220 QualType ToPointee;
2221 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2222 ToPointee = ToPointer->getPointeeType();
2223 else
2224 return false;
2225
2226 Qualifiers ToQuals = ToPointee.getQualifiers();
2227 if (!ToPointee->isObjCLifetimeType() ||
2228 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002229 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002230 return false;
2231
2232 // Argument must be a pointer to __strong to __weak.
2233 QualType FromPointee;
2234 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2235 FromPointee = FromPointer->getPointeeType();
2236 else
2237 return false;
2238
2239 Qualifiers FromQuals = FromPointee.getQualifiers();
2240 if (!FromPointee->isObjCLifetimeType() ||
2241 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2242 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2243 return false;
2244
2245 // Make sure that we have compatible qualifiers.
2246 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2247 if (!ToQuals.compatiblyIncludes(FromQuals))
2248 return false;
2249
2250 // Remove qualifiers from the pointee type we're converting from; they
2251 // aren't used in the compatibility check belong, and we'll be adding back
2252 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2253 FromPointee = FromPointee.getUnqualifiedType();
2254
2255 // The unqualified form of the pointee types must be compatible.
2256 ToPointee = ToPointee.getUnqualifiedType();
2257 bool IncompatibleObjC;
2258 if (Context.typesAreCompatible(FromPointee, ToPointee))
2259 FromPointee = ToPointee;
2260 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2261 IncompatibleObjC))
2262 return false;
2263
2264 /// \brief Construct the type we're converting to, which is a pointer to
2265 /// __autoreleasing pointee.
2266 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2267 ConvertedType = Context.getPointerType(FromPointee);
2268 return true;
2269}
2270
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002271bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2272 QualType& ConvertedType) {
2273 QualType ToPointeeType;
2274 if (const BlockPointerType *ToBlockPtr =
2275 ToType->getAs<BlockPointerType>())
2276 ToPointeeType = ToBlockPtr->getPointeeType();
2277 else
2278 return false;
2279
2280 QualType FromPointeeType;
2281 if (const BlockPointerType *FromBlockPtr =
2282 FromType->getAs<BlockPointerType>())
2283 FromPointeeType = FromBlockPtr->getPointeeType();
2284 else
2285 return false;
2286 // We have pointer to blocks, check whether the only
2287 // differences in the argument and result types are in Objective-C
2288 // pointer conversions. If so, we permit the conversion.
2289
2290 const FunctionProtoType *FromFunctionType
2291 = FromPointeeType->getAs<FunctionProtoType>();
2292 const FunctionProtoType *ToFunctionType
2293 = ToPointeeType->getAs<FunctionProtoType>();
2294
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002295 if (!FromFunctionType || !ToFunctionType)
2296 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002297
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002298 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002299 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002300
2301 // Perform the quick checks that will tell us whether these
2302 // function types are obviously different.
2303 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2304 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2305 return false;
2306
2307 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2308 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2309 if (FromEInfo != ToEInfo)
2310 return false;
2311
2312 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002313 if (Context.hasSameType(FromFunctionType->getResultType(),
2314 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002315 // Okay, the types match exactly. Nothing to do.
2316 } else {
2317 QualType RHS = FromFunctionType->getResultType();
2318 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002319 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002320 !RHS.hasQualifiers() && LHS.hasQualifiers())
2321 LHS = LHS.getUnqualifiedType();
2322
2323 if (Context.hasSameType(RHS,LHS)) {
2324 // OK exact match.
2325 } else if (isObjCPointerConversion(RHS, LHS,
2326 ConvertedType, IncompatibleObjC)) {
2327 if (IncompatibleObjC)
2328 return false;
2329 // Okay, we have an Objective-C pointer conversion.
2330 }
2331 else
2332 return false;
2333 }
2334
2335 // Check argument types.
2336 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2337 ArgIdx != NumArgs; ++ArgIdx) {
2338 IncompatibleObjC = false;
2339 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2340 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2341 if (Context.hasSameType(FromArgType, ToArgType)) {
2342 // Okay, the types match exactly. Nothing to do.
2343 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2344 ConvertedType, IncompatibleObjC)) {
2345 if (IncompatibleObjC)
2346 return false;
2347 // Okay, we have an Objective-C pointer conversion.
2348 } else
2349 // Argument types are too different. Abort.
2350 return false;
2351 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002352 if (LangOpts.ObjCAutoRefCount &&
2353 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2354 ToFunctionType))
2355 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002356
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002357 ConvertedType = ToType;
2358 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002359}
2360
Richard Trieucaff2472011-11-23 22:32:32 +00002361enum {
2362 ft_default,
2363 ft_different_class,
2364 ft_parameter_arity,
2365 ft_parameter_mismatch,
2366 ft_return_type,
2367 ft_qualifer_mismatch
2368};
2369
2370/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2371/// function types. Catches different number of parameter, mismatch in
2372/// parameter types, and different return types.
2373void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2374 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002375 // If either type is not valid, include no extra info.
2376 if (FromType.isNull() || ToType.isNull()) {
2377 PDiag << ft_default;
2378 return;
2379 }
2380
Richard Trieucaff2472011-11-23 22:32:32 +00002381 // Get the function type from the pointers.
2382 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2383 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2384 *ToMember = ToType->getAs<MemberPointerType>();
2385 if (FromMember->getClass() != ToMember->getClass()) {
2386 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2387 << QualType(FromMember->getClass(), 0);
2388 return;
2389 }
2390 FromType = FromMember->getPointeeType();
2391 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002392 }
2393
Richard Trieu96ed5b62011-12-13 23:19:45 +00002394 if (FromType->isPointerType())
2395 FromType = FromType->getPointeeType();
2396 if (ToType->isPointerType())
2397 ToType = ToType->getPointeeType();
2398
2399 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002400 FromType = FromType.getNonReferenceType();
2401 ToType = ToType.getNonReferenceType();
2402
Richard Trieucaff2472011-11-23 22:32:32 +00002403 // Don't print extra info for non-specialized template functions.
2404 if (FromType->isInstantiationDependentType() &&
2405 !FromType->getAs<TemplateSpecializationType>()) {
2406 PDiag << ft_default;
2407 return;
2408 }
2409
Richard Trieu96ed5b62011-12-13 23:19:45 +00002410 // No extra info for same types.
2411 if (Context.hasSameType(FromType, ToType)) {
2412 PDiag << ft_default;
2413 return;
2414 }
2415
Richard Trieucaff2472011-11-23 22:32:32 +00002416 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2417 *ToFunction = ToType->getAs<FunctionProtoType>();
2418
2419 // Both types need to be function types.
2420 if (!FromFunction || !ToFunction) {
2421 PDiag << ft_default;
2422 return;
2423 }
2424
2425 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2426 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2427 << FromFunction->getNumArgs();
2428 return;
2429 }
2430
2431 // Handle different parameter types.
2432 unsigned ArgPos;
2433 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2434 PDiag << ft_parameter_mismatch << ArgPos + 1
2435 << ToFunction->getArgType(ArgPos)
2436 << FromFunction->getArgType(ArgPos);
2437 return;
2438 }
2439
2440 // Handle different return type.
2441 if (!Context.hasSameType(FromFunction->getResultType(),
2442 ToFunction->getResultType())) {
2443 PDiag << ft_return_type << ToFunction->getResultType()
2444 << FromFunction->getResultType();
2445 return;
2446 }
2447
2448 unsigned FromQuals = FromFunction->getTypeQuals(),
2449 ToQuals = ToFunction->getTypeQuals();
2450 if (FromQuals != ToQuals) {
2451 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2452 return;
2453 }
2454
2455 // Unable to find a difference, so add no extra info.
2456 PDiag << ft_default;
2457}
2458
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002459/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002460/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002461/// they have same number of arguments. This routine assumes that Objective-C
2462/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002463/// If the parameters are different, ArgPos will have the the parameter index
2464/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002465bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002466 const FunctionProtoType *NewType,
2467 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002468 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002469 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2470 N = NewType->arg_type_begin(),
2471 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2472 if (!Context.hasSameType(*O, *N)) {
2473 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2474 return false;
2475 }
2476 }
2477 return true;
2478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002479
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002480 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2481 N = NewType->arg_type_begin(),
2482 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2483 QualType ToType = (*O);
2484 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002485 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002486 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2487 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002488 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2489 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2490 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2491 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002492 continue;
2493 }
John McCall8b07ec22010-05-15 11:32:37 +00002494 else if (const ObjCObjectPointerType *PTTo =
2495 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002496 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002497 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002498 if (Context.hasSameUnqualifiedType(
2499 PTTo->getObjectType()->getBaseType(),
2500 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002501 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002502 }
Richard Trieucaff2472011-11-23 22:32:32 +00002503 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002504 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002505 }
2506 }
2507 return true;
2508}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002509
Douglas Gregor39c16d42008-10-24 04:54:22 +00002510/// CheckPointerConversion - Check the pointer conversion from the
2511/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002512/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002513/// conversions for which IsPointerConversion has already returned
2514/// true. It returns true and produces a diagnostic if there was an
2515/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002516bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002517 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002518 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002519 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002520 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002521 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002522
John McCall8cb679e2010-11-15 09:13:47 +00002523 Kind = CK_BitCast;
2524
Chandler Carruthffab8732011-04-09 07:32:05 +00002525 if (!IsCStyleOrFunctionalCast &&
2526 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2527 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2528 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002529 PDiag(diag::warn_impcast_bool_to_null_pointer)
2530 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002531
John McCall9320b872011-09-09 05:25:32 +00002532 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2533 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002534 QualType FromPointeeType = FromPtrType->getPointeeType(),
2535 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002536
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002537 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2538 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002539 // We must have a derived-to-base conversion. Check an
2540 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002541 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2542 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002543 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002544 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002545 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002546
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002547 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002548 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002549 }
2550 }
John McCall9320b872011-09-09 05:25:32 +00002551 } else if (const ObjCObjectPointerType *ToPtrType =
2552 ToType->getAs<ObjCObjectPointerType>()) {
2553 if (const ObjCObjectPointerType *FromPtrType =
2554 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002555 // Objective-C++ conversions are always okay.
2556 // FIXME: We should have a different class of conversions for the
2557 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002558 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002559 return false;
John McCall9320b872011-09-09 05:25:32 +00002560 } else if (FromType->isBlockPointerType()) {
2561 Kind = CK_BlockPointerToObjCPointerCast;
2562 } else {
2563 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002564 }
John McCall9320b872011-09-09 05:25:32 +00002565 } else if (ToType->isBlockPointerType()) {
2566 if (!FromType->isBlockPointerType())
2567 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002568 }
John McCall8cb679e2010-11-15 09:13:47 +00002569
2570 // We shouldn't fall into this case unless it's valid for other
2571 // reasons.
2572 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2573 Kind = CK_NullToPointer;
2574
Douglas Gregor39c16d42008-10-24 04:54:22 +00002575 return false;
2576}
2577
Sebastian Redl72b597d2009-01-25 19:43:20 +00002578/// IsMemberPointerConversion - Determines whether the conversion of the
2579/// expression From, which has the (possibly adjusted) type FromType, can be
2580/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2581/// If so, returns true and places the converted type (that might differ from
2582/// ToType in its cv-qualifiers at some level) into ConvertedType.
2583bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002584 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002585 bool InOverloadResolution,
2586 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002587 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002588 if (!ToTypePtr)
2589 return false;
2590
2591 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002592 if (From->isNullPointerConstant(Context,
2593 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2594 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002595 ConvertedType = ToType;
2596 return true;
2597 }
2598
2599 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002600 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002601 if (!FromTypePtr)
2602 return false;
2603
2604 // A pointer to member of B can be converted to a pointer to member of D,
2605 // where D is derived from B (C++ 4.11p2).
2606 QualType FromClass(FromTypePtr->getClass(), 0);
2607 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002608
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002609 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2610 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2611 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002612 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2613 ToClass.getTypePtr());
2614 return true;
2615 }
2616
2617 return false;
2618}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002619
Sebastian Redl72b597d2009-01-25 19:43:20 +00002620/// CheckMemberPointerConversion - Check the member pointer conversion from the
2621/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002622/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002623/// for which IsMemberPointerConversion has already returned true. It returns
2624/// true and produces a diagnostic if there was an error, or returns false
2625/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002626bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002627 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002628 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002629 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002630 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002631 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002632 if (!FromPtrType) {
2633 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002635 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002636 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002637 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002638 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002639 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002640
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002641 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002642 assert(ToPtrType && "No member pointer cast has a target type "
2643 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002644
Sebastian Redled8f2002009-01-28 18:33:18 +00002645 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2646 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002647
Sebastian Redled8f2002009-01-28 18:33:18 +00002648 // FIXME: What about dependent types?
2649 assert(FromClass->isRecordType() && "Pointer into non-class.");
2650 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002651
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002652 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002653 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002654 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2655 assert(DerivationOkay &&
2656 "Should not have been called if derivation isn't OK.");
2657 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002658
Sebastian Redled8f2002009-01-28 18:33:18 +00002659 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2660 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002661 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2662 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2663 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2664 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002665 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002666
Douglas Gregor89ee6822009-02-28 01:32:25 +00002667 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002668 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2669 << FromClass << ToClass << QualType(VBase, 0)
2670 << From->getSourceRange();
2671 return true;
2672 }
2673
John McCall5b0829a2010-02-10 09:31:12 +00002674 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002675 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2676 Paths.front(),
2677 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002678
Anders Carlssond7923c62009-08-22 23:33:40 +00002679 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002680 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002681 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002682 return false;
2683}
2684
Douglas Gregor9a657932008-10-21 23:43:52 +00002685/// IsQualificationConversion - Determines whether the conversion from
2686/// an rvalue of type FromType to ToType is a qualification conversion
2687/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002688///
2689/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2690/// when the qualification conversion involves a change in the Objective-C
2691/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002692bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002694 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002695 FromType = Context.getCanonicalType(FromType);
2696 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002697 ObjCLifetimeConversion = false;
2698
Douglas Gregor9a657932008-10-21 23:43:52 +00002699 // If FromType and ToType are the same type, this is not a
2700 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002701 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002702 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002703
Douglas Gregor9a657932008-10-21 23:43:52 +00002704 // (C++ 4.4p4):
2705 // A conversion can add cv-qualifiers at levels other than the first
2706 // in multi-level pointers, subject to the following rules: [...]
2707 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002708 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002709 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002710 // Within each iteration of the loop, we check the qualifiers to
2711 // determine if this still looks like a qualification
2712 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002713 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002714 // until there are no more pointers or pointers-to-members left to
2715 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002716 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002717
Douglas Gregor90609aa2011-04-25 18:40:17 +00002718 Qualifiers FromQuals = FromType.getQualifiers();
2719 Qualifiers ToQuals = ToType.getQualifiers();
2720
John McCall31168b02011-06-15 23:02:42 +00002721 // Objective-C ARC:
2722 // Check Objective-C lifetime conversions.
2723 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2724 UnwrappedAnyPointer) {
2725 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2726 ObjCLifetimeConversion = true;
2727 FromQuals.removeObjCLifetime();
2728 ToQuals.removeObjCLifetime();
2729 } else {
2730 // Qualification conversions cannot cast between different
2731 // Objective-C lifetime qualifiers.
2732 return false;
2733 }
2734 }
2735
Douglas Gregorf30053d2011-05-08 06:09:53 +00002736 // Allow addition/removal of GC attributes but not changing GC attributes.
2737 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2738 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2739 FromQuals.removeObjCGCAttr();
2740 ToQuals.removeObjCGCAttr();
2741 }
2742
Douglas Gregor9a657932008-10-21 23:43:52 +00002743 // -- for every j > 0, if const is in cv 1,j then const is in cv
2744 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002745 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002746 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002747
Douglas Gregor9a657932008-10-21 23:43:52 +00002748 // -- if the cv 1,j and cv 2,j are different, then const is in
2749 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002750 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002751 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002752 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregor9a657932008-10-21 23:43:52 +00002754 // Keep track of whether all prior cv-qualifiers in the "to" type
2755 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002756 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002757 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002758 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002759
2760 // We are left with FromType and ToType being the pointee types
2761 // after unwrapping the original FromType and ToType the same number
2762 // of types. If we unwrapped any pointers, and if FromType and
2763 // ToType have the same unqualified type (since we checked
2764 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002765 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002766}
2767
Sebastian Redle5417162012-03-27 18:33:03 +00002768static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2769 CXXConstructorDecl *Constructor,
2770 QualType Type) {
2771 const FunctionProtoType *CtorType =
2772 Constructor->getType()->getAs<FunctionProtoType>();
2773 if (CtorType->getNumArgs() > 0) {
2774 QualType FirstArg = CtorType->getArgType(0);
2775 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2776 return true;
2777 }
2778 return false;
2779}
2780
Sebastian Redl82ace982012-02-11 23:51:08 +00002781static OverloadingResult
2782IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2783 CXXRecordDecl *To,
2784 UserDefinedConversionSequence &User,
2785 OverloadCandidateSet &CandidateSet,
2786 bool AllowExplicit) {
2787 DeclContext::lookup_iterator Con, ConEnd;
2788 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2789 Con != ConEnd; ++Con) {
2790 NamedDecl *D = *Con;
2791 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2792
2793 // Find the constructor (which may be a template).
2794 CXXConstructorDecl *Constructor = 0;
2795 FunctionTemplateDecl *ConstructorTmpl
2796 = dyn_cast<FunctionTemplateDecl>(D);
2797 if (ConstructorTmpl)
2798 Constructor
2799 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2800 else
2801 Constructor = cast<CXXConstructorDecl>(D);
2802
2803 bool Usable = !Constructor->isInvalidDecl() &&
2804 S.isInitListConstructor(Constructor) &&
2805 (AllowExplicit || !Constructor->isExplicit());
2806 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002807 // If the first argument is (a reference to) the target type,
2808 // suppress conversions.
2809 bool SuppressUserConversions =
2810 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002811 if (ConstructorTmpl)
2812 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2813 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002814 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002815 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002816 else
2817 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002818 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002819 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002820 }
2821 }
2822
2823 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2824
2825 OverloadCandidateSet::iterator Best;
2826 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2827 case OR_Success: {
2828 // Record the standard conversion we used and the conversion function.
2829 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2830 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2831
2832 QualType ThisType = Constructor->getThisType(S.Context);
2833 // Initializer lists don't have conversions as such.
2834 User.Before.setAsIdentityConversion();
2835 User.HadMultipleCandidates = HadMultipleCandidates;
2836 User.ConversionFunction = Constructor;
2837 User.FoundConversionFunction = Best->FoundDecl;
2838 User.After.setAsIdentityConversion();
2839 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2840 User.After.setAllToTypes(ToType);
2841 return OR_Success;
2842 }
2843
2844 case OR_No_Viable_Function:
2845 return OR_No_Viable_Function;
2846 case OR_Deleted:
2847 return OR_Deleted;
2848 case OR_Ambiguous:
2849 return OR_Ambiguous;
2850 }
2851
2852 llvm_unreachable("Invalid OverloadResult!");
2853}
2854
Douglas Gregor576e98c2009-01-30 23:27:23 +00002855/// Determines whether there is a user-defined conversion sequence
2856/// (C++ [over.ics.user]) that converts expression From to the type
2857/// ToType. If such a conversion exists, User will contain the
2858/// user-defined conversion sequence that performs such a conversion
2859/// and this routine will return true. Otherwise, this routine returns
2860/// false and User is unspecified.
2861///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002862/// \param AllowExplicit true if the conversion should consider C++0x
2863/// "explicit" conversion functions as well as non-explicit conversion
2864/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002865static OverloadingResult
2866IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002867 UserDefinedConversionSequence &User,
2868 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002869 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002870 // Whether we will only visit constructors.
2871 bool ConstructorsOnly = false;
2872
2873 // If the type we are conversion to is a class type, enumerate its
2874 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002875 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002876 // C++ [over.match.ctor]p1:
2877 // When objects of class type are direct-initialized (8.5), or
2878 // copy-initialized from an expression of the same or a
2879 // derived class type (8.5), overload resolution selects the
2880 // constructor. [...] For copy-initialization, the candidate
2881 // functions are all the converting constructors (12.3.1) of
2882 // that class. The argument list is the expression-list within
2883 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002884 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002885 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002886 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002887 ConstructorsOnly = true;
2888
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002889 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2890 // RequireCompleteType may have returned true due to some invalid decl
2891 // during template instantiation, but ToType may be complete enough now
2892 // to try to recover.
2893 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002894 // We're not going to find any constructors.
2895 } else if (CXXRecordDecl *ToRecordDecl
2896 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002897
2898 Expr **Args = &From;
2899 unsigned NumArgs = 1;
2900 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002901 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002902 // But first, see if there is an init-list-contructor that will work.
2903 OverloadingResult Result = IsInitializerListConstructorConversion(
2904 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2905 if (Result != OR_No_Viable_Function)
2906 return Result;
2907 // Never mind.
2908 CandidateSet.clear();
2909
2910 // If we're list-initializing, we pass the individual elements as
2911 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002912 Args = InitList->getInits();
2913 NumArgs = InitList->getNumInits();
2914 ListInitializing = true;
2915 }
2916
Douglas Gregor89ee6822009-02-28 01:32:25 +00002917 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002918 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002919 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002920 NamedDecl *D = *Con;
2921 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2922
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002923 // Find the constructor (which may be a template).
2924 CXXConstructorDecl *Constructor = 0;
2925 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002926 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002927 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002928 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002929 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2930 else
John McCalla0296f72010-03-19 07:35:19 +00002931 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002932
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002933 bool Usable = !Constructor->isInvalidDecl();
2934 if (ListInitializing)
2935 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2936 else
2937 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2938 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00002939 bool SuppressUserConversions = !ConstructorsOnly;
2940 if (SuppressUserConversions && ListInitializing) {
2941 SuppressUserConversions = false;
2942 if (NumArgs == 1) {
2943 // If the first argument is (a reference to) the target type,
2944 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00002945 SuppressUserConversions = isFirstArgumentCompatibleWithType(
2946 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00002947 }
2948 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002949 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002950 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2951 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002952 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002953 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002954 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002955 // Allow one user-defined conversion when user specifies a
2956 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002957 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002958 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002959 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002960 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002961 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002962 }
2963 }
2964
Douglas Gregor5ab11652010-04-17 22:01:05 +00002965 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002966 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002967 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2968 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002969 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002970 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002971 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002972 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002973 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2974 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002975 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002976 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002977 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002978 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002979 DeclAccessPair FoundDecl = I.getPair();
2980 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002981 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2982 if (isa<UsingShadowDecl>(D))
2983 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2984
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002985 CXXConversionDecl *Conv;
2986 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002987 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2988 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002989 else
John McCallda4458e2010-03-31 01:36:47 +00002990 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002991
2992 if (AllowExplicit || !Conv->isExplicit()) {
2993 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002994 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2995 ActingContext, From, ToType,
2996 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002997 else
John McCall5c32be02010-08-24 20:38:10 +00002998 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2999 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003000 }
3001 }
3002 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003003 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003004
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003005 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3006
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003007 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003008 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003009 case OR_Success:
3010 // Record the standard conversion we used and the conversion function.
3011 if (CXXConstructorDecl *Constructor
3012 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003013 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00003014
John McCall5c32be02010-08-24 20:38:10 +00003015 // C++ [over.ics.user]p1:
3016 // If the user-defined conversion is specified by a
3017 // constructor (12.3.1), the initial standard conversion
3018 // sequence converts the source type to the type required by
3019 // the argument of the constructor.
3020 //
3021 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003022 if (isa<InitListExpr>(From)) {
3023 // Initializer lists don't have conversions as such.
3024 User.Before.setAsIdentityConversion();
3025 } else {
3026 if (Best->Conversions[0].isEllipsis())
3027 User.EllipsisConversion = true;
3028 else {
3029 User.Before = Best->Conversions[0].Standard;
3030 User.EllipsisConversion = false;
3031 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003032 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003033 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003034 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003035 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003036 User.After.setAsIdentityConversion();
3037 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3038 User.After.setAllToTypes(ToType);
3039 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003040 }
3041 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003042 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003043 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003044
John McCall5c32be02010-08-24 20:38:10 +00003045 // C++ [over.ics.user]p1:
3046 //
3047 // [...] If the user-defined conversion is specified by a
3048 // conversion function (12.3.2), the initial standard
3049 // conversion sequence converts the source type to the
3050 // implicit object parameter of the conversion function.
3051 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003052 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003053 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003054 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003055 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003056
John McCall5c32be02010-08-24 20:38:10 +00003057 // C++ [over.ics.user]p2:
3058 // The second standard conversion sequence converts the
3059 // result of the user-defined conversion to the target type
3060 // for the sequence. Since an implicit conversion sequence
3061 // is an initialization, the special rules for
3062 // initialization by user-defined conversion apply when
3063 // selecting the best user-defined conversion for a
3064 // user-defined conversion sequence (see 13.3.3 and
3065 // 13.3.3.1).
3066 User.After = Best->FinalConversion;
3067 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003068 }
David Blaikie8a40f702012-01-17 06:56:22 +00003069 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003070
John McCall5c32be02010-08-24 20:38:10 +00003071 case OR_No_Viable_Function:
3072 return OR_No_Viable_Function;
3073 case OR_Deleted:
3074 // No conversion here! We're done.
3075 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076
John McCall5c32be02010-08-24 20:38:10 +00003077 case OR_Ambiguous:
3078 return OR_Ambiguous;
3079 }
3080
David Blaikie8a40f702012-01-17 06:56:22 +00003081 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003082}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003084bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003085Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003086 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003087 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003088 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003089 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003090 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003091 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003092 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003093 diag::err_typecheck_ambiguous_condition)
3094 << From->getType() << ToType << From->getSourceRange();
3095 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003096 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003097 diag::err_typecheck_nonviable_condition)
3098 << From->getType() << ToType << From->getSourceRange();
3099 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003100 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003101 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003102 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003103}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003104
Douglas Gregor2837aa22012-02-22 17:32:19 +00003105/// \brief Compare the user-defined conversion functions or constructors
3106/// of two user-defined conversion sequences to determine whether any ordering
3107/// is possible.
3108static ImplicitConversionSequence::CompareKind
3109compareConversionFunctions(Sema &S,
3110 FunctionDecl *Function1,
3111 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003112 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003113 return ImplicitConversionSequence::Indistinguishable;
3114
3115 // Objective-C++:
3116 // If both conversion functions are implicitly-declared conversions from
3117 // a lambda closure type to a function pointer and a block pointer,
3118 // respectively, always prefer the conversion to a function pointer,
3119 // because the function pointer is more lightweight and is more likely
3120 // to keep code working.
3121 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3122 if (!Conv1)
3123 return ImplicitConversionSequence::Indistinguishable;
3124
3125 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3126 if (!Conv2)
3127 return ImplicitConversionSequence::Indistinguishable;
3128
3129 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3130 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3131 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3132 if (Block1 != Block2)
3133 return Block1? ImplicitConversionSequence::Worse
3134 : ImplicitConversionSequence::Better;
3135 }
3136
3137 return ImplicitConversionSequence::Indistinguishable;
3138}
3139
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003140/// CompareImplicitConversionSequences - Compare two implicit
3141/// conversion sequences to determine whether one is better than the
3142/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003143static ImplicitConversionSequence::CompareKind
3144CompareImplicitConversionSequences(Sema &S,
3145 const ImplicitConversionSequence& ICS1,
3146 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003147{
3148 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3149 // conversion sequences (as defined in 13.3.3.1)
3150 // -- a standard conversion sequence (13.3.3.1.1) is a better
3151 // conversion sequence than a user-defined conversion sequence or
3152 // an ellipsis conversion sequence, and
3153 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3154 // conversion sequence than an ellipsis conversion sequence
3155 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003156 //
John McCall0d1da222010-01-12 00:44:57 +00003157 // C++0x [over.best.ics]p10:
3158 // For the purpose of ranking implicit conversion sequences as
3159 // described in 13.3.3.2, the ambiguous conversion sequence is
3160 // treated as a user-defined sequence that is indistinguishable
3161 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003162 if (ICS1.getKindRank() < ICS2.getKindRank())
3163 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003164 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003165 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003166
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003167 // The following checks require both conversion sequences to be of
3168 // the same kind.
3169 if (ICS1.getKind() != ICS2.getKind())
3170 return ImplicitConversionSequence::Indistinguishable;
3171
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003172 ImplicitConversionSequence::CompareKind Result =
3173 ImplicitConversionSequence::Indistinguishable;
3174
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003175 // Two implicit conversion sequences of the same form are
3176 // indistinguishable conversion sequences unless one of the
3177 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003178 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003179 Result = CompareStandardConversionSequences(S,
3180 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003181 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003182 // User-defined conversion sequence U1 is a better conversion
3183 // sequence than another user-defined conversion sequence U2 if
3184 // they contain the same user-defined conversion function or
3185 // constructor and if the second standard conversion sequence of
3186 // U1 is better than the second standard conversion sequence of
3187 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003188 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003189 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003190 Result = CompareStandardConversionSequences(S,
3191 ICS1.UserDefined.After,
3192 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003193 else
3194 Result = compareConversionFunctions(S,
3195 ICS1.UserDefined.ConversionFunction,
3196 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003197 }
3198
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003199 // List-initialization sequence L1 is a better conversion sequence than
3200 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3201 // for some X and L2 does not.
3202 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003203 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003204 ICS1.isListInitializationSequence() &&
3205 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003206 if (ICS1.isStdInitializerListElement() &&
3207 !ICS2.isStdInitializerListElement())
3208 return ImplicitConversionSequence::Better;
3209 if (!ICS1.isStdInitializerListElement() &&
3210 ICS2.isStdInitializerListElement())
3211 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003212 }
3213
3214 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003215}
3216
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003217static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3218 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3219 Qualifiers Quals;
3220 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003223
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003224 return Context.hasSameUnqualifiedType(T1, T2);
3225}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003226
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003227// Per 13.3.3.2p3, compare the given standard conversion sequences to
3228// determine if one is a proper subset of the other.
3229static ImplicitConversionSequence::CompareKind
3230compareStandardConversionSubsets(ASTContext &Context,
3231 const StandardConversionSequence& SCS1,
3232 const StandardConversionSequence& SCS2) {
3233 ImplicitConversionSequence::CompareKind Result
3234 = ImplicitConversionSequence::Indistinguishable;
3235
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003237 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003238 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3239 return ImplicitConversionSequence::Better;
3240 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3241 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003243 if (SCS1.Second != SCS2.Second) {
3244 if (SCS1.Second == ICK_Identity)
3245 Result = ImplicitConversionSequence::Better;
3246 else if (SCS2.Second == ICK_Identity)
3247 Result = ImplicitConversionSequence::Worse;
3248 else
3249 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003250 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003251 return ImplicitConversionSequence::Indistinguishable;
3252
3253 if (SCS1.Third == SCS2.Third) {
3254 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3255 : ImplicitConversionSequence::Indistinguishable;
3256 }
3257
3258 if (SCS1.Third == ICK_Identity)
3259 return Result == ImplicitConversionSequence::Worse
3260 ? ImplicitConversionSequence::Indistinguishable
3261 : ImplicitConversionSequence::Better;
3262
3263 if (SCS2.Third == ICK_Identity)
3264 return Result == ImplicitConversionSequence::Better
3265 ? ImplicitConversionSequence::Indistinguishable
3266 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003268 return ImplicitConversionSequence::Indistinguishable;
3269}
3270
Douglas Gregore696ebb2011-01-26 14:52:12 +00003271/// \brief Determine whether one of the given reference bindings is better
3272/// than the other based on what kind of bindings they are.
3273static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3274 const StandardConversionSequence &SCS2) {
3275 // C++0x [over.ics.rank]p3b4:
3276 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3277 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003279 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003281 // reference*.
3282 //
3283 // FIXME: Rvalue references. We're going rogue with the above edits,
3284 // because the semantics in the current C++0x working paper (N3225 at the
3285 // time of this writing) break the standard definition of std::forward
3286 // and std::reference_wrapper when dealing with references to functions.
3287 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003288 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3289 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3290 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291
Douglas Gregore696ebb2011-01-26 14:52:12 +00003292 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3293 SCS2.IsLvalueReference) ||
3294 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3295 !SCS2.IsLvalueReference);
3296}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003298/// CompareStandardConversionSequences - Compare two standard
3299/// conversion sequences to determine whether one is better than the
3300/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003301static ImplicitConversionSequence::CompareKind
3302CompareStandardConversionSequences(Sema &S,
3303 const StandardConversionSequence& SCS1,
3304 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003305{
3306 // Standard conversion sequence S1 is a better conversion sequence
3307 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3308
3309 // -- S1 is a proper subsequence of S2 (comparing the conversion
3310 // sequences in the canonical form defined by 13.3.3.1.1,
3311 // excluding any Lvalue Transformation; the identity conversion
3312 // sequence is considered to be a subsequence of any
3313 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003314 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003315 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003316 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003317
3318 // -- the rank of S1 is better than the rank of S2 (by the rules
3319 // defined below), or, if not that,
3320 ImplicitConversionRank Rank1 = SCS1.getRank();
3321 ImplicitConversionRank Rank2 = SCS2.getRank();
3322 if (Rank1 < Rank2)
3323 return ImplicitConversionSequence::Better;
3324 else if (Rank2 < Rank1)
3325 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003326
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003327 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3328 // are indistinguishable unless one of the following rules
3329 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003330
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003331 // A conversion that is not a conversion of a pointer, or
3332 // pointer to member, to bool is better than another conversion
3333 // that is such a conversion.
3334 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3335 return SCS2.isPointerConversionToBool()
3336 ? ImplicitConversionSequence::Better
3337 : ImplicitConversionSequence::Worse;
3338
Douglas Gregor5c407d92008-10-23 00:40:37 +00003339 // C++ [over.ics.rank]p4b2:
3340 //
3341 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003342 // conversion of B* to A* is better than conversion of B* to
3343 // void*, and conversion of A* to void* is better than conversion
3344 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003345 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003346 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003347 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003348 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003349 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3350 // Exactly one of the conversion sequences is a conversion to
3351 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003352 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3353 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003354 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3355 // Neither conversion sequence converts to a void pointer; compare
3356 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003357 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003358 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003359 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003360 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3361 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003362 // Both conversion sequences are conversions to void
3363 // pointers. Compare the source types to determine if there's an
3364 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003365 QualType FromType1 = SCS1.getFromType();
3366 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003367
3368 // Adjust the types we're converting from via the array-to-pointer
3369 // conversion, if we need to.
3370 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003371 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003372 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003373 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003374
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003375 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3376 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003377
John McCall5c32be02010-08-24 20:38:10 +00003378 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003379 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003380 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003381 return ImplicitConversionSequence::Worse;
3382
3383 // Objective-C++: If one interface is more specific than the
3384 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003385 const ObjCObjectPointerType* FromObjCPtr1
3386 = FromType1->getAs<ObjCObjectPointerType>();
3387 const ObjCObjectPointerType* FromObjCPtr2
3388 = FromType2->getAs<ObjCObjectPointerType>();
3389 if (FromObjCPtr1 && FromObjCPtr2) {
3390 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3391 FromObjCPtr2);
3392 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3393 FromObjCPtr1);
3394 if (AssignLeft != AssignRight) {
3395 return AssignLeft? ImplicitConversionSequence::Better
3396 : ImplicitConversionSequence::Worse;
3397 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003398 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003399 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003400
3401 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3402 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003403 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003404 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003405 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003406
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003407 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003408 // Check for a better reference binding based on the kind of bindings.
3409 if (isBetterReferenceBindingKind(SCS1, SCS2))
3410 return ImplicitConversionSequence::Better;
3411 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3412 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Sebastian Redlb28b4072009-03-22 23:49:27 +00003414 // C++ [over.ics.rank]p3b4:
3415 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3416 // which the references refer are the same type except for
3417 // top-level cv-qualifiers, and the type to which the reference
3418 // initialized by S2 refers is more cv-qualified than the type
3419 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003420 QualType T1 = SCS1.getToType(2);
3421 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003422 T1 = S.Context.getCanonicalType(T1);
3423 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003424 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003425 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3426 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003427 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003428 // Objective-C++ ARC: If the references refer to objects with different
3429 // lifetimes, prefer bindings that don't change lifetime.
3430 if (SCS1.ObjCLifetimeConversionBinding !=
3431 SCS2.ObjCLifetimeConversionBinding) {
3432 return SCS1.ObjCLifetimeConversionBinding
3433 ? ImplicitConversionSequence::Worse
3434 : ImplicitConversionSequence::Better;
3435 }
3436
Chandler Carruth8e543b32010-12-12 08:17:55 +00003437 // If the type is an array type, promote the element qualifiers to the
3438 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003439 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003440 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003441 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003442 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003443 if (T2.isMoreQualifiedThan(T1))
3444 return ImplicitConversionSequence::Better;
3445 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003446 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003447 }
3448 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003449
Francois Pichet08d2fa02011-09-18 21:37:37 +00003450 // In Microsoft mode, prefer an integral conversion to a
3451 // floating-to-integral conversion if the integral conversion
3452 // is between types of the same size.
3453 // For example:
3454 // void f(float);
3455 // void f(int);
3456 // int main {
3457 // long a;
3458 // f(a);
3459 // }
3460 // Here, MSVC will call f(int) instead of generating a compile error
3461 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003462 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003463 SCS1.Second == ICK_Integral_Conversion &&
3464 SCS2.Second == ICK_Floating_Integral &&
3465 S.Context.getTypeSize(SCS1.getFromType()) ==
3466 S.Context.getTypeSize(SCS1.getToType(2)))
3467 return ImplicitConversionSequence::Better;
3468
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003469 return ImplicitConversionSequence::Indistinguishable;
3470}
3471
3472/// CompareQualificationConversions - Compares two standard conversion
3473/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003474/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3475ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003476CompareQualificationConversions(Sema &S,
3477 const StandardConversionSequence& SCS1,
3478 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003479 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003480 // -- S1 and S2 differ only in their qualification conversion and
3481 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3482 // cv-qualification signature of type T1 is a proper subset of
3483 // the cv-qualification signature of type T2, and S1 is not the
3484 // deprecated string literal array-to-pointer conversion (4.2).
3485 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3486 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3487 return ImplicitConversionSequence::Indistinguishable;
3488
3489 // FIXME: the example in the standard doesn't use a qualification
3490 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003491 QualType T1 = SCS1.getToType(2);
3492 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003493 T1 = S.Context.getCanonicalType(T1);
3494 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003495 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003496 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3497 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003498
3499 // If the types are the same, we won't learn anything by unwrapped
3500 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003501 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003502 return ImplicitConversionSequence::Indistinguishable;
3503
Chandler Carruth607f38e2009-12-29 07:16:59 +00003504 // If the type is an array type, promote the element qualifiers to the type
3505 // for comparison.
3506 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003507 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003508 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003509 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003510
Mike Stump11289f42009-09-09 15:08:12 +00003511 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003512 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003513
3514 // Objective-C++ ARC:
3515 // Prefer qualification conversions not involving a change in lifetime
3516 // to qualification conversions that do not change lifetime.
3517 if (SCS1.QualificationIncludesObjCLifetime !=
3518 SCS2.QualificationIncludesObjCLifetime) {
3519 Result = SCS1.QualificationIncludesObjCLifetime
3520 ? ImplicitConversionSequence::Worse
3521 : ImplicitConversionSequence::Better;
3522 }
3523
John McCall5c32be02010-08-24 20:38:10 +00003524 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003525 // Within each iteration of the loop, we check the qualifiers to
3526 // determine if this still looks like a qualification
3527 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003528 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003529 // until there are no more pointers or pointers-to-members left
3530 // to unwrap. This essentially mimics what
3531 // IsQualificationConversion does, but here we're checking for a
3532 // strict subset of qualifiers.
3533 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3534 // The qualifiers are the same, so this doesn't tell us anything
3535 // about how the sequences rank.
3536 ;
3537 else if (T2.isMoreQualifiedThan(T1)) {
3538 // T1 has fewer qualifiers, so it could be the better sequence.
3539 if (Result == ImplicitConversionSequence::Worse)
3540 // Neither has qualifiers that are a subset of the other's
3541 // qualifiers.
3542 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003543
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003544 Result = ImplicitConversionSequence::Better;
3545 } else if (T1.isMoreQualifiedThan(T2)) {
3546 // T2 has fewer qualifiers, so it could be the better sequence.
3547 if (Result == ImplicitConversionSequence::Better)
3548 // Neither has qualifiers that are a subset of the other's
3549 // qualifiers.
3550 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003551
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003552 Result = ImplicitConversionSequence::Worse;
3553 } else {
3554 // Qualifiers are disjoint.
3555 return ImplicitConversionSequence::Indistinguishable;
3556 }
3557
3558 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003559 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003560 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003561 }
3562
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003563 // Check that the winning standard conversion sequence isn't using
3564 // the deprecated string literal array to pointer conversion.
3565 switch (Result) {
3566 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003567 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003568 Result = ImplicitConversionSequence::Indistinguishable;
3569 break;
3570
3571 case ImplicitConversionSequence::Indistinguishable:
3572 break;
3573
3574 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003575 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003576 Result = ImplicitConversionSequence::Indistinguishable;
3577 break;
3578 }
3579
3580 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003581}
3582
Douglas Gregor5c407d92008-10-23 00:40:37 +00003583/// CompareDerivedToBaseConversions - Compares two standard conversion
3584/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003585/// various kinds of derived-to-base conversions (C++
3586/// [over.ics.rank]p4b3). As part of these checks, we also look at
3587/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003588ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003589CompareDerivedToBaseConversions(Sema &S,
3590 const StandardConversionSequence& SCS1,
3591 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003592 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003593 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003594 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003595 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003596
3597 // Adjust the types we're converting from via the array-to-pointer
3598 // conversion, if we need to.
3599 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003600 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003601 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003602 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003603
3604 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003605 FromType1 = S.Context.getCanonicalType(FromType1);
3606 ToType1 = S.Context.getCanonicalType(ToType1);
3607 FromType2 = S.Context.getCanonicalType(FromType2);
3608 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003609
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003610 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003611 //
3612 // If class B is derived directly or indirectly from class A and
3613 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003614 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003615 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003616 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003617 SCS2.Second == ICK_Pointer_Conversion &&
3618 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3619 FromType1->isPointerType() && FromType2->isPointerType() &&
3620 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003621 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003622 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003623 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003624 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003625 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003626 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003627 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003628 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003629
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003630 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003631 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003632 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003633 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003634 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003635 return ImplicitConversionSequence::Worse;
3636 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003637
3638 // -- conversion of B* to A* is better than conversion of C* to A*,
3639 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003640 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003641 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003642 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003643 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003644 }
3645 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3646 SCS2.Second == ICK_Pointer_Conversion) {
3647 const ObjCObjectPointerType *FromPtr1
3648 = FromType1->getAs<ObjCObjectPointerType>();
3649 const ObjCObjectPointerType *FromPtr2
3650 = FromType2->getAs<ObjCObjectPointerType>();
3651 const ObjCObjectPointerType *ToPtr1
3652 = ToType1->getAs<ObjCObjectPointerType>();
3653 const ObjCObjectPointerType *ToPtr2
3654 = ToType2->getAs<ObjCObjectPointerType>();
3655
3656 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3657 // Apply the same conversion ranking rules for Objective-C pointer types
3658 // that we do for C++ pointers to class types. However, we employ the
3659 // Objective-C pseudo-subtyping relationship used for assignment of
3660 // Objective-C pointer types.
3661 bool FromAssignLeft
3662 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3663 bool FromAssignRight
3664 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3665 bool ToAssignLeft
3666 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3667 bool ToAssignRight
3668 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3669
3670 // A conversion to an a non-id object pointer type or qualified 'id'
3671 // type is better than a conversion to 'id'.
3672 if (ToPtr1->isObjCIdType() &&
3673 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3674 return ImplicitConversionSequence::Worse;
3675 if (ToPtr2->isObjCIdType() &&
3676 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3677 return ImplicitConversionSequence::Better;
3678
3679 // A conversion to a non-id object pointer type is better than a
3680 // conversion to a qualified 'id' type
3681 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3682 return ImplicitConversionSequence::Worse;
3683 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3684 return ImplicitConversionSequence::Better;
3685
3686 // A conversion to an a non-Class object pointer type or qualified 'Class'
3687 // type is better than a conversion to 'Class'.
3688 if (ToPtr1->isObjCClassType() &&
3689 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3690 return ImplicitConversionSequence::Worse;
3691 if (ToPtr2->isObjCClassType() &&
3692 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3693 return ImplicitConversionSequence::Better;
3694
3695 // A conversion to a non-Class object pointer type is better than a
3696 // conversion to a qualified 'Class' type.
3697 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3698 return ImplicitConversionSequence::Worse;
3699 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3700 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregor058d3de2011-01-31 18:51:41 +00003702 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3703 if (S.Context.hasSameType(FromType1, FromType2) &&
3704 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3705 (ToAssignLeft != ToAssignRight))
3706 return ToAssignLeft? ImplicitConversionSequence::Worse
3707 : ImplicitConversionSequence::Better;
3708
3709 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3710 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3711 (FromAssignLeft != FromAssignRight))
3712 return FromAssignLeft? ImplicitConversionSequence::Better
3713 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003714 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003715 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003716
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003717 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003718 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3719 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3720 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003722 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003724 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003726 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003728 ToType2->getAs<MemberPointerType>();
3729 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3730 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3731 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3732 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3733 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3734 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3735 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3736 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003737 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003738 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003739 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003740 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003741 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003742 return ImplicitConversionSequence::Better;
3743 }
3744 // conversion of B::* to C::* is better than conversion of A::* to C::*
3745 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003746 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003747 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003748 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003749 return ImplicitConversionSequence::Worse;
3750 }
3751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
Douglas Gregor5ab11652010-04-17 22:01:05 +00003753 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003754 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003755 // -- binding of an expression of type C to a reference of type
3756 // B& is better than binding an expression of type C to a
3757 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003758 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3759 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3760 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003761 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003762 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003763 return ImplicitConversionSequence::Worse;
3764 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003765
Douglas Gregor2fe98832008-11-03 19:09:14 +00003766 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003767 // -- binding of an expression of type B to a reference of type
3768 // A& is better than binding an expression of type C to a
3769 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003770 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3771 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3772 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003773 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003774 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003775 return ImplicitConversionSequence::Worse;
3776 }
3777 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003778
Douglas Gregor5c407d92008-10-23 00:40:37 +00003779 return ImplicitConversionSequence::Indistinguishable;
3780}
3781
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003782/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3783/// determine whether they are reference-related,
3784/// reference-compatible, reference-compatible with added
3785/// qualification, or incompatible, for use in C++ initialization by
3786/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3787/// type, and the first type (T1) is the pointee type of the reference
3788/// type being initialized.
3789Sema::ReferenceCompareResult
3790Sema::CompareReferenceRelationship(SourceLocation Loc,
3791 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003792 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003793 bool &ObjCConversion,
3794 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003795 assert(!OrigT1->isReferenceType() &&
3796 "T1 must be the pointee type of the reference type");
3797 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3798
3799 QualType T1 = Context.getCanonicalType(OrigT1);
3800 QualType T2 = Context.getCanonicalType(OrigT2);
3801 Qualifiers T1Quals, T2Quals;
3802 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3803 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3804
3805 // C++ [dcl.init.ref]p4:
3806 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3807 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3808 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003809 DerivedToBase = false;
3810 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003811 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003812 if (UnqualT1 == UnqualT2) {
3813 // Nothing to do.
3814 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003815 IsDerivedFrom(UnqualT2, UnqualT1))
3816 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003817 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3818 UnqualT2->isObjCObjectOrInterfaceType() &&
3819 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3820 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003821 else
3822 return Ref_Incompatible;
3823
3824 // At this point, we know that T1 and T2 are reference-related (at
3825 // least).
3826
3827 // If the type is an array type, promote the element qualifiers to the type
3828 // for comparison.
3829 if (isa<ArrayType>(T1) && T1Quals)
3830 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3831 if (isa<ArrayType>(T2) && T2Quals)
3832 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3833
3834 // C++ [dcl.init.ref]p4:
3835 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3836 // reference-related to T2 and cv1 is the same cv-qualification
3837 // as, or greater cv-qualification than, cv2. For purposes of
3838 // overload resolution, cases for which cv1 is greater
3839 // cv-qualification than cv2 are identified as
3840 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003841 //
3842 // Note that we also require equivalence of Objective-C GC and address-space
3843 // qualifiers when performing these computations, so that e.g., an int in
3844 // address space 1 is not reference-compatible with an int in address
3845 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003846 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3847 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3848 T1Quals.removeObjCLifetime();
3849 T2Quals.removeObjCLifetime();
3850 ObjCLifetimeConversion = true;
3851 }
3852
Douglas Gregord517d552011-04-28 17:56:11 +00003853 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003854 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003855 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003856 return Ref_Compatible_With_Added_Qualification;
3857 else
3858 return Ref_Related;
3859}
3860
Douglas Gregor836a7e82010-08-11 02:15:33 +00003861/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003862/// with DeclType. Return true if something definite is found.
3863static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003864FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3865 QualType DeclType, SourceLocation DeclLoc,
3866 Expr *Init, QualType T2, bool AllowRvalues,
3867 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003868 assert(T2->isRecordType() && "Can only find conversions of record types.");
3869 CXXRecordDecl *T2RecordDecl
3870 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3871
3872 OverloadCandidateSet CandidateSet(DeclLoc);
3873 const UnresolvedSetImpl *Conversions
3874 = T2RecordDecl->getVisibleConversionFunctions();
3875 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3876 E = Conversions->end(); I != E; ++I) {
3877 NamedDecl *D = *I;
3878 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3879 if (isa<UsingShadowDecl>(D))
3880 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3881
3882 FunctionTemplateDecl *ConvTemplate
3883 = dyn_cast<FunctionTemplateDecl>(D);
3884 CXXConversionDecl *Conv;
3885 if (ConvTemplate)
3886 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3887 else
3888 Conv = cast<CXXConversionDecl>(D);
3889
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003891 // explicit conversions, skip it.
3892 if (!AllowExplicit && Conv->isExplicit())
3893 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894
Douglas Gregor836a7e82010-08-11 02:15:33 +00003895 if (AllowRvalues) {
3896 bool DerivedToBase = false;
3897 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003898 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003899
3900 // If we are initializing an rvalue reference, don't permit conversion
3901 // functions that return lvalues.
3902 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3903 const ReferenceType *RefType
3904 = Conv->getConversionType()->getAs<LValueReferenceType>();
3905 if (RefType && !RefType->getPointeeType()->isFunctionType())
3906 continue;
3907 }
3908
Douglas Gregor836a7e82010-08-11 02:15:33 +00003909 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003910 S.CompareReferenceRelationship(
3911 DeclLoc,
3912 Conv->getConversionType().getNonReferenceType()
3913 .getUnqualifiedType(),
3914 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003915 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003916 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003917 continue;
3918 } else {
3919 // If the conversion function doesn't return a reference type,
3920 // it can't be considered for this conversion. An rvalue reference
3921 // is only acceptable if its referencee is a function type.
3922
3923 const ReferenceType *RefType =
3924 Conv->getConversionType()->getAs<ReferenceType>();
3925 if (!RefType ||
3926 (!RefType->isLValueReferenceType() &&
3927 !RefType->getPointeeType()->isFunctionType()))
3928 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003929 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930
Douglas Gregor836a7e82010-08-11 02:15:33 +00003931 if (ConvTemplate)
3932 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003933 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003934 else
3935 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003936 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003937 }
3938
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003939 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3940
Sebastian Redld92badf2010-06-30 18:13:39 +00003941 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003942 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003943 case OR_Success:
3944 // C++ [over.ics.ref]p1:
3945 //
3946 // [...] If the parameter binds directly to the result of
3947 // applying a conversion function to the argument
3948 // expression, the implicit conversion sequence is a
3949 // user-defined conversion sequence (13.3.3.1.2), with the
3950 // second standard conversion sequence either an identity
3951 // conversion or, if the conversion function returns an
3952 // entity of a type that is a derived class of the parameter
3953 // type, a derived-to-base Conversion.
3954 if (!Best->FinalConversion.DirectBinding)
3955 return false;
3956
Chandler Carruth30141632011-02-25 19:41:05 +00003957 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003958 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003959 ICS.setUserDefined();
3960 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3961 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003962 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003963 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003964 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003965 ICS.UserDefined.EllipsisConversion = false;
3966 assert(ICS.UserDefined.After.ReferenceBinding &&
3967 ICS.UserDefined.After.DirectBinding &&
3968 "Expected a direct reference binding!");
3969 return true;
3970
3971 case OR_Ambiguous:
3972 ICS.setAmbiguous();
3973 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3974 Cand != CandidateSet.end(); ++Cand)
3975 if (Cand->Viable)
3976 ICS.Ambiguous.addConversion(Cand->Function);
3977 return true;
3978
3979 case OR_No_Viable_Function:
3980 case OR_Deleted:
3981 // There was no suitable conversion, or we found a deleted
3982 // conversion; continue with other checks.
3983 return false;
3984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
David Blaikie8a40f702012-01-17 06:56:22 +00003986 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00003987}
3988
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003989/// \brief Compute an implicit conversion sequence for reference
3990/// initialization.
3991static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003992TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003993 SourceLocation DeclLoc,
3994 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003995 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003996 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3997
3998 // Most paths end in a failed conversion.
3999 ImplicitConversionSequence ICS;
4000 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4001
4002 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4003 QualType T2 = Init->getType();
4004
4005 // If the initializer is the address of an overloaded function, try
4006 // to resolve the overloaded function. If all goes well, T2 is the
4007 // type of the resulting function.
4008 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4009 DeclAccessPair Found;
4010 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4011 false, Found))
4012 T2 = Fn->getType();
4013 }
4014
4015 // Compute some basic properties of the types and the initializer.
4016 bool isRValRef = DeclType->isRValueReferenceType();
4017 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004018 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004019 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004020 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004021 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004022 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004023 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004024
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004025
Sebastian Redld92badf2010-06-30 18:13:39 +00004026 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004027 // A reference to type "cv1 T1" is initialized by an expression
4028 // of type "cv2 T2" as follows:
4029
Sebastian Redld92badf2010-06-30 18:13:39 +00004030 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004031 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004032 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4033 // reference-compatible with "cv2 T2," or
4034 //
4035 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4036 if (InitCategory.isLValue() &&
4037 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004038 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004039 // When a parameter of reference type binds directly (8.5.3)
4040 // to an argument expression, the implicit conversion sequence
4041 // is the identity conversion, unless the argument expression
4042 // has a type that is a derived class of the parameter type,
4043 // in which case the implicit conversion sequence is a
4044 // derived-to-base Conversion (13.3.3.1).
4045 ICS.setStandard();
4046 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004047 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4048 : ObjCConversion? ICK_Compatible_Conversion
4049 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004050 ICS.Standard.Third = ICK_Identity;
4051 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4052 ICS.Standard.setToType(0, T2);
4053 ICS.Standard.setToType(1, T1);
4054 ICS.Standard.setToType(2, T1);
4055 ICS.Standard.ReferenceBinding = true;
4056 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004057 ICS.Standard.IsLvalueReference = !isRValRef;
4058 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4059 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004060 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004061 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004062 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004063
Sebastian Redld92badf2010-06-30 18:13:39 +00004064 // Nothing more to do: the inaccessibility/ambiguity check for
4065 // derived-to-base conversions is suppressed when we're
4066 // computing the implicit conversion sequence (C++
4067 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004068 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004069 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004070
Sebastian Redld92badf2010-06-30 18:13:39 +00004071 // -- has a class type (i.e., T2 is a class type), where T1 is
4072 // not reference-related to T2, and can be implicitly
4073 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4074 // is reference-compatible with "cv3 T3" 92) (this
4075 // conversion is selected by enumerating the applicable
4076 // conversion functions (13.3.1.6) and choosing the best
4077 // one through overload resolution (13.3)),
4078 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004080 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004081 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4082 Init, T2, /*AllowRvalues=*/false,
4083 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004084 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004085 }
4086 }
4087
Sebastian Redld92badf2010-06-30 18:13:39 +00004088 // -- Otherwise, the reference shall be an lvalue reference to a
4089 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004090 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004091 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004092 // We actually handle one oddity of C++ [over.ics.ref] at this
4093 // point, which is that, due to p2 (which short-circuits reference
4094 // binding by only attempting a simple conversion for non-direct
4095 // bindings) and p3's strange wording, we allow a const volatile
4096 // reference to bind to an rvalue. Hence the check for the presence
4097 // of "const" rather than checking for "const" being the only
4098 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004099 // This is also the point where rvalue references and lvalue inits no longer
4100 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00004101 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004102 return ICS;
4103
Douglas Gregorf143cd52011-01-24 16:14:37 +00004104 // -- If the initializer expression
4105 //
4106 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004107 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004108 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4109 (InitCategory.isXValue() ||
4110 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4111 (InitCategory.isLValue() && T2->isFunctionType()))) {
4112 ICS.setStandard();
4113 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004114 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004115 : ObjCConversion? ICK_Compatible_Conversion
4116 : ICK_Identity;
4117 ICS.Standard.Third = ICK_Identity;
4118 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4119 ICS.Standard.setToType(0, T2);
4120 ICS.Standard.setToType(1, T1);
4121 ICS.Standard.setToType(2, T1);
4122 ICS.Standard.ReferenceBinding = true;
4123 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4124 // binding unless we're binding to a class prvalue.
4125 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4126 // allow the use of rvalue references in C++98/03 for the benefit of
4127 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004129 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004130 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004131 ICS.Standard.IsLvalueReference = !isRValRef;
4132 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004134 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004135 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004136 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139
Douglas Gregorf143cd52011-01-24 16:14:37 +00004140 // -- has a class type (i.e., T2 is a class type), where T1 is not
4141 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142 // an xvalue, class prvalue, or function lvalue of type
4143 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004144 // "cv3 T3",
4145 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004147 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004149 // class subobject).
4150 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004152 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4153 Init, T2, /*AllowRvalues=*/true,
4154 AllowExplicit)) {
4155 // In the second case, if the reference is an rvalue reference
4156 // and the second standard conversion sequence of the
4157 // user-defined conversion sequence includes an lvalue-to-rvalue
4158 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004160 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4161 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4162
Douglas Gregor95273c32011-01-21 16:36:05 +00004163 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004166 // -- Otherwise, a temporary of type "cv1 T1" is created and
4167 // initialized from the initializer expression using the
4168 // rules for a non-reference copy initialization (8.5). The
4169 // reference is then bound to the temporary. If T1 is
4170 // reference-related to T2, cv1 must be the same
4171 // cv-qualification as, or greater cv-qualification than,
4172 // cv2; otherwise, the program is ill-formed.
4173 if (RefRelationship == Sema::Ref_Related) {
4174 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4175 // we would be reference-compatible or reference-compatible with
4176 // added qualification. But that wasn't the case, so the reference
4177 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004178 //
4179 // Note that we only want to check address spaces and cvr-qualifiers here.
4180 // ObjC GC and lifetime qualifiers aren't important.
4181 Qualifiers T1Quals = T1.getQualifiers();
4182 Qualifiers T2Quals = T2.getQualifiers();
4183 T1Quals.removeObjCGCAttr();
4184 T1Quals.removeObjCLifetime();
4185 T2Quals.removeObjCGCAttr();
4186 T2Quals.removeObjCLifetime();
4187 if (!T1Quals.compatiblyIncludes(T2Quals))
4188 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004189 }
4190
4191 // If at least one of the types is a class type, the types are not
4192 // related, and we aren't allowed any user conversions, the
4193 // reference binding fails. This case is important for breaking
4194 // recursion, since TryImplicitConversion below will attempt to
4195 // create a temporary through the use of a copy constructor.
4196 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4197 (T1->isRecordType() || T2->isRecordType()))
4198 return ICS;
4199
Douglas Gregorcba72b12011-01-21 05:18:22 +00004200 // If T1 is reference-related to T2 and the reference is an rvalue
4201 // reference, the initializer expression shall not be an lvalue.
4202 if (RefRelationship >= Sema::Ref_Related &&
4203 isRValRef && Init->Classify(S.Context).isLValue())
4204 return ICS;
4205
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004206 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004207 // When a parameter of reference type is not bound directly to
4208 // an argument expression, the conversion sequence is the one
4209 // required to convert the argument expression to the
4210 // underlying type of the reference according to
4211 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4212 // to copy-initializing a temporary of the underlying type with
4213 // the argument expression. Any difference in top-level
4214 // cv-qualification is subsumed by the initialization itself
4215 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004216 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4217 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004218 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004219 /*CStyle=*/false,
4220 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004221
4222 // Of course, that's still a reference binding.
4223 if (ICS.isStandard()) {
4224 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004225 ICS.Standard.IsLvalueReference = !isRValRef;
4226 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4227 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004228 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004229 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004230 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004231 // Don't allow rvalue references to bind to lvalues.
4232 if (DeclType->isRValueReferenceType()) {
4233 if (const ReferenceType *RefType
4234 = ICS.UserDefined.ConversionFunction->getResultType()
4235 ->getAs<LValueReferenceType>()) {
4236 if (!RefType->getPointeeType()->isFunctionType()) {
4237 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4238 DeclType);
4239 return ICS;
4240 }
4241 }
4242 }
4243
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004244 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004245 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4246 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4247 ICS.UserDefined.After.BindsToRvalue = true;
4248 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4249 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004250 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004251
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004252 return ICS;
4253}
4254
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004255static ImplicitConversionSequence
4256TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4257 bool SuppressUserConversions,
4258 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004259 bool AllowObjCWritebackConversion,
4260 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004261
4262/// TryListConversion - Try to copy-initialize a value of type ToType from the
4263/// initializer list From.
4264static ImplicitConversionSequence
4265TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4266 bool SuppressUserConversions,
4267 bool InOverloadResolution,
4268 bool AllowObjCWritebackConversion) {
4269 // C++11 [over.ics.list]p1:
4270 // When an argument is an initializer list, it is not an expression and
4271 // special rules apply for converting it to a parameter type.
4272
4273 ImplicitConversionSequence Result;
4274 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004275 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004276
Sebastian Redl09edce02012-01-23 22:09:39 +00004277 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004278 // initialized from init lists.
4279 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4280 return Result;
4281
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004282 // C++11 [over.ics.list]p2:
4283 // If the parameter type is std::initializer_list<X> or "array of X" and
4284 // all the elements can be implicitly converted to X, the implicit
4285 // conversion sequence is the worst conversion necessary to convert an
4286 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004287 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004288 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004289 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004290 X = S.Context.getBaseElementType(ToType);
4291 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004292 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004293 if (!X.isNull()) {
4294 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4295 Expr *Init = From->getInit(i);
4296 ImplicitConversionSequence ICS =
4297 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4298 InOverloadResolution,
4299 AllowObjCWritebackConversion);
4300 // If a single element isn't convertible, fail.
4301 if (ICS.isBad()) {
4302 Result = ICS;
4303 break;
4304 }
4305 // Otherwise, look for the worst conversion.
4306 if (Result.isBad() ||
4307 CompareImplicitConversionSequences(S, ICS, Result) ==
4308 ImplicitConversionSequence::Worse)
4309 Result = ICS;
4310 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004311
4312 // For an empty list, we won't have computed any conversion sequence.
4313 // Introduce the identity conversion sequence.
4314 if (From->getNumInits() == 0) {
4315 Result.setStandard();
4316 Result.Standard.setAsIdentityConversion();
4317 Result.Standard.setFromType(ToType);
4318 Result.Standard.setAllToTypes(ToType);
4319 }
4320
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004321 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004322 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004323 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004324 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004325
4326 // C++11 [over.ics.list]p3:
4327 // Otherwise, if the parameter is a non-aggregate class X and overload
4328 // resolution chooses a single best constructor [...] the implicit
4329 // conversion sequence is a user-defined conversion sequence. If multiple
4330 // constructors are viable but none is better than the others, the
4331 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004332 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4333 // This function can deal with initializer lists.
4334 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4335 /*AllowExplicit=*/false,
4336 InOverloadResolution, /*CStyle=*/false,
4337 AllowObjCWritebackConversion);
4338 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004339 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004340 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004341
4342 // C++11 [over.ics.list]p4:
4343 // Otherwise, if the parameter has an aggregate type which can be
4344 // initialized from the initializer list [...] the implicit conversion
4345 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004346 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004347 // Type is an aggregate, argument is an init list. At this point it comes
4348 // down to checking whether the initialization works.
4349 // FIXME: Find out whether this parameter is consumed or not.
4350 InitializedEntity Entity =
4351 InitializedEntity::InitializeParameter(S.Context, ToType,
4352 /*Consumed=*/false);
4353 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4354 Result.setUserDefined();
4355 Result.UserDefined.Before.setAsIdentityConversion();
4356 // Initializer lists don't have a type.
4357 Result.UserDefined.Before.setFromType(QualType());
4358 Result.UserDefined.Before.setAllToTypes(QualType());
4359
4360 Result.UserDefined.After.setAsIdentityConversion();
4361 Result.UserDefined.After.setFromType(ToType);
4362 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004363 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004364 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004365 return Result;
4366 }
4367
4368 // C++11 [over.ics.list]p5:
4369 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004370 if (ToType->isReferenceType()) {
4371 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4372 // mention initializer lists in any way. So we go by what list-
4373 // initialization would do and try to extrapolate from that.
4374
4375 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4376
4377 // If the initializer list has a single element that is reference-related
4378 // to the parameter type, we initialize the reference from that.
4379 if (From->getNumInits() == 1) {
4380 Expr *Init = From->getInit(0);
4381
4382 QualType T2 = Init->getType();
4383
4384 // If the initializer is the address of an overloaded function, try
4385 // to resolve the overloaded function. If all goes well, T2 is the
4386 // type of the resulting function.
4387 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4388 DeclAccessPair Found;
4389 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4390 Init, ToType, false, Found))
4391 T2 = Fn->getType();
4392 }
4393
4394 // Compute some basic properties of the types and the initializer.
4395 bool dummy1 = false;
4396 bool dummy2 = false;
4397 bool dummy3 = false;
4398 Sema::ReferenceCompareResult RefRelationship
4399 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4400 dummy2, dummy3);
4401
4402 if (RefRelationship >= Sema::Ref_Related)
4403 return TryReferenceInit(S, Init, ToType,
4404 /*FIXME:*/From->getLocStart(),
4405 SuppressUserConversions,
4406 /*AllowExplicit=*/false);
4407 }
4408
4409 // Otherwise, we bind the reference to a temporary created from the
4410 // initializer list.
4411 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4412 InOverloadResolution,
4413 AllowObjCWritebackConversion);
4414 if (Result.isFailure())
4415 return Result;
4416 assert(!Result.isEllipsis() &&
4417 "Sub-initialization cannot result in ellipsis conversion.");
4418
4419 // Can we even bind to a temporary?
4420 if (ToType->isRValueReferenceType() ||
4421 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4422 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4423 Result.UserDefined.After;
4424 SCS.ReferenceBinding = true;
4425 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4426 SCS.BindsToRvalue = true;
4427 SCS.BindsToFunctionLvalue = false;
4428 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4429 SCS.ObjCLifetimeConversionBinding = false;
4430 } else
4431 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4432 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004433 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004434 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004435
4436 // C++11 [over.ics.list]p6:
4437 // Otherwise, if the parameter type is not a class:
4438 if (!ToType->isRecordType()) {
4439 // - if the initializer list has one element, the implicit conversion
4440 // sequence is the one required to convert the element to the
4441 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004442 unsigned NumInits = From->getNumInits();
4443 if (NumInits == 1)
4444 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4445 SuppressUserConversions,
4446 InOverloadResolution,
4447 AllowObjCWritebackConversion);
4448 // - if the initializer list has no elements, the implicit conversion
4449 // sequence is the identity conversion.
4450 else if (NumInits == 0) {
4451 Result.setStandard();
4452 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004453 Result.Standard.setFromType(ToType);
4454 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004455 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004456 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004457 return Result;
4458 }
4459
4460 // C++11 [over.ics.list]p7:
4461 // In all cases other than those enumerated above, no conversion is possible
4462 return Result;
4463}
4464
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004465/// TryCopyInitialization - Try to copy-initialize a value of type
4466/// ToType from the expression From. Return the implicit conversion
4467/// sequence required to pass this argument, which may be a bad
4468/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004469/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004470/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004471static ImplicitConversionSequence
4472TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004474 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004475 bool AllowObjCWritebackConversion,
4476 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004477 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4478 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4479 InOverloadResolution,AllowObjCWritebackConversion);
4480
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004481 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004482 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004483 /*FIXME:*/From->getLocStart(),
4484 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004485 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004486
John McCall5c32be02010-08-24 20:38:10 +00004487 return TryImplicitConversion(S, From, ToType,
4488 SuppressUserConversions,
4489 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004490 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004491 /*CStyle=*/false,
4492 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004493}
4494
Anna Zaks1b068122011-07-28 19:46:48 +00004495static bool TryCopyInitialization(const CanQualType FromQTy,
4496 const CanQualType ToQTy,
4497 Sema &S,
4498 SourceLocation Loc,
4499 ExprValueKind FromVK) {
4500 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4501 ImplicitConversionSequence ICS =
4502 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4503
4504 return !ICS.isBad();
4505}
4506
Douglas Gregor436424c2008-11-18 23:14:02 +00004507/// TryObjectArgumentInitialization - Try to initialize the object
4508/// parameter of the given member function (@c Method) from the
4509/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004510static ImplicitConversionSequence
4511TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004512 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004513 CXXMethodDecl *Method,
4514 CXXRecordDecl *ActingContext) {
4515 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004516 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4517 // const volatile object.
4518 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4519 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004520 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004521
4522 // Set up the conversion sequence as a "bad" conversion, to allow us
4523 // to exit early.
4524 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004525
4526 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004527 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004528 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004529 FromType = PT->getPointeeType();
4530
Douglas Gregor02824322011-01-26 19:30:28 +00004531 // When we had a pointer, it's implicitly dereferenced, so we
4532 // better have an lvalue.
4533 assert(FromClassification.isLValue());
4534 }
4535
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004536 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004537
Douglas Gregor02824322011-01-26 19:30:28 +00004538 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004540 // parameter is
4541 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004542 // - "lvalue reference to cv X" for functions declared without a
4543 // ref-qualifier or with the & ref-qualifier
4544 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004545 // ref-qualifier
4546 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004548 // cv-qualification on the member function declaration.
4549 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004551 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004552 // (C++ [over.match.funcs]p5). We perform a simplified version of
4553 // reference binding here, that allows class rvalues to bind to
4554 // non-constant references.
4555
Douglas Gregor02824322011-01-26 19:30:28 +00004556 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004557 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004559 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004560 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004561 ICS.setBad(BadConversionSequence::bad_qualifiers,
4562 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004563 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004564 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004565
4566 // Check that we have either the same type or a derived type. It
4567 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004568 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004569 ImplicitConversionKind SecondKind;
4570 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4571 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004572 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004573 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004574 else {
John McCall65eb8792010-02-25 01:37:24 +00004575 ICS.setBad(BadConversionSequence::unrelated_class,
4576 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004577 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004578 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004579
Douglas Gregor02824322011-01-26 19:30:28 +00004580 // Check the ref-qualifier.
4581 switch (Method->getRefQualifier()) {
4582 case RQ_None:
4583 // Do nothing; we don't care about lvalueness or rvalueness.
4584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Douglas Gregor02824322011-01-26 19:30:28 +00004586 case RQ_LValue:
4587 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4588 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004590 ImplicitParamType);
4591 return ICS;
4592 }
4593 break;
4594
4595 case RQ_RValue:
4596 if (!FromClassification.isRValue()) {
4597 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004598 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004599 ImplicitParamType);
4600 return ICS;
4601 }
4602 break;
4603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004604
Douglas Gregor436424c2008-11-18 23:14:02 +00004605 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004606 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004607 ICS.Standard.setAsIdentityConversion();
4608 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004609 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004610 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004611 ICS.Standard.ReferenceBinding = true;
4612 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004613 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004614 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004615 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4616 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4617 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004618 return ICS;
4619}
4620
4621/// PerformObjectArgumentInitialization - Perform initialization of
4622/// the implicit object parameter for the given Method with the given
4623/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004624ExprResult
4625Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004627 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004628 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004629 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004630 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004631 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004632
Douglas Gregor02824322011-01-26 19:30:28 +00004633 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004634 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004635 FromRecordType = PT->getPointeeType();
4636 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004637 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004638 } else {
4639 FromRecordType = From->getType();
4640 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004641 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004642 }
4643
John McCall6e9f8f62009-12-03 04:06:58 +00004644 // Note that we always use the true parent context when performing
4645 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004646 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004647 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4648 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004649 if (ICS.isBad()) {
4650 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4651 Qualifiers FromQs = FromRecordType.getQualifiers();
4652 Qualifiers ToQs = DestType.getQualifiers();
4653 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4654 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004655 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004656 diag::err_member_function_call_bad_cvr)
4657 << Method->getDeclName() << FromRecordType << (CVR - 1)
4658 << From->getSourceRange();
4659 Diag(Method->getLocation(), diag::note_previous_decl)
4660 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004661 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004662 }
4663 }
4664
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004665 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004666 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004667 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004668 }
Mike Stump11289f42009-09-09 15:08:12 +00004669
John Wiegley01296292011-04-08 18:41:53 +00004670 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4671 ExprResult FromRes =
4672 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4673 if (FromRes.isInvalid())
4674 return ExprError();
4675 From = FromRes.take();
4676 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004677
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004678 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004679 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004680 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004681 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004682}
4683
Douglas Gregor5fb53972009-01-14 15:45:31 +00004684/// TryContextuallyConvertToBool - Attempt to contextually convert the
4685/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004686static ImplicitConversionSequence
4687TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004688 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004689 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004690 // FIXME: Are these flags correct?
4691 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004692 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004693 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004694 /*CStyle=*/false,
4695 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004696}
4697
4698/// PerformContextuallyConvertToBool - Perform a contextual conversion
4699/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004700ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004701 if (checkPlaceholderForOverload(*this, From))
4702 return ExprError();
4703
John McCall5c32be02010-08-24 20:38:10 +00004704 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004705 if (!ICS.isBad())
4706 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Fariborz Jahanian76197412009-11-18 18:26:29 +00004708 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004709 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004710 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004711 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004712 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004713}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004714
Richard Smithf8379a02012-01-18 23:55:52 +00004715/// Check that the specified conversion is permitted in a converted constant
4716/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4717/// is acceptable.
4718static bool CheckConvertedConstantConversions(Sema &S,
4719 StandardConversionSequence &SCS) {
4720 // Since we know that the target type is an integral or unscoped enumeration
4721 // type, most conversion kinds are impossible. All possible First and Third
4722 // conversions are fine.
4723 switch (SCS.Second) {
4724 case ICK_Identity:
4725 case ICK_Integral_Promotion:
4726 case ICK_Integral_Conversion:
4727 return true;
4728
4729 case ICK_Boolean_Conversion:
4730 // Conversion from an integral or unscoped enumeration type to bool is
4731 // classified as ICK_Boolean_Conversion, but it's also an integral
4732 // conversion, so it's permitted in a converted constant expression.
4733 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4734 SCS.getToType(2)->isBooleanType();
4735
4736 case ICK_Floating_Integral:
4737 case ICK_Complex_Real:
4738 return false;
4739
4740 case ICK_Lvalue_To_Rvalue:
4741 case ICK_Array_To_Pointer:
4742 case ICK_Function_To_Pointer:
4743 case ICK_NoReturn_Adjustment:
4744 case ICK_Qualification:
4745 case ICK_Compatible_Conversion:
4746 case ICK_Vector_Conversion:
4747 case ICK_Vector_Splat:
4748 case ICK_Derived_To_Base:
4749 case ICK_Pointer_Conversion:
4750 case ICK_Pointer_Member:
4751 case ICK_Block_Pointer_Conversion:
4752 case ICK_Writeback_Conversion:
4753 case ICK_Floating_Promotion:
4754 case ICK_Complex_Promotion:
4755 case ICK_Complex_Conversion:
4756 case ICK_Floating_Conversion:
4757 case ICK_TransparentUnionConversion:
4758 llvm_unreachable("unexpected second conversion kind");
4759
4760 case ICK_Num_Conversion_Kinds:
4761 break;
4762 }
4763
4764 llvm_unreachable("unknown conversion kind");
4765}
4766
4767/// CheckConvertedConstantExpression - Check that the expression From is a
4768/// converted constant expression of type T, perform the conversion and produce
4769/// the converted expression, per C++11 [expr.const]p3.
4770ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4771 llvm::APSInt &Value,
4772 CCEKind CCE) {
4773 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4774 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4775
4776 if (checkPlaceholderForOverload(*this, From))
4777 return ExprError();
4778
4779 // C++11 [expr.const]p3 with proposed wording fixes:
4780 // A converted constant expression of type T is a core constant expression,
4781 // implicitly converted to a prvalue of type T, where the converted
4782 // expression is a literal constant expression and the implicit conversion
4783 // sequence contains only user-defined conversions, lvalue-to-rvalue
4784 // conversions, integral promotions, and integral conversions other than
4785 // narrowing conversions.
4786 ImplicitConversionSequence ICS =
4787 TryImplicitConversion(From, T,
4788 /*SuppressUserConversions=*/false,
4789 /*AllowExplicit=*/false,
4790 /*InOverloadResolution=*/false,
4791 /*CStyle=*/false,
4792 /*AllowObjcWritebackConversion=*/false);
4793 StandardConversionSequence *SCS = 0;
4794 switch (ICS.getKind()) {
4795 case ImplicitConversionSequence::StandardConversion:
4796 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004797 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004798 diag::err_typecheck_converted_constant_expression_disallowed)
4799 << From->getType() << From->getSourceRange() << T;
4800 SCS = &ICS.Standard;
4801 break;
4802 case ImplicitConversionSequence::UserDefinedConversion:
4803 // We are converting from class type to an integral or enumeration type, so
4804 // the Before sequence must be trivial.
4805 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004806 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004807 diag::err_typecheck_converted_constant_expression_disallowed)
4808 << From->getType() << From->getSourceRange() << T;
4809 SCS = &ICS.UserDefined.After;
4810 break;
4811 case ImplicitConversionSequence::AmbiguousConversion:
4812 case ImplicitConversionSequence::BadConversion:
4813 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004814 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004815 diag::err_typecheck_converted_constant_expression)
4816 << From->getType() << From->getSourceRange() << T;
4817 return ExprError();
4818
4819 case ImplicitConversionSequence::EllipsisConversion:
4820 llvm_unreachable("ellipsis conversion in converted constant expression");
4821 }
4822
4823 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4824 if (Result.isInvalid())
4825 return Result;
4826
4827 // Check for a narrowing implicit conversion.
4828 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004829 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004830 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4831 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004832 case NK_Variable_Narrowing:
4833 // Implicit conversion to a narrower type, and the value is not a constant
4834 // expression. We'll diagnose this in a moment.
4835 case NK_Not_Narrowing:
4836 break;
4837
4838 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004839 Diag(From->getLocStart(),
4840 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4841 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004842 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004843 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004844 break;
4845
4846 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004847 Diag(From->getLocStart(),
4848 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4849 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004850 << CCE << /*Constant*/0 << From->getType() << T;
4851 break;
4852 }
4853
4854 // Check the expression is a constant expression.
4855 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4856 Expr::EvalResult Eval;
4857 Eval.Diag = &Notes;
4858
4859 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4860 // The expression can't be folded, so we can't keep it at this position in
4861 // the AST.
4862 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004863 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004864 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004865
4866 if (Notes.empty()) {
4867 // It's a constant expression.
4868 return Result;
4869 }
Richard Smithf8379a02012-01-18 23:55:52 +00004870 }
4871
4872 // It's not a constant expression. Produce an appropriate diagnostic.
4873 if (Notes.size() == 1 &&
4874 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4875 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4876 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004877 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004878 << CCE << From->getSourceRange();
4879 for (unsigned I = 0; I < Notes.size(); ++I)
4880 Diag(Notes[I].first, Notes[I].second);
4881 }
Richard Smith911e1422012-01-30 22:27:01 +00004882 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004883}
4884
John McCallfec112d2011-09-09 06:11:02 +00004885/// dropPointerConversions - If the given standard conversion sequence
4886/// involves any pointer conversions, remove them. This may change
4887/// the result type of the conversion sequence.
4888static void dropPointerConversion(StandardConversionSequence &SCS) {
4889 if (SCS.Second == ICK_Pointer_Conversion) {
4890 SCS.Second = ICK_Identity;
4891 SCS.Third = ICK_Identity;
4892 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4893 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004894}
John McCall5c32be02010-08-24 20:38:10 +00004895
John McCallfec112d2011-09-09 06:11:02 +00004896/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4897/// convert the expression From to an Objective-C pointer type.
4898static ImplicitConversionSequence
4899TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4900 // Do an implicit conversion to 'id'.
4901 QualType Ty = S.Context.getObjCIdType();
4902 ImplicitConversionSequence ICS
4903 = TryImplicitConversion(S, From, Ty,
4904 // FIXME: Are these flags correct?
4905 /*SuppressUserConversions=*/false,
4906 /*AllowExplicit=*/true,
4907 /*InOverloadResolution=*/false,
4908 /*CStyle=*/false,
4909 /*AllowObjCWritebackConversion=*/false);
4910
4911 // Strip off any final conversions to 'id'.
4912 switch (ICS.getKind()) {
4913 case ImplicitConversionSequence::BadConversion:
4914 case ImplicitConversionSequence::AmbiguousConversion:
4915 case ImplicitConversionSequence::EllipsisConversion:
4916 break;
4917
4918 case ImplicitConversionSequence::UserDefinedConversion:
4919 dropPointerConversion(ICS.UserDefined.After);
4920 break;
4921
4922 case ImplicitConversionSequence::StandardConversion:
4923 dropPointerConversion(ICS.Standard);
4924 break;
4925 }
4926
4927 return ICS;
4928}
4929
4930/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4931/// conversion of the expression From to an Objective-C pointer type.
4932ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004933 if (checkPlaceholderForOverload(*this, From))
4934 return ExprError();
4935
John McCall8b07ec22010-05-15 11:32:37 +00004936 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004937 ImplicitConversionSequence ICS =
4938 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004939 if (!ICS.isBad())
4940 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004941 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004942}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004943
Richard Smith8dd34252012-02-04 07:07:42 +00004944/// Determine whether the provided type is an integral type, or an enumeration
4945/// type of a permitted flavor.
4946static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4947 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4948 : T->isIntegralOrUnscopedEnumerationType();
4949}
4950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004951/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004952/// enumeration type.
4953///
4954/// This routine will attempt to convert an expression of class type to an
4955/// integral or enumeration type, if that class type only has a single
4956/// conversion to an integral or enumeration type.
4957///
Douglas Gregor4799d032010-06-30 00:20:43 +00004958/// \param Loc The source location of the construct that requires the
4959/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004960///
Douglas Gregor4799d032010-06-30 00:20:43 +00004961/// \param FromE The expression we're converting from.
4962///
4963/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4964/// have integral or enumeration type.
4965///
4966/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4967/// incomplete class type.
4968///
4969/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4970/// explicit conversion function (because no implicit conversion functions
4971/// were available). This is a recovery mode.
4972///
4973/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4974/// showing which conversion was picked.
4975///
4976/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4977/// conversion function that could convert to integral or enumeration type.
4978///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004980/// usable conversion function.
4981///
4982/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4983/// function, which may be an extension in this case.
4984///
Richard Smith8dd34252012-02-04 07:07:42 +00004985/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4986/// enumerations should be considered.
4987///
Douglas Gregor4799d032010-06-30 00:20:43 +00004988/// \returns The expression, converted to an integral or enumeration type if
4989/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990ExprResult
John McCallb268a282010-08-23 23:25:46 +00004991Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004992 const PartialDiagnostic &NotIntDiag,
4993 const PartialDiagnostic &IncompleteDiag,
4994 const PartialDiagnostic &ExplicitConvDiag,
4995 const PartialDiagnostic &ExplicitConvNote,
4996 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004997 const PartialDiagnostic &AmbigNote,
Richard Smith8dd34252012-02-04 07:07:42 +00004998 const PartialDiagnostic &ConvDiag,
4999 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005000 // We can't perform any more checking for type-dependent expressions.
5001 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005002 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005003
Eli Friedman1da70392012-01-26 00:26:18 +00005004 // Process placeholders immediately.
5005 if (From->hasPlaceholderType()) {
5006 ExprResult result = CheckPlaceholderExpr(From);
5007 if (result.isInvalid()) return result;
5008 From = result.take();
5009 }
5010
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005011 // If the expression already has integral or enumeration type, we're golden.
5012 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005013 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005014 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005015
5016 // FIXME: Check for missing '()' if T is a function type?
5017
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005018 // 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 +00005019 // expression of integral or enumeration type.
5020 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005021 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithf4c51d92012-02-04 09:53:13 +00005022 if (NotIntDiag.getDiagID())
5023 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005024 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005025 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005027 // We must have a complete class type.
5028 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00005029 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005031 // Look for a conversion to an integral or enumeration type.
5032 UnresolvedSet<4> ViableConversions;
5033 UnresolvedSet<4> ExplicitConversions;
5034 const UnresolvedSetImpl *Conversions
5035 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005037 bool HadMultipleCandidates = (Conversions->size() > 1);
5038
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005039 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040 E = Conversions->end();
5041 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005042 ++I) {
5043 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005044 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5045 if (isIntegralOrEnumerationType(
5046 Conversion->getConversionType().getNonReferenceType(),
5047 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005048 if (Conversion->isExplicit())
5049 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5050 else
5051 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5052 }
Richard Smith8dd34252012-02-04 07:07:42 +00005053 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005056 switch (ViableConversions.size()) {
5057 case 0:
Richard Smithf4c51d92012-02-04 09:53:13 +00005058 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005059 DeclAccessPair Found = ExplicitConversions[0];
5060 CXXConversionDecl *Conversion
5061 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063 // The user probably meant to invoke the given explicit
5064 // conversion; use it.
5065 QualType ConvTy
5066 = Conversion->getConversionType().getNonReferenceType();
5067 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005068 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005070 Diag(Loc, ExplicitConvDiag)
5071 << T << ConvTy
5072 << FixItHint::CreateInsertion(From->getLocStart(),
5073 "static_cast<" + TypeStr + ">(")
5074 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5075 ")");
5076 Diag(Conversion->getLocation(), ExplicitConvNote)
5077 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078
5079 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005080 // explicit conversion function.
5081 if (isSFINAEContext())
5082 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005084 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005085 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5086 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005087 if (Result.isInvalid())
5088 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005089 // Record usage of conversion in an implicit cast.
5090 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5091 CK_UserDefinedConversion,
5092 Result.get(), 0,
5093 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005096 // We'll complain below about a non-integral condition type.
5097 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005099 case 1: {
5100 // Apply this conversion.
5101 DeclAccessPair Found = ViableConversions[0];
5102 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005103
Douglas Gregor4799d032010-06-30 00:20:43 +00005104 CXXConversionDecl *Conversion
5105 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5106 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00005108 if (ConvDiag.getDiagID()) {
5109 if (isSFINAEContext())
5110 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005111
Douglas Gregor4799d032010-06-30 00:20:43 +00005112 Diag(Loc, ConvDiag)
5113 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005115
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005116 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5117 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005118 if (Result.isInvalid())
5119 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005120 // Record usage of conversion in an implicit cast.
5121 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5122 CK_UserDefinedConversion,
5123 Result.get(), 0,
5124 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005125 break;
5126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005127
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005128 default:
Richard Smithf4c51d92012-02-04 09:53:13 +00005129 if (!AmbigDiag.getDiagID())
5130 return Owned(From);
5131
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005132 Diag(Loc, AmbigDiag)
5133 << T << From->getSourceRange();
5134 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5135 CXXConversionDecl *Conv
5136 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5137 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5138 Diag(Conv->getLocation(), AmbigNote)
5139 << ConvTy->isEnumeralType() << ConvTy;
5140 }
John McCallb268a282010-08-23 23:25:46 +00005141 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143
Richard Smithf4c51d92012-02-04 09:53:13 +00005144 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5145 NotIntDiag.getDiagID())
5146 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005147
Eli Friedman1da70392012-01-26 00:26:18 +00005148 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005149}
5150
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005151/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005152/// candidate functions, using the given function call arguments. If
5153/// @p SuppressUserConversions, then don't allow user-defined
5154/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005155///
5156/// \para PartialOverloading true if we are performing "partial" overloading
5157/// based on an incomplete set of function arguments. This feature is used by
5158/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005159void
5160Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005161 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005162 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005163 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005164 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005165 bool PartialOverloading,
5166 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005167 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005168 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005169 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005170 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005171 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005172
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005173 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005174 if (!isa<CXXConstructorDecl>(Method)) {
5175 // If we get here, it's because we're calling a member function
5176 // that is named without a member access expression (e.g.,
5177 // "this->f") that was either written explicitly or created
5178 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005179 // function, e.g., X::f(). We use an empty type for the implied
5180 // object argument (C++ [over.call.func]p3), and the acting context
5181 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005182 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005184 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005185 return;
5186 }
5187 // We treat a constructor like a non-member function, since its object
5188 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005189 }
5190
Douglas Gregorff7028a2009-11-13 23:59:09 +00005191 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005192 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005193
Douglas Gregor27381f32009-11-23 12:27:39 +00005194 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005195 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005196
Douglas Gregorffe14e32009-11-14 01:20:54 +00005197 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5198 // C++ [class.copy]p3:
5199 // A member function template is never instantiated to perform the copy
5200 // of a class object to an object of its class type.
5201 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005202 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005203 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005204 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5205 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005206 return;
5207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005208
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005209 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005210 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005211 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005212 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005213 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005214 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005215 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005216 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005217
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005218 unsigned NumArgsInProto = Proto->getNumArgs();
5219
5220 // (C++ 13.3.2p2): A candidate function having fewer than m
5221 // parameters is viable only if it has an ellipsis in its parameter
5222 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005223 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005224 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005225 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005226 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005227 return;
5228 }
5229
5230 // (C++ 13.3.2p2): A candidate function having more than m parameters
5231 // is viable only if the (m+1)st parameter has a default argument
5232 // (8.3.6). For the purposes of overload resolution, the
5233 // parameter list is truncated on the right, so that there are
5234 // exactly m parameters.
5235 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005236 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005237 // Not enough arguments.
5238 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005239 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005240 return;
5241 }
5242
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005243 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005244 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005245 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5246 if (CheckCUDATarget(Caller, Function)) {
5247 Candidate.Viable = false;
5248 Candidate.FailureKind = ovl_fail_bad_target;
5249 return;
5250 }
5251
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005252 // Determine the implicit conversion sequences for each of the
5253 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005254 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005255 if (ArgIdx < NumArgsInProto) {
5256 // (C++ 13.3.2p3): for F to be a viable function, there shall
5257 // exist for each argument an implicit conversion sequence
5258 // (13.3.3.1) that converts that argument to the corresponding
5259 // parameter of F.
5260 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005261 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005262 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005264 /*InOverloadResolution=*/true,
5265 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005266 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005267 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005268 if (Candidate.Conversions[ArgIdx].isBad()) {
5269 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005270 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005271 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005272 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005273 } else {
5274 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5275 // argument for which there is no corresponding parameter is
5276 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005277 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005278 }
5279 }
5280}
5281
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005282/// \brief Add all of the function declarations in the given function set to
5283/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005284void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005285 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005286 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005287 bool SuppressUserConversions,
5288 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005289 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005290 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5291 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005292 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005293 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005294 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005295 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005296 Args.slice(1), CandidateSet,
5297 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005298 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005299 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005300 SuppressUserConversions);
5301 } else {
John McCalla0296f72010-03-19 07:35:19 +00005302 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005303 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5304 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005305 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005306 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005307 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005308 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005309 Args[0]->Classify(Context), Args.slice(1),
5310 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005311 else
John McCalla0296f72010-03-19 07:35:19 +00005312 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005313 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005314 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005315 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005316 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005317}
5318
John McCallf0f1cf02009-11-17 07:50:12 +00005319/// AddMethodCandidate - Adds a named decl (which is some kind of
5320/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005321void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005322 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005323 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005324 Expr **Args, unsigned NumArgs,
5325 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005326 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005327 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005329
5330 if (isa<UsingShadowDecl>(Decl))
5331 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332
John McCallf0f1cf02009-11-17 07:50:12 +00005333 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5334 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5335 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005336 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5337 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005338 ObjectType, ObjectClassification,
5339 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005340 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005341 } else {
John McCalla0296f72010-03-19 07:35:19 +00005342 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005343 ObjectType, ObjectClassification,
5344 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005345 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005346 }
5347}
5348
Douglas Gregor436424c2008-11-18 23:14:02 +00005349/// AddMethodCandidate - Adds the given C++ member function to the set
5350/// of candidate functions, using the given function call arguments
5351/// and the object argument (@c Object). For example, in a call
5352/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5353/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5354/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005355/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005356void
John McCalla0296f72010-03-19 07:35:19 +00005357Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005358 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005359 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005360 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005361 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005362 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005363 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005364 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005365 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005366 assert(!isa<CXXConstructorDecl>(Method) &&
5367 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005368
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005369 if (!CandidateSet.isNewCandidate(Method))
5370 return;
5371
Douglas Gregor27381f32009-11-23 12:27:39 +00005372 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005373 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005374
Douglas Gregor436424c2008-11-18 23:14:02 +00005375 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005376 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005377 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005378 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005379 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005380 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005381 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005382
5383 unsigned NumArgsInProto = Proto->getNumArgs();
5384
5385 // (C++ 13.3.2p2): A candidate function having fewer than m
5386 // parameters is viable only if it has an ellipsis in its parameter
5387 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005388 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005389 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005390 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005391 return;
5392 }
5393
5394 // (C++ 13.3.2p2): A candidate function having more than m parameters
5395 // is viable only if the (m+1)st parameter has a default argument
5396 // (8.3.6). For the purposes of overload resolution, the
5397 // parameter list is truncated on the right, so that there are
5398 // exactly m parameters.
5399 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005400 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005401 // Not enough arguments.
5402 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005403 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005404 return;
5405 }
5406
5407 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005408
John McCall6e9f8f62009-12-03 04:06:58 +00005409 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005410 // The implicit object argument is ignored.
5411 Candidate.IgnoreObjectArgument = true;
5412 else {
5413 // Determine the implicit conversion sequence for the object
5414 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005415 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005416 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5417 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005418 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005419 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005420 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005421 return;
5422 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005423 }
5424
5425 // Determine the implicit conversion sequences for each of the
5426 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005427 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005428 if (ArgIdx < NumArgsInProto) {
5429 // (C++ 13.3.2p3): for F to be a viable function, there shall
5430 // exist for each argument an implicit conversion sequence
5431 // (13.3.3.1) that converts that argument to the corresponding
5432 // parameter of F.
5433 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005434 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005435 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005437 /*InOverloadResolution=*/true,
5438 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005439 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005440 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005441 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005442 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005443 break;
5444 }
5445 } else {
5446 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5447 // argument for which there is no corresponding parameter is
5448 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005449 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005450 }
5451 }
5452}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453
Douglas Gregor97628d62009-08-21 00:16:32 +00005454/// \brief Add a C++ member function template as a candidate to the candidate
5455/// set, using template argument deduction to produce an appropriate member
5456/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005457void
Douglas Gregor97628d62009-08-21 00:16:32 +00005458Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005459 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005460 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005461 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005462 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005463 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005464 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005465 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005466 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005467 if (!CandidateSet.isNewCandidate(MethodTmpl))
5468 return;
5469
Douglas Gregor97628d62009-08-21 00:16:32 +00005470 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005471 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005472 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005473 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005474 // candidate functions in the usual way.113) A given name can refer to one
5475 // or more function templates and also to a set of overloaded non-template
5476 // functions. In such a case, the candidate functions generated from each
5477 // function template are combined with the set of non-template candidate
5478 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005479 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005480 FunctionDecl *Specialization = 0;
5481 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005482 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5483 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005484 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005485 Candidate.FoundDecl = FoundDecl;
5486 Candidate.Function = MethodTmpl->getTemplatedDecl();
5487 Candidate.Viable = false;
5488 Candidate.FailureKind = ovl_fail_bad_deduction;
5489 Candidate.IsSurrogate = false;
5490 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005491 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005493 Info);
5494 return;
5495 }
Mike Stump11289f42009-09-09 15:08:12 +00005496
Douglas Gregor97628d62009-08-21 00:16:32 +00005497 // Add the function template specialization produced by template argument
5498 // deduction as a candidate.
5499 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005500 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005501 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005502 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005503 ActingContext, ObjectType, ObjectClassification, Args,
5504 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005505}
5506
Douglas Gregor05155d82009-08-21 23:19:43 +00005507/// \brief Add a C++ function template specialization as a candidate
5508/// in the candidate set, using template argument deduction to produce
5509/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005510void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005511Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005512 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005513 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005514 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005515 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005516 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005517 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5518 return;
5519
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005520 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005521 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005522 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005523 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005524 // candidate functions in the usual way.113) A given name can refer to one
5525 // or more function templates and also to a set of overloaded non-template
5526 // functions. In such a case, the candidate functions generated from each
5527 // function template are combined with the set of non-template candidate
5528 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005529 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005530 FunctionDecl *Specialization = 0;
5531 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005532 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5533 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005534 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005535 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005536 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5537 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005538 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005539 Candidate.IsSurrogate = false;
5540 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005541 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005543 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005544 return;
5545 }
Mike Stump11289f42009-09-09 15:08:12 +00005546
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005547 // Add the function template specialization produced by template argument
5548 // deduction as a candidate.
5549 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005550 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005551 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005552}
Mike Stump11289f42009-09-09 15:08:12 +00005553
Douglas Gregora1f013e2008-11-07 22:36:19 +00005554/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005555/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005556/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005557/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005558/// (which may or may not be the same type as the type that the
5559/// conversion function produces).
5560void
5561Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005562 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005563 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005564 Expr *From, QualType ToType,
5565 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005566 assert(!Conversion->getDescribedFunctionTemplate() &&
5567 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005568 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005569 if (!CandidateSet.isNewCandidate(Conversion))
5570 return;
5571
Douglas Gregor27381f32009-11-23 12:27:39 +00005572 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005573 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005574
Douglas Gregora1f013e2008-11-07 22:36:19 +00005575 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005576 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005577 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005578 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005579 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005580 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005581 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005582 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005583 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005584 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005585 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005586
Douglas Gregor6affc782010-08-19 15:37:02 +00005587 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588 // For conversion functions, the function is considered to be a member of
5589 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005590 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005591 //
5592 // Determine the implicit conversion sequence for the implicit
5593 // object parameter.
5594 QualType ImplicitParamType = From->getType();
5595 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5596 ImplicitParamType = FromPtrType->getPointeeType();
5597 CXXRecordDecl *ConversionContext
5598 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005599
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005600 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601 = TryObjectArgumentInitialization(*this, From->getType(),
5602 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005603 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604
John McCall0d1da222010-01-12 00:44:57 +00005605 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005606 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005607 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005608 return;
5609 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005610
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005611 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005612 // derived to base as such conversions are given Conversion Rank. They only
5613 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5614 QualType FromCanon
5615 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5616 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5617 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5618 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005619 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005620 return;
5621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005622
Douglas Gregora1f013e2008-11-07 22:36:19 +00005623 // To determine what the conversion from the result of calling the
5624 // conversion function to the type we're eventually trying to
5625 // convert to (ToType), we need to synthesize a call to the
5626 // conversion function and attempt copy initialization from it. This
5627 // makes sure that we get the right semantics with respect to
5628 // lvalues/rvalues and the type. Fortunately, we can allocate this
5629 // call on the stack and we don't need its arguments to be
5630 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005631 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005632 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005633 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5634 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005635 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005636 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005637
Richard Smith48d24642011-07-13 22:53:21 +00005638 QualType ConversionType = Conversion->getConversionType();
5639 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005640 Candidate.Viable = false;
5641 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5642 return;
5643 }
5644
Richard Smith48d24642011-07-13 22:53:21 +00005645 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005646
Mike Stump11289f42009-09-09 15:08:12 +00005647 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005648 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5649 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005650 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005651 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005652 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005653 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005654 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005655 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005656 /*InOverloadResolution=*/false,
5657 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005658
John McCall0d1da222010-01-12 00:44:57 +00005659 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005660 case ImplicitConversionSequence::StandardConversion:
5661 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005662
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005663 // C++ [over.ics.user]p3:
5664 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005665 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005666 // shall have exact match rank.
5667 if (Conversion->getPrimaryTemplate() &&
5668 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5669 Candidate.Viable = false;
5670 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005672
Douglas Gregorcba72b12011-01-21 05:18:22 +00005673 // C++0x [dcl.init.ref]p5:
5674 // In the second case, if the reference is an rvalue reference and
5675 // the second standard conversion sequence of the user-defined
5676 // conversion sequence includes an lvalue-to-rvalue conversion, the
5677 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005679 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5680 Candidate.Viable = false;
5681 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5682 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005683 break;
5684
5685 case ImplicitConversionSequence::BadConversion:
5686 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005687 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005688 break;
5689
5690 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005691 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005692 "Can only end up with a standard conversion sequence or failure");
5693 }
5694}
5695
Douglas Gregor05155d82009-08-21 23:19:43 +00005696/// \brief Adds a conversion function template specialization
5697/// candidate to the overload set, using template argument deduction
5698/// to deduce the template arguments of the conversion function
5699/// template from the type that we are converting to (C++
5700/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005701void
Douglas Gregor05155d82009-08-21 23:19:43 +00005702Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005703 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005704 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005705 Expr *From, QualType ToType,
5706 OverloadCandidateSet &CandidateSet) {
5707 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5708 "Only conversion function templates permitted here");
5709
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005710 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5711 return;
5712
John McCallbc077cf2010-02-08 23:07:23 +00005713 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005714 CXXConversionDecl *Specialization = 0;
5715 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005716 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005717 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005718 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005719 Candidate.FoundDecl = FoundDecl;
5720 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5721 Candidate.Viable = false;
5722 Candidate.FailureKind = ovl_fail_bad_deduction;
5723 Candidate.IsSurrogate = false;
5724 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005725 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005727 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005728 return;
5729 }
Mike Stump11289f42009-09-09 15:08:12 +00005730
Douglas Gregor05155d82009-08-21 23:19:43 +00005731 // Add the conversion function template specialization produced by
5732 // template argument deduction as a candidate.
5733 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005734 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005735 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005736}
5737
Douglas Gregorab7897a2008-11-19 22:57:39 +00005738/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5739/// converts the given @c Object to a function pointer via the
5740/// conversion function @c Conversion, and then attempts to call it
5741/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5742/// the type of function that we'll eventually be calling.
5743void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005744 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005745 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005746 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005747 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005748 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005749 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005750 if (!CandidateSet.isNewCandidate(Conversion))
5751 return;
5752
Douglas Gregor27381f32009-11-23 12:27:39 +00005753 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005754 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005755
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005756 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005757 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005758 Candidate.Function = 0;
5759 Candidate.Surrogate = Conversion;
5760 Candidate.Viable = true;
5761 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005762 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005763 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005764
5765 // Determine the implicit conversion sequence for the implicit
5766 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005767 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005768 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005769 Object->Classify(Context),
5770 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005771 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005772 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005773 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005774 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005775 return;
5776 }
5777
5778 // The first conversion is actually a user-defined conversion whose
5779 // first conversion is ObjectInit's standard conversion (which is
5780 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005781 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005782 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005783 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005784 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005785 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005786 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005787 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005788 = Candidate.Conversions[0].UserDefined.Before;
5789 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5790
Mike Stump11289f42009-09-09 15:08:12 +00005791 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005792 unsigned NumArgsInProto = Proto->getNumArgs();
5793
5794 // (C++ 13.3.2p2): A candidate function having fewer than m
5795 // parameters is viable only if it has an ellipsis in its parameter
5796 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005797 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005798 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005799 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005800 return;
5801 }
5802
5803 // Function types don't have any default arguments, so just check if
5804 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005805 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005806 // Not enough arguments.
5807 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005808 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005809 return;
5810 }
5811
5812 // Determine the implicit conversion sequences for each of the
5813 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005814 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005815 if (ArgIdx < NumArgsInProto) {
5816 // (C++ 13.3.2p3): for F to be a viable function, there shall
5817 // exist for each argument an implicit conversion sequence
5818 // (13.3.3.1) that converts that argument to the corresponding
5819 // parameter of F.
5820 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005821 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005822 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005823 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005824 /*InOverloadResolution=*/false,
5825 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005826 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005827 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005828 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005829 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005830 break;
5831 }
5832 } else {
5833 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5834 // argument for which there is no corresponding parameter is
5835 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005836 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005837 }
5838 }
5839}
5840
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005841/// \brief Add overload candidates for overloaded operators that are
5842/// member functions.
5843///
5844/// Add the overloaded operator candidates that are member functions
5845/// for the operator Op that was used in an operator expression such
5846/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5847/// CandidateSet will store the added overload candidates. (C++
5848/// [over.match.oper]).
5849void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5850 SourceLocation OpLoc,
5851 Expr **Args, unsigned NumArgs,
5852 OverloadCandidateSet& CandidateSet,
5853 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005854 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5855
5856 // C++ [over.match.oper]p3:
5857 // For a unary operator @ with an operand of a type whose
5858 // cv-unqualified version is T1, and for a binary operator @ with
5859 // a left operand of a type whose cv-unqualified version is T1 and
5860 // a right operand of a type whose cv-unqualified version is T2,
5861 // three sets of candidate functions, designated member
5862 // candidates, non-member candidates and built-in candidates, are
5863 // constructed as follows:
5864 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005865
5866 // -- If T1 is a class type, the set of member candidates is the
5867 // result of the qualified lookup of T1::operator@
5868 // (13.3.1.1.1); otherwise, the set of member candidates is
5869 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005870 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005871 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005872 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005873 return;
Mike Stump11289f42009-09-09 15:08:12 +00005874
John McCall27b18f82009-11-17 02:14:36 +00005875 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5876 LookupQualifiedName(Operators, T1Rec->getDecl());
5877 Operators.suppressDiagnostics();
5878
Mike Stump11289f42009-09-09 15:08:12 +00005879 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005880 OperEnd = Operators.end();
5881 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005882 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005883 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005884 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005885 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005886 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005887 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005888}
5889
Douglas Gregora11693b2008-11-12 17:17:38 +00005890/// AddBuiltinCandidate - Add a candidate for a built-in
5891/// operator. ResultTy and ParamTys are the result and parameter types
5892/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005893/// arguments being passed to the candidate. IsAssignmentOperator
5894/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005895/// operator. NumContextualBoolArguments is the number of arguments
5896/// (at the beginning of the argument list) that will be contextually
5897/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005898void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005899 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005900 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005901 bool IsAssignmentOperator,
5902 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005903 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005904 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005905
Douglas Gregora11693b2008-11-12 17:17:38 +00005906 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005907 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005908 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005909 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005910 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005911 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005912 Candidate.BuiltinTypes.ResultTy = ResultTy;
5913 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5914 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5915
5916 // Determine the implicit conversion sequences for each of the
5917 // arguments.
5918 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005919 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005920 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005921 // C++ [over.match.oper]p4:
5922 // For the built-in assignment operators, conversions of the
5923 // left operand are restricted as follows:
5924 // -- no temporaries are introduced to hold the left operand, and
5925 // -- no user-defined conversions are applied to the left
5926 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005927 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005928 //
5929 // We block these conversions by turning off user-defined
5930 // conversions, since that is the only way that initialization of
5931 // a reference to a non-class type can occur from something that
5932 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005933 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005934 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005935 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005936 Candidate.Conversions[ArgIdx]
5937 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005938 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005939 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005940 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005941 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005942 /*InOverloadResolution=*/false,
5943 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005944 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005945 }
John McCall0d1da222010-01-12 00:44:57 +00005946 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005947 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005948 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005949 break;
5950 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005951 }
5952}
5953
5954/// BuiltinCandidateTypeSet - A set of types that will be used for the
5955/// candidate operator functions for built-in operators (C++
5956/// [over.built]). The types are separated into pointer types and
5957/// enumeration types.
5958class BuiltinCandidateTypeSet {
5959 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005960 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005961
5962 /// PointerTypes - The set of pointer types that will be used in the
5963 /// built-in candidates.
5964 TypeSet PointerTypes;
5965
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005966 /// MemberPointerTypes - The set of member pointer types that will be
5967 /// used in the built-in candidates.
5968 TypeSet MemberPointerTypes;
5969
Douglas Gregora11693b2008-11-12 17:17:38 +00005970 /// EnumerationTypes - The set of enumeration types that will be
5971 /// used in the built-in candidates.
5972 TypeSet EnumerationTypes;
5973
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005974 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005975 /// candidates.
5976 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005977
5978 /// \brief A flag indicating non-record types are viable candidates
5979 bool HasNonRecordTypes;
5980
5981 /// \brief A flag indicating whether either arithmetic or enumeration types
5982 /// were present in the candidate set.
5983 bool HasArithmeticOrEnumeralTypes;
5984
Douglas Gregor80af3132011-05-21 23:15:46 +00005985 /// \brief A flag indicating whether the nullptr type was present in the
5986 /// candidate set.
5987 bool HasNullPtrType;
5988
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005989 /// Sema - The semantic analysis instance where we are building the
5990 /// candidate type set.
5991 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005992
Douglas Gregora11693b2008-11-12 17:17:38 +00005993 /// Context - The AST context in which we will build the type sets.
5994 ASTContext &Context;
5995
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005996 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5997 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005998 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005999
6000public:
6001 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006002 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006003
Mike Stump11289f42009-09-09 15:08:12 +00006004 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006005 : HasNonRecordTypes(false),
6006 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006007 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006008 SemaRef(SemaRef),
6009 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006010
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006011 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006012 SourceLocation Loc,
6013 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006014 bool AllowExplicitConversions,
6015 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006016
6017 /// pointer_begin - First pointer type found;
6018 iterator pointer_begin() { return PointerTypes.begin(); }
6019
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006020 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006021 iterator pointer_end() { return PointerTypes.end(); }
6022
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006023 /// member_pointer_begin - First member pointer type found;
6024 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6025
6026 /// member_pointer_end - Past the last member pointer type found;
6027 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6028
Douglas Gregora11693b2008-11-12 17:17:38 +00006029 /// enumeration_begin - First enumeration type found;
6030 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6031
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006032 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006033 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006034
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006035 iterator vector_begin() { return VectorTypes.begin(); }
6036 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006037
6038 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6039 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006040 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006041};
6042
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006043/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006044/// the set of pointer types along with any more-qualified variants of
6045/// that type. For example, if @p Ty is "int const *", this routine
6046/// will add "int const *", "int const volatile *", "int const
6047/// restrict *", and "int const volatile restrict *" to the set of
6048/// pointer types. Returns true if the add of @p Ty itself succeeded,
6049/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006050///
6051/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006052bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006053BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6054 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006055
Douglas Gregora11693b2008-11-12 17:17:38 +00006056 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006057 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006058 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006060 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006061 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006062 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006063 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006064 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006065 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006066 buildObjCPtr = true;
6067 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006068 else
David Blaikie83d382b2011-09-23 05:06:16 +00006069 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006070 }
6071 else
6072 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006073
Sebastian Redl4990a632009-11-18 20:39:26 +00006074 // Don't add qualified variants of arrays. For one, they're not allowed
6075 // (the qualifier would sink to the element type), and for another, the
6076 // only overload situation where it matters is subscript or pointer +- int,
6077 // and those shouldn't have qualifier variants anyway.
6078 if (PointeeTy->isArrayType())
6079 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006080 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00006081 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00006082 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006083 bool hasVolatile = VisibleQuals.hasVolatile();
6084 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006085
John McCall8ccfcb52009-09-24 19:53:00 +00006086 // Iterate through all strict supersets of BaseCVR.
6087 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6088 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006089 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6090 // in the types.
6091 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6092 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00006093 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006094 if (!buildObjCPtr)
6095 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6096 else
6097 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00006098 }
6099
6100 return true;
6101}
6102
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006103/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6104/// to the set of pointer types along with any more-qualified variants of
6105/// that type. For example, if @p Ty is "int const *", this routine
6106/// will add "int const *", "int const volatile *", "int const
6107/// restrict *", and "int const volatile restrict *" to the set of
6108/// pointer types. Returns true if the add of @p Ty itself succeeded,
6109/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006110///
6111/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006112bool
6113BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6114 QualType Ty) {
6115 // Insert this type.
6116 if (!MemberPointerTypes.insert(Ty))
6117 return false;
6118
John McCall8ccfcb52009-09-24 19:53:00 +00006119 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6120 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006121
John McCall8ccfcb52009-09-24 19:53:00 +00006122 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006123 // Don't add qualified variants of arrays. For one, they're not allowed
6124 // (the qualifier would sink to the element type), and for another, the
6125 // only overload situation where it matters is subscript or pointer +- int,
6126 // and those shouldn't have qualifier variants anyway.
6127 if (PointeeTy->isArrayType())
6128 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006129 const Type *ClassTy = PointerTy->getClass();
6130
6131 // Iterate through all strict supersets of the pointee type's CVR
6132 // qualifiers.
6133 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6134 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6135 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006136
John McCall8ccfcb52009-09-24 19:53:00 +00006137 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006138 MemberPointerTypes.insert(
6139 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006140 }
6141
6142 return true;
6143}
6144
Douglas Gregora11693b2008-11-12 17:17:38 +00006145/// AddTypesConvertedFrom - Add each of the types to which the type @p
6146/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006147/// primarily interested in pointer types and enumeration types. We also
6148/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006149/// AllowUserConversions is true if we should look at the conversion
6150/// functions of a class type, and AllowExplicitConversions if we
6151/// should also include the explicit conversion functions of a class
6152/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006153void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006154BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006155 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006156 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006157 bool AllowExplicitConversions,
6158 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006159 // Only deal with canonical types.
6160 Ty = Context.getCanonicalType(Ty);
6161
6162 // Look through reference types; they aren't part of the type of an
6163 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006164 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006165 Ty = RefTy->getPointeeType();
6166
John McCall33ddac02011-01-19 10:06:00 +00006167 // If we're dealing with an array type, decay to the pointer.
6168 if (Ty->isArrayType())
6169 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6170
6171 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006172 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006173
Chandler Carruth00a38332010-12-13 01:44:01 +00006174 // Flag if we ever add a non-record type.
6175 const RecordType *TyRec = Ty->getAs<RecordType>();
6176 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6177
Chandler Carruth00a38332010-12-13 01:44:01 +00006178 // Flag if we encounter an arithmetic type.
6179 HasArithmeticOrEnumeralTypes =
6180 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6181
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006182 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6183 PointerTypes.insert(Ty);
6184 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006185 // Insert our type, and its more-qualified variants, into the set
6186 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006187 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006188 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006189 } else if (Ty->isMemberPointerType()) {
6190 // Member pointers are far easier, since the pointee can't be converted.
6191 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6192 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006193 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006194 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006195 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006196 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006197 // We treat vector types as arithmetic types in many contexts as an
6198 // extension.
6199 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006200 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006201 } else if (Ty->isNullPtrType()) {
6202 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006203 } else if (AllowUserConversions && TyRec) {
6204 // No conversion functions in incomplete types.
6205 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6206 return;
Mike Stump11289f42009-09-09 15:08:12 +00006207
Chandler Carruth00a38332010-12-13 01:44:01 +00006208 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6209 const UnresolvedSetImpl *Conversions
6210 = ClassDecl->getVisibleConversionFunctions();
6211 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6212 E = Conversions->end(); I != E; ++I) {
6213 NamedDecl *D = I.getDecl();
6214 if (isa<UsingShadowDecl>(D))
6215 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006216
Chandler Carruth00a38332010-12-13 01:44:01 +00006217 // Skip conversion function templates; they don't tell us anything
6218 // about which builtin types we can convert to.
6219 if (isa<FunctionTemplateDecl>(D))
6220 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006221
Chandler Carruth00a38332010-12-13 01:44:01 +00006222 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6223 if (AllowExplicitConversions || !Conv->isExplicit()) {
6224 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6225 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006226 }
6227 }
6228 }
6229}
6230
Douglas Gregor84605ae2009-08-24 13:43:27 +00006231/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6232/// the volatile- and non-volatile-qualified assignment operators for the
6233/// given type to the candidate set.
6234static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6235 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006236 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006237 unsigned NumArgs,
6238 OverloadCandidateSet &CandidateSet) {
6239 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006240
Douglas Gregor84605ae2009-08-24 13:43:27 +00006241 // T& operator=(T&, T)
6242 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6243 ParamTypes[1] = T;
6244 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6245 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006246
Douglas Gregor84605ae2009-08-24 13:43:27 +00006247 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6248 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006249 ParamTypes[0]
6250 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006251 ParamTypes[1] = T;
6252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006253 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006254 }
6255}
Mike Stump11289f42009-09-09 15:08:12 +00006256
Sebastian Redl1054fae2009-10-25 17:03:50 +00006257/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6258/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006259static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6260 Qualifiers VRQuals;
6261 const RecordType *TyRec;
6262 if (const MemberPointerType *RHSMPType =
6263 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006264 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006265 else
6266 TyRec = ArgExpr->getType()->getAs<RecordType>();
6267 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006268 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006269 VRQuals.addVolatile();
6270 VRQuals.addRestrict();
6271 return VRQuals;
6272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006273
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006274 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006275 if (!ClassDecl->hasDefinition())
6276 return VRQuals;
6277
John McCallad371252010-01-20 00:46:10 +00006278 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006279 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006280
John McCallad371252010-01-20 00:46:10 +00006281 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006282 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006283 NamedDecl *D = I.getDecl();
6284 if (isa<UsingShadowDecl>(D))
6285 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6286 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006287 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6288 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6289 CanTy = ResTypeRef->getPointeeType();
6290 // Need to go down the pointer/mempointer chain and add qualifiers
6291 // as see them.
6292 bool done = false;
6293 while (!done) {
6294 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6295 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006296 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006297 CanTy->getAs<MemberPointerType>())
6298 CanTy = ResTypeMPtr->getPointeeType();
6299 else
6300 done = true;
6301 if (CanTy.isVolatileQualified())
6302 VRQuals.addVolatile();
6303 if (CanTy.isRestrictQualified())
6304 VRQuals.addRestrict();
6305 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6306 return VRQuals;
6307 }
6308 }
6309 }
6310 return VRQuals;
6311}
John McCall52872982010-11-13 05:51:15 +00006312
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006313namespace {
John McCall52872982010-11-13 05:51:15 +00006314
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006315/// \brief Helper class to manage the addition of builtin operator overload
6316/// candidates. It provides shared state and utility methods used throughout
6317/// the process, as well as a helper method to add each group of builtin
6318/// operator overloads from the standard to a candidate set.
6319class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006320 // Common instance state available to all overload candidate addition methods.
6321 Sema &S;
6322 Expr **Args;
6323 unsigned NumArgs;
6324 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006325 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006326 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006327 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006328
Chandler Carruthc6586e52010-12-12 10:35:00 +00006329 // Define some constants used to index and iterate over the arithemetic types
6330 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006331 // The "promoted arithmetic types" are the arithmetic
6332 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006333 static const unsigned FirstIntegralType = 3;
6334 static const unsigned LastIntegralType = 18;
6335 static const unsigned FirstPromotedIntegralType = 3,
6336 LastPromotedIntegralType = 9;
6337 static const unsigned FirstPromotedArithmeticType = 0,
6338 LastPromotedArithmeticType = 9;
6339 static const unsigned NumArithmeticTypes = 18;
6340
Chandler Carruthc6586e52010-12-12 10:35:00 +00006341 /// \brief Get the canonical type for a given arithmetic type index.
6342 CanQualType getArithmeticType(unsigned index) {
6343 assert(index < NumArithmeticTypes);
6344 static CanQualType ASTContext::* const
6345 ArithmeticTypes[NumArithmeticTypes] = {
6346 // Start of promoted types.
6347 &ASTContext::FloatTy,
6348 &ASTContext::DoubleTy,
6349 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006350
Chandler Carruthc6586e52010-12-12 10:35:00 +00006351 // Start of integral types.
6352 &ASTContext::IntTy,
6353 &ASTContext::LongTy,
6354 &ASTContext::LongLongTy,
6355 &ASTContext::UnsignedIntTy,
6356 &ASTContext::UnsignedLongTy,
6357 &ASTContext::UnsignedLongLongTy,
6358 // End of promoted types.
6359
6360 &ASTContext::BoolTy,
6361 &ASTContext::CharTy,
6362 &ASTContext::WCharTy,
6363 &ASTContext::Char16Ty,
6364 &ASTContext::Char32Ty,
6365 &ASTContext::SignedCharTy,
6366 &ASTContext::ShortTy,
6367 &ASTContext::UnsignedCharTy,
6368 &ASTContext::UnsignedShortTy,
6369 // End of integral types.
6370 // FIXME: What about complex?
6371 };
6372 return S.Context.*ArithmeticTypes[index];
6373 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006374
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006375 /// \brief Gets the canonical type resulting from the usual arithemetic
6376 /// converions for the given arithmetic types.
6377 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6378 // Accelerator table for performing the usual arithmetic conversions.
6379 // The rules are basically:
6380 // - if either is floating-point, use the wider floating-point
6381 // - if same signedness, use the higher rank
6382 // - if same size, use unsigned of the higher rank
6383 // - use the larger type
6384 // These rules, together with the axiom that higher ranks are
6385 // never smaller, are sufficient to precompute all of these results
6386 // *except* when dealing with signed types of higher rank.
6387 // (we could precompute SLL x UI for all known platforms, but it's
6388 // better not to make any assumptions).
6389 enum PromotedType {
6390 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6391 };
6392 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6393 [LastPromotedArithmeticType] = {
6394 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6395 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6396 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6397 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6398 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6399 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6400 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6401 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6402 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6403 };
6404
6405 assert(L < LastPromotedArithmeticType);
6406 assert(R < LastPromotedArithmeticType);
6407 int Idx = ConversionsTable[L][R];
6408
6409 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006410 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006411
6412 // Slow path: we need to compare widths.
6413 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006414 CanQualType LT = getArithmeticType(L),
6415 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006416 unsigned LW = S.Context.getIntWidth(LT),
6417 RW = S.Context.getIntWidth(RT);
6418
6419 // If they're different widths, use the signed type.
6420 if (LW > RW) return LT;
6421 else if (LW < RW) return RT;
6422
6423 // Otherwise, use the unsigned type of the signed type's rank.
6424 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6425 assert(L == SLL || R == SLL);
6426 return S.Context.UnsignedLongLongTy;
6427 }
6428
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006429 /// \brief Helper method to factor out the common pattern of adding overloads
6430 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006431 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6432 bool HasVolatile) {
6433 QualType ParamTypes[2] = {
6434 S.Context.getLValueReferenceType(CandidateTy),
6435 S.Context.IntTy
6436 };
6437
6438 // Non-volatile version.
6439 if (NumArgs == 1)
6440 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6441 else
6442 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6443
6444 // Use a heuristic to reduce number of builtin candidates in the set:
6445 // add volatile version only if there are conversions to a volatile type.
6446 if (HasVolatile) {
6447 ParamTypes[0] =
6448 S.Context.getLValueReferenceType(
6449 S.Context.getVolatileType(CandidateTy));
6450 if (NumArgs == 1)
6451 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6452 else
6453 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6454 }
6455 }
6456
6457public:
6458 BuiltinOperatorOverloadBuilder(
6459 Sema &S, Expr **Args, unsigned NumArgs,
6460 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006461 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006462 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006463 OverloadCandidateSet &CandidateSet)
6464 : S(S), Args(Args), NumArgs(NumArgs),
6465 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006466 HasArithmeticOrEnumeralCandidateType(
6467 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006468 CandidateTypes(CandidateTypes),
6469 CandidateSet(CandidateSet) {
6470 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006471 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006472 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006473 assert(getArithmeticType(LastPromotedIntegralType - 1)
6474 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006475 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006476 assert(getArithmeticType(FirstPromotedArithmeticType)
6477 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006478 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006479 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6480 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006481 "Invalid last promoted arithmetic type");
6482 }
6483
6484 // C++ [over.built]p3:
6485 //
6486 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6487 // is either volatile or empty, there exist candidate operator
6488 // functions of the form
6489 //
6490 // VQ T& operator++(VQ T&);
6491 // T operator++(VQ T&, int);
6492 //
6493 // C++ [over.built]p4:
6494 //
6495 // For every pair (T, VQ), where T is an arithmetic type other
6496 // than bool, and VQ is either volatile or empty, there exist
6497 // candidate operator functions of the form
6498 //
6499 // VQ T& operator--(VQ T&);
6500 // T operator--(VQ T&, int);
6501 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006502 if (!HasArithmeticOrEnumeralCandidateType)
6503 return;
6504
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006505 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6506 Arith < NumArithmeticTypes; ++Arith) {
6507 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006508 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006509 VisibleTypeConversionsQuals.hasVolatile());
6510 }
6511 }
6512
6513 // C++ [over.built]p5:
6514 //
6515 // For every pair (T, VQ), where T is a cv-qualified or
6516 // cv-unqualified object type, and VQ is either volatile or
6517 // empty, there exist candidate operator functions of the form
6518 //
6519 // T*VQ& operator++(T*VQ&);
6520 // T*VQ& operator--(T*VQ&);
6521 // T* operator++(T*VQ&, int);
6522 // T* operator--(T*VQ&, int);
6523 void addPlusPlusMinusMinusPointerOverloads() {
6524 for (BuiltinCandidateTypeSet::iterator
6525 Ptr = CandidateTypes[0].pointer_begin(),
6526 PtrEnd = CandidateTypes[0].pointer_end();
6527 Ptr != PtrEnd; ++Ptr) {
6528 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006529 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006530 continue;
6531
6532 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6533 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6534 VisibleTypeConversionsQuals.hasVolatile()));
6535 }
6536 }
6537
6538 // C++ [over.built]p6:
6539 // For every cv-qualified or cv-unqualified object type T, there
6540 // exist candidate operator functions of the form
6541 //
6542 // T& operator*(T*);
6543 //
6544 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006545 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006546 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006547 // T& operator*(T*);
6548 void addUnaryStarPointerOverloads() {
6549 for (BuiltinCandidateTypeSet::iterator
6550 Ptr = CandidateTypes[0].pointer_begin(),
6551 PtrEnd = CandidateTypes[0].pointer_end();
6552 Ptr != PtrEnd; ++Ptr) {
6553 QualType ParamTy = *Ptr;
6554 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006555 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6556 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006557
Douglas Gregor02824322011-01-26 19:30:28 +00006558 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6559 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6560 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006562 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6563 &ParamTy, Args, 1, CandidateSet);
6564 }
6565 }
6566
6567 // C++ [over.built]p9:
6568 // For every promoted arithmetic type T, there exist candidate
6569 // operator functions of the form
6570 //
6571 // T operator+(T);
6572 // T operator-(T);
6573 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006574 if (!HasArithmeticOrEnumeralCandidateType)
6575 return;
6576
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006577 for (unsigned Arith = FirstPromotedArithmeticType;
6578 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006579 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006580 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6581 }
6582
6583 // Extension: We also add these operators for vector types.
6584 for (BuiltinCandidateTypeSet::iterator
6585 Vec = CandidateTypes[0].vector_begin(),
6586 VecEnd = CandidateTypes[0].vector_end();
6587 Vec != VecEnd; ++Vec) {
6588 QualType VecTy = *Vec;
6589 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6590 }
6591 }
6592
6593 // C++ [over.built]p8:
6594 // For every type T, there exist candidate operator functions of
6595 // the form
6596 //
6597 // T* operator+(T*);
6598 void addUnaryPlusPointerOverloads() {
6599 for (BuiltinCandidateTypeSet::iterator
6600 Ptr = CandidateTypes[0].pointer_begin(),
6601 PtrEnd = CandidateTypes[0].pointer_end();
6602 Ptr != PtrEnd; ++Ptr) {
6603 QualType ParamTy = *Ptr;
6604 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6605 }
6606 }
6607
6608 // C++ [over.built]p10:
6609 // For every promoted integral type T, there exist candidate
6610 // operator functions of the form
6611 //
6612 // T operator~(T);
6613 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006614 if (!HasArithmeticOrEnumeralCandidateType)
6615 return;
6616
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006617 for (unsigned Int = FirstPromotedIntegralType;
6618 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006619 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006620 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6621 }
6622
6623 // Extension: We also add this operator for vector types.
6624 for (BuiltinCandidateTypeSet::iterator
6625 Vec = CandidateTypes[0].vector_begin(),
6626 VecEnd = CandidateTypes[0].vector_end();
6627 Vec != VecEnd; ++Vec) {
6628 QualType VecTy = *Vec;
6629 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6630 }
6631 }
6632
6633 // C++ [over.match.oper]p16:
6634 // For every pointer to member type T, there exist candidate operator
6635 // functions of the form
6636 //
6637 // bool operator==(T,T);
6638 // bool operator!=(T,T);
6639 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6640 /// Set of (canonical) types that we've already handled.
6641 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6642
6643 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6644 for (BuiltinCandidateTypeSet::iterator
6645 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6646 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6647 MemPtr != MemPtrEnd;
6648 ++MemPtr) {
6649 // Don't add the same builtin candidate twice.
6650 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6651 continue;
6652
6653 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6654 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6655 CandidateSet);
6656 }
6657 }
6658 }
6659
6660 // C++ [over.built]p15:
6661 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006662 // For every T, where T is an enumeration type, a pointer type, or
6663 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006664 //
6665 // bool operator<(T, T);
6666 // bool operator>(T, T);
6667 // bool operator<=(T, T);
6668 // bool operator>=(T, T);
6669 // bool operator==(T, T);
6670 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006671 void addRelationalPointerOrEnumeralOverloads() {
6672 // C++ [over.built]p1:
6673 // If there is a user-written candidate with the same name and parameter
6674 // types as a built-in candidate operator function, the built-in operator
6675 // function is hidden and is not included in the set of candidate
6676 // functions.
6677 //
6678 // The text is actually in a note, but if we don't implement it then we end
6679 // up with ambiguities when the user provides an overloaded operator for
6680 // an enumeration type. Note that only enumeration types have this problem,
6681 // so we track which enumeration types we've seen operators for. Also, the
6682 // only other overloaded operator with enumeration argumenst, operator=,
6683 // cannot be overloaded for enumeration types, so this is the only place
6684 // where we must suppress candidates like this.
6685 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6686 UserDefinedBinaryOperators;
6687
6688 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6689 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6690 CandidateTypes[ArgIdx].enumeration_end()) {
6691 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6692 CEnd = CandidateSet.end();
6693 C != CEnd; ++C) {
6694 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6695 continue;
6696
6697 QualType FirstParamType =
6698 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6699 QualType SecondParamType =
6700 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6701
6702 // Skip if either parameter isn't of enumeral type.
6703 if (!FirstParamType->isEnumeralType() ||
6704 !SecondParamType->isEnumeralType())
6705 continue;
6706
6707 // Add this operator to the set of known user-defined operators.
6708 UserDefinedBinaryOperators.insert(
6709 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6710 S.Context.getCanonicalType(SecondParamType)));
6711 }
6712 }
6713 }
6714
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006715 /// Set of (canonical) types that we've already handled.
6716 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6717
6718 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6719 for (BuiltinCandidateTypeSet::iterator
6720 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6721 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6722 Ptr != PtrEnd; ++Ptr) {
6723 // Don't add the same builtin candidate twice.
6724 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6725 continue;
6726
6727 QualType ParamTypes[2] = { *Ptr, *Ptr };
6728 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6729 CandidateSet);
6730 }
6731 for (BuiltinCandidateTypeSet::iterator
6732 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6733 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6734 Enum != EnumEnd; ++Enum) {
6735 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6736
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006737 // Don't add the same builtin candidate twice, or if a user defined
6738 // candidate exists.
6739 if (!AddedTypes.insert(CanonType) ||
6740 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6741 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006742 continue;
6743
6744 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006745 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6746 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006747 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006748
6749 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6750 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6751 if (AddedTypes.insert(NullPtrTy) &&
6752 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6753 NullPtrTy))) {
6754 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6755 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6756 CandidateSet);
6757 }
6758 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006759 }
6760 }
6761
6762 // C++ [over.built]p13:
6763 //
6764 // For every cv-qualified or cv-unqualified object type T
6765 // there exist candidate operator functions of the form
6766 //
6767 // T* operator+(T*, ptrdiff_t);
6768 // T& operator[](T*, ptrdiff_t); [BELOW]
6769 // T* operator-(T*, ptrdiff_t);
6770 // T* operator+(ptrdiff_t, T*);
6771 // T& operator[](ptrdiff_t, T*); [BELOW]
6772 //
6773 // C++ [over.built]p14:
6774 //
6775 // For every T, where T is a pointer to object type, there
6776 // exist candidate operator functions of the form
6777 //
6778 // ptrdiff_t operator-(T, T);
6779 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6780 /// Set of (canonical) types that we've already handled.
6781 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6782
6783 for (int Arg = 0; Arg < 2; ++Arg) {
6784 QualType AsymetricParamTypes[2] = {
6785 S.Context.getPointerDiffType(),
6786 S.Context.getPointerDiffType(),
6787 };
6788 for (BuiltinCandidateTypeSet::iterator
6789 Ptr = CandidateTypes[Arg].pointer_begin(),
6790 PtrEnd = CandidateTypes[Arg].pointer_end();
6791 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006792 QualType PointeeTy = (*Ptr)->getPointeeType();
6793 if (!PointeeTy->isObjectType())
6794 continue;
6795
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006796 AsymetricParamTypes[Arg] = *Ptr;
6797 if (Arg == 0 || Op == OO_Plus) {
6798 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6799 // T* operator+(ptrdiff_t, T*);
6800 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6801 CandidateSet);
6802 }
6803 if (Op == OO_Minus) {
6804 // ptrdiff_t operator-(T, T);
6805 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6806 continue;
6807
6808 QualType ParamTypes[2] = { *Ptr, *Ptr };
6809 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6810 Args, 2, CandidateSet);
6811 }
6812 }
6813 }
6814 }
6815
6816 // C++ [over.built]p12:
6817 //
6818 // For every pair of promoted arithmetic types L and R, there
6819 // exist candidate operator functions of the form
6820 //
6821 // LR operator*(L, R);
6822 // LR operator/(L, R);
6823 // LR operator+(L, R);
6824 // LR operator-(L, R);
6825 // bool operator<(L, R);
6826 // bool operator>(L, R);
6827 // bool operator<=(L, R);
6828 // bool operator>=(L, R);
6829 // bool operator==(L, R);
6830 // bool operator!=(L, R);
6831 //
6832 // where LR is the result of the usual arithmetic conversions
6833 // between types L and R.
6834 //
6835 // C++ [over.built]p24:
6836 //
6837 // For every pair of promoted arithmetic types L and R, there exist
6838 // candidate operator functions of the form
6839 //
6840 // LR operator?(bool, L, R);
6841 //
6842 // where LR is the result of the usual arithmetic conversions
6843 // between types L and R.
6844 // Our candidates ignore the first parameter.
6845 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006846 if (!HasArithmeticOrEnumeralCandidateType)
6847 return;
6848
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006849 for (unsigned Left = FirstPromotedArithmeticType;
6850 Left < LastPromotedArithmeticType; ++Left) {
6851 for (unsigned Right = FirstPromotedArithmeticType;
6852 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006853 QualType LandR[2] = { getArithmeticType(Left),
6854 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006855 QualType Result =
6856 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006857 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006858 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6859 }
6860 }
6861
6862 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6863 // conditional operator for vector types.
6864 for (BuiltinCandidateTypeSet::iterator
6865 Vec1 = CandidateTypes[0].vector_begin(),
6866 Vec1End = CandidateTypes[0].vector_end();
6867 Vec1 != Vec1End; ++Vec1) {
6868 for (BuiltinCandidateTypeSet::iterator
6869 Vec2 = CandidateTypes[1].vector_begin(),
6870 Vec2End = CandidateTypes[1].vector_end();
6871 Vec2 != Vec2End; ++Vec2) {
6872 QualType LandR[2] = { *Vec1, *Vec2 };
6873 QualType Result = S.Context.BoolTy;
6874 if (!isComparison) {
6875 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6876 Result = *Vec1;
6877 else
6878 Result = *Vec2;
6879 }
6880
6881 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6882 }
6883 }
6884 }
6885
6886 // C++ [over.built]p17:
6887 //
6888 // For every pair of promoted integral types L and R, there
6889 // exist candidate operator functions of the form
6890 //
6891 // LR operator%(L, R);
6892 // LR operator&(L, R);
6893 // LR operator^(L, R);
6894 // LR operator|(L, R);
6895 // L operator<<(L, R);
6896 // L operator>>(L, R);
6897 //
6898 // where LR is the result of the usual arithmetic conversions
6899 // between types L and R.
6900 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006901 if (!HasArithmeticOrEnumeralCandidateType)
6902 return;
6903
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006904 for (unsigned Left = FirstPromotedIntegralType;
6905 Left < LastPromotedIntegralType; ++Left) {
6906 for (unsigned Right = FirstPromotedIntegralType;
6907 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006908 QualType LandR[2] = { getArithmeticType(Left),
6909 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006910 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6911 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006912 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006913 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6914 }
6915 }
6916 }
6917
6918 // C++ [over.built]p20:
6919 //
6920 // For every pair (T, VQ), where T is an enumeration or
6921 // pointer to member type and VQ is either volatile or
6922 // empty, there exist candidate operator functions of the form
6923 //
6924 // VQ T& operator=(VQ T&, T);
6925 void addAssignmentMemberPointerOrEnumeralOverloads() {
6926 /// Set of (canonical) types that we've already handled.
6927 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6928
6929 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6930 for (BuiltinCandidateTypeSet::iterator
6931 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6932 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6933 Enum != EnumEnd; ++Enum) {
6934 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6935 continue;
6936
6937 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6938 CandidateSet);
6939 }
6940
6941 for (BuiltinCandidateTypeSet::iterator
6942 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6943 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6944 MemPtr != MemPtrEnd; ++MemPtr) {
6945 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6946 continue;
6947
6948 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6949 CandidateSet);
6950 }
6951 }
6952 }
6953
6954 // C++ [over.built]p19:
6955 //
6956 // For every pair (T, VQ), where T is any type and VQ is either
6957 // volatile or empty, there exist candidate operator functions
6958 // of the form
6959 //
6960 // T*VQ& operator=(T*VQ&, T*);
6961 //
6962 // C++ [over.built]p21:
6963 //
6964 // For every pair (T, VQ), where T is a cv-qualified or
6965 // cv-unqualified object type and VQ is either volatile or
6966 // empty, there exist candidate operator functions of the form
6967 //
6968 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6969 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6970 void addAssignmentPointerOverloads(bool isEqualOp) {
6971 /// Set of (canonical) types that we've already handled.
6972 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6973
6974 for (BuiltinCandidateTypeSet::iterator
6975 Ptr = CandidateTypes[0].pointer_begin(),
6976 PtrEnd = CandidateTypes[0].pointer_end();
6977 Ptr != PtrEnd; ++Ptr) {
6978 // If this is operator=, keep track of the builtin candidates we added.
6979 if (isEqualOp)
6980 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006981 else if (!(*Ptr)->getPointeeType()->isObjectType())
6982 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006983
6984 // non-volatile version
6985 QualType ParamTypes[2] = {
6986 S.Context.getLValueReferenceType(*Ptr),
6987 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6988 };
6989 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6990 /*IsAssigmentOperator=*/ isEqualOp);
6991
6992 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6993 VisibleTypeConversionsQuals.hasVolatile()) {
6994 // volatile version
6995 ParamTypes[0] =
6996 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6997 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6998 /*IsAssigmentOperator=*/isEqualOp);
6999 }
7000 }
7001
7002 if (isEqualOp) {
7003 for (BuiltinCandidateTypeSet::iterator
7004 Ptr = CandidateTypes[1].pointer_begin(),
7005 PtrEnd = CandidateTypes[1].pointer_end();
7006 Ptr != PtrEnd; ++Ptr) {
7007 // Make sure we don't add the same candidate twice.
7008 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7009 continue;
7010
Chandler Carruth8e543b32010-12-12 08:17:55 +00007011 QualType ParamTypes[2] = {
7012 S.Context.getLValueReferenceType(*Ptr),
7013 *Ptr,
7014 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007015
7016 // non-volatile version
7017 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7018 /*IsAssigmentOperator=*/true);
7019
7020 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7021 VisibleTypeConversionsQuals.hasVolatile()) {
7022 // volatile version
7023 ParamTypes[0] =
7024 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007025 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7026 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007027 }
7028 }
7029 }
7030 }
7031
7032 // C++ [over.built]p18:
7033 //
7034 // For every triple (L, VQ, R), where L is an arithmetic type,
7035 // VQ is either volatile or empty, and R is a promoted
7036 // arithmetic type, there exist candidate operator functions of
7037 // the form
7038 //
7039 // VQ L& operator=(VQ L&, R);
7040 // VQ L& operator*=(VQ L&, R);
7041 // VQ L& operator/=(VQ L&, R);
7042 // VQ L& operator+=(VQ L&, R);
7043 // VQ L& operator-=(VQ L&, R);
7044 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007045 if (!HasArithmeticOrEnumeralCandidateType)
7046 return;
7047
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007048 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7049 for (unsigned Right = FirstPromotedArithmeticType;
7050 Right < LastPromotedArithmeticType; ++Right) {
7051 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007052 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007053
7054 // Add this built-in operator as a candidate (VQ is empty).
7055 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007056 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007057 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7058 /*IsAssigmentOperator=*/isEqualOp);
7059
7060 // Add this built-in operator as a candidate (VQ is 'volatile').
7061 if (VisibleTypeConversionsQuals.hasVolatile()) {
7062 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007063 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007064 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007065 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7066 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007067 /*IsAssigmentOperator=*/isEqualOp);
7068 }
7069 }
7070 }
7071
7072 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7073 for (BuiltinCandidateTypeSet::iterator
7074 Vec1 = CandidateTypes[0].vector_begin(),
7075 Vec1End = CandidateTypes[0].vector_end();
7076 Vec1 != Vec1End; ++Vec1) {
7077 for (BuiltinCandidateTypeSet::iterator
7078 Vec2 = CandidateTypes[1].vector_begin(),
7079 Vec2End = CandidateTypes[1].vector_end();
7080 Vec2 != Vec2End; ++Vec2) {
7081 QualType ParamTypes[2];
7082 ParamTypes[1] = *Vec2;
7083 // Add this built-in operator as a candidate (VQ is empty).
7084 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7085 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7086 /*IsAssigmentOperator=*/isEqualOp);
7087
7088 // Add this built-in operator as a candidate (VQ is 'volatile').
7089 if (VisibleTypeConversionsQuals.hasVolatile()) {
7090 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7091 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007092 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7093 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007094 /*IsAssigmentOperator=*/isEqualOp);
7095 }
7096 }
7097 }
7098 }
7099
7100 // C++ [over.built]p22:
7101 //
7102 // For every triple (L, VQ, R), where L is an integral type, VQ
7103 // is either volatile or empty, and R is a promoted integral
7104 // type, there exist candidate operator functions of the form
7105 //
7106 // VQ L& operator%=(VQ L&, R);
7107 // VQ L& operator<<=(VQ L&, R);
7108 // VQ L& operator>>=(VQ L&, R);
7109 // VQ L& operator&=(VQ L&, R);
7110 // VQ L& operator^=(VQ L&, R);
7111 // VQ L& operator|=(VQ L&, R);
7112 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007113 if (!HasArithmeticOrEnumeralCandidateType)
7114 return;
7115
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007116 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7117 for (unsigned Right = FirstPromotedIntegralType;
7118 Right < LastPromotedIntegralType; ++Right) {
7119 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007120 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007121
7122 // Add this built-in operator as a candidate (VQ is empty).
7123 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007124 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007125 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7126 if (VisibleTypeConversionsQuals.hasVolatile()) {
7127 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007128 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007129 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7130 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7131 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7132 CandidateSet);
7133 }
7134 }
7135 }
7136 }
7137
7138 // C++ [over.operator]p23:
7139 //
7140 // There also exist candidate operator functions of the form
7141 //
7142 // bool operator!(bool);
7143 // bool operator&&(bool, bool);
7144 // bool operator||(bool, bool);
7145 void addExclaimOverload() {
7146 QualType ParamTy = S.Context.BoolTy;
7147 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7148 /*IsAssignmentOperator=*/false,
7149 /*NumContextualBoolArguments=*/1);
7150 }
7151 void addAmpAmpOrPipePipeOverload() {
7152 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7153 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7154 /*IsAssignmentOperator=*/false,
7155 /*NumContextualBoolArguments=*/2);
7156 }
7157
7158 // C++ [over.built]p13:
7159 //
7160 // For every cv-qualified or cv-unqualified object type T there
7161 // exist candidate operator functions of the form
7162 //
7163 // T* operator+(T*, ptrdiff_t); [ABOVE]
7164 // T& operator[](T*, ptrdiff_t);
7165 // T* operator-(T*, ptrdiff_t); [ABOVE]
7166 // T* operator+(ptrdiff_t, T*); [ABOVE]
7167 // T& operator[](ptrdiff_t, T*);
7168 void addSubscriptOverloads() {
7169 for (BuiltinCandidateTypeSet::iterator
7170 Ptr = CandidateTypes[0].pointer_begin(),
7171 PtrEnd = CandidateTypes[0].pointer_end();
7172 Ptr != PtrEnd; ++Ptr) {
7173 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7174 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007175 if (!PointeeType->isObjectType())
7176 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007178 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7179
7180 // T& operator[](T*, ptrdiff_t)
7181 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7182 }
7183
7184 for (BuiltinCandidateTypeSet::iterator
7185 Ptr = CandidateTypes[1].pointer_begin(),
7186 PtrEnd = CandidateTypes[1].pointer_end();
7187 Ptr != PtrEnd; ++Ptr) {
7188 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7189 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007190 if (!PointeeType->isObjectType())
7191 continue;
7192
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007193 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7194
7195 // T& operator[](ptrdiff_t, T*)
7196 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7197 }
7198 }
7199
7200 // C++ [over.built]p11:
7201 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7202 // C1 is the same type as C2 or is a derived class of C2, T is an object
7203 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7204 // there exist candidate operator functions of the form
7205 //
7206 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7207 //
7208 // where CV12 is the union of CV1 and CV2.
7209 void addArrowStarOverloads() {
7210 for (BuiltinCandidateTypeSet::iterator
7211 Ptr = CandidateTypes[0].pointer_begin(),
7212 PtrEnd = CandidateTypes[0].pointer_end();
7213 Ptr != PtrEnd; ++Ptr) {
7214 QualType C1Ty = (*Ptr);
7215 QualType C1;
7216 QualifierCollector Q1;
7217 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7218 if (!isa<RecordType>(C1))
7219 continue;
7220 // heuristic to reduce number of builtin candidates in the set.
7221 // Add volatile/restrict version only if there are conversions to a
7222 // volatile/restrict type.
7223 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7224 continue;
7225 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7226 continue;
7227 for (BuiltinCandidateTypeSet::iterator
7228 MemPtr = CandidateTypes[1].member_pointer_begin(),
7229 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7230 MemPtr != MemPtrEnd; ++MemPtr) {
7231 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7232 QualType C2 = QualType(mptr->getClass(), 0);
7233 C2 = C2.getUnqualifiedType();
7234 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7235 break;
7236 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7237 // build CV12 T&
7238 QualType T = mptr->getPointeeType();
7239 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7240 T.isVolatileQualified())
7241 continue;
7242 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7243 T.isRestrictQualified())
7244 continue;
7245 T = Q1.apply(S.Context, T);
7246 QualType ResultTy = S.Context.getLValueReferenceType(T);
7247 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7248 }
7249 }
7250 }
7251
7252 // Note that we don't consider the first argument, since it has been
7253 // contextually converted to bool long ago. The candidates below are
7254 // therefore added as binary.
7255 //
7256 // C++ [over.built]p25:
7257 // For every type T, where T is a pointer, pointer-to-member, or scoped
7258 // enumeration type, there exist candidate operator functions of the form
7259 //
7260 // T operator?(bool, T, T);
7261 //
7262 void addConditionalOperatorOverloads() {
7263 /// Set of (canonical) types that we've already handled.
7264 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7265
7266 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7267 for (BuiltinCandidateTypeSet::iterator
7268 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7269 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7270 Ptr != PtrEnd; ++Ptr) {
7271 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7272 continue;
7273
7274 QualType ParamTypes[2] = { *Ptr, *Ptr };
7275 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7276 }
7277
7278 for (BuiltinCandidateTypeSet::iterator
7279 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7280 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7281 MemPtr != MemPtrEnd; ++MemPtr) {
7282 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7283 continue;
7284
7285 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7286 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7287 }
7288
David Blaikiebbafb8a2012-03-11 07:00:24 +00007289 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007290 for (BuiltinCandidateTypeSet::iterator
7291 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7292 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7293 Enum != EnumEnd; ++Enum) {
7294 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7295 continue;
7296
7297 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7298 continue;
7299
7300 QualType ParamTypes[2] = { *Enum, *Enum };
7301 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7302 }
7303 }
7304 }
7305 }
7306};
7307
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007308} // end anonymous namespace
7309
7310/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7311/// operator overloads to the candidate set (C++ [over.built]), based
7312/// on the operator @p Op and the arguments given. For example, if the
7313/// operator is a binary '+', this routine might add "int
7314/// operator+(int, int)" to cover integer addition.
7315void
7316Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7317 SourceLocation OpLoc,
7318 Expr **Args, unsigned NumArgs,
7319 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007320 // Find all of the types that the arguments can convert to, but only
7321 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007322 // that make use of these types. Also record whether we encounter non-record
7323 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007324 Qualifiers VisibleTypeConversionsQuals;
7325 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007326 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7327 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007328
7329 bool HasNonRecordCandidateType = false;
7330 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007331 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007332 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7333 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7334 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7335 OpLoc,
7336 true,
7337 (Op == OO_Exclaim ||
7338 Op == OO_AmpAmp ||
7339 Op == OO_PipePipe),
7340 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007341 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7342 CandidateTypes[ArgIdx].hasNonRecordTypes();
7343 HasArithmeticOrEnumeralCandidateType =
7344 HasArithmeticOrEnumeralCandidateType ||
7345 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007346 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007347
Chandler Carruth00a38332010-12-13 01:44:01 +00007348 // Exit early when no non-record types have been added to the candidate set
7349 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007350 //
7351 // We can't exit early for !, ||, or &&, since there we have always have
7352 // 'bool' overloads.
7353 if (!HasNonRecordCandidateType &&
7354 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007355 return;
7356
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007357 // Setup an object to manage the common state for building overloads.
7358 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7359 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007360 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007361 CandidateTypes, CandidateSet);
7362
7363 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007364 switch (Op) {
7365 case OO_None:
7366 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007367 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007368
Chandler Carruth5184de02010-12-12 08:51:33 +00007369 case OO_New:
7370 case OO_Delete:
7371 case OO_Array_New:
7372 case OO_Array_Delete:
7373 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007374 llvm_unreachable(
7375 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007376
7377 case OO_Comma:
7378 case OO_Arrow:
7379 // C++ [over.match.oper]p3:
7380 // -- For the operator ',', the unary operator '&', or the
7381 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007382 break;
7383
7384 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007385 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007386 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007387 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007388
7389 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007390 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007391 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007392 } else {
7393 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7394 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7395 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007396 break;
7397
Chandler Carruth5184de02010-12-12 08:51:33 +00007398 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007399 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007400 OpBuilder.addUnaryStarPointerOverloads();
7401 else
7402 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7403 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007404
Chandler Carruth5184de02010-12-12 08:51:33 +00007405 case OO_Slash:
7406 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007407 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007408
7409 case OO_PlusPlus:
7410 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007411 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7412 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007413 break;
7414
Douglas Gregor84605ae2009-08-24 13:43:27 +00007415 case OO_EqualEqual:
7416 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007417 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007418 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007419
Douglas Gregora11693b2008-11-12 17:17:38 +00007420 case OO_Less:
7421 case OO_Greater:
7422 case OO_LessEqual:
7423 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007424 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007425 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7426 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007427
Douglas Gregora11693b2008-11-12 17:17:38 +00007428 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007429 case OO_Caret:
7430 case OO_Pipe:
7431 case OO_LessLess:
7432 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007433 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007434 break;
7435
Chandler Carruth5184de02010-12-12 08:51:33 +00007436 case OO_Amp: // '&' is either unary or binary
7437 if (NumArgs == 1)
7438 // C++ [over.match.oper]p3:
7439 // -- For the operator ',', the unary operator '&', or the
7440 // operator '->', the built-in candidates set is empty.
7441 break;
7442
7443 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7444 break;
7445
7446 case OO_Tilde:
7447 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7448 break;
7449
Douglas Gregora11693b2008-11-12 17:17:38 +00007450 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007451 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007452 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007453
7454 case OO_PlusEqual:
7455 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007456 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007457 // Fall through.
7458
7459 case OO_StarEqual:
7460 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007461 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007462 break;
7463
7464 case OO_PercentEqual:
7465 case OO_LessLessEqual:
7466 case OO_GreaterGreaterEqual:
7467 case OO_AmpEqual:
7468 case OO_CaretEqual:
7469 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007470 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007471 break;
7472
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007473 case OO_Exclaim:
7474 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007475 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007476
Douglas Gregora11693b2008-11-12 17:17:38 +00007477 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007478 case OO_PipePipe:
7479 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007480 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007481
7482 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007483 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007484 break;
7485
7486 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007487 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007488 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007489
7490 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007491 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007492 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7493 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007494 }
7495}
7496
Douglas Gregore254f902009-02-04 00:32:51 +00007497/// \brief Add function candidates found via argument-dependent lookup
7498/// to the set of overloading candidates.
7499///
7500/// This routine performs argument-dependent name lookup based on the
7501/// given function name (which may also be an operator name) and adds
7502/// all of the overload candidates found by ADL to the overload
7503/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007504void
Douglas Gregore254f902009-02-04 00:32:51 +00007505Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007506 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007507 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007508 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007509 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007510 bool PartialOverloading,
7511 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007512 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007513
John McCall91f61fc2010-01-26 06:04:06 +00007514 // FIXME: This approach for uniquing ADL results (and removing
7515 // redundant candidates from the set) relies on pointer-equality,
7516 // which means we need to key off the canonical decl. However,
7517 // always going back to the canonical decl might not get us the
7518 // right set of default arguments. What default arguments are
7519 // we supposed to consider on ADL candidates, anyway?
7520
Douglas Gregorcabea402009-09-22 15:41:20 +00007521 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007522 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007523 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007524
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007525 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007526 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7527 CandEnd = CandidateSet.end();
7528 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007529 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007530 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007531 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007532 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007533 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007534
7535 // For each of the ADL candidates we found, add it to the overload
7536 // set.
John McCall8fe68082010-01-26 07:16:45 +00007537 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007538 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007539 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007540 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007541 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007542
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007543 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7544 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007545 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007546 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007547 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007548 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007549 }
Douglas Gregore254f902009-02-04 00:32:51 +00007550}
7551
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007552/// isBetterOverloadCandidate - Determines whether the first overload
7553/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007554bool
John McCall5c32be02010-08-24 20:38:10 +00007555isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007556 const OverloadCandidate &Cand1,
7557 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007558 SourceLocation Loc,
7559 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007560 // Define viable functions to be better candidates than non-viable
7561 // functions.
7562 if (!Cand2.Viable)
7563 return Cand1.Viable;
7564 else if (!Cand1.Viable)
7565 return false;
7566
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007567 // C++ [over.match.best]p1:
7568 //
7569 // -- if F is a static member function, ICS1(F) is defined such
7570 // that ICS1(F) is neither better nor worse than ICS1(G) for
7571 // any function G, and, symmetrically, ICS1(G) is neither
7572 // better nor worse than ICS1(F).
7573 unsigned StartArg = 0;
7574 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7575 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007576
Douglas Gregord3cb3562009-07-07 23:38:56 +00007577 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007578 // A viable function F1 is defined to be a better function than another
7579 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007580 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007581 unsigned NumArgs = Cand1.NumConversions;
7582 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007583 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007584 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007585 switch (CompareImplicitConversionSequences(S,
7586 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007587 Cand2.Conversions[ArgIdx])) {
7588 case ImplicitConversionSequence::Better:
7589 // Cand1 has a better conversion sequence.
7590 HasBetterConversion = true;
7591 break;
7592
7593 case ImplicitConversionSequence::Worse:
7594 // Cand1 can't be better than Cand2.
7595 return false;
7596
7597 case ImplicitConversionSequence::Indistinguishable:
7598 // Do nothing.
7599 break;
7600 }
7601 }
7602
Mike Stump11289f42009-09-09 15:08:12 +00007603 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007604 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007605 if (HasBetterConversion)
7606 return true;
7607
Mike Stump11289f42009-09-09 15:08:12 +00007608 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007609 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007610 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007611 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7612 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007613
7614 // -- F1 and F2 are function template specializations, and the function
7615 // template for F1 is more specialized than the template for F2
7616 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007617 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007618 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007619 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007620 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007621 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7622 Cand2.Function->getPrimaryTemplate(),
7623 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007624 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007625 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007626 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007627 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007629
Douglas Gregora1f013e2008-11-07 22:36:19 +00007630 // -- the context is an initialization by user-defined conversion
7631 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7632 // from the return type of F1 to the destination type (i.e.,
7633 // the type of the entity being initialized) is a better
7634 // conversion sequence than the standard conversion sequence
7635 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007636 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007637 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007638 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007639 // First check whether we prefer one of the conversion functions over the
7640 // other. This only distinguishes the results in non-standard, extension
7641 // cases such as the conversion from a lambda closure type to a function
7642 // pointer or block.
7643 ImplicitConversionSequence::CompareKind FuncResult
7644 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7645 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7646 return FuncResult;
7647
John McCall5c32be02010-08-24 20:38:10 +00007648 switch (CompareStandardConversionSequences(S,
7649 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007650 Cand2.FinalConversion)) {
7651 case ImplicitConversionSequence::Better:
7652 // Cand1 has a better conversion sequence.
7653 return true;
7654
7655 case ImplicitConversionSequence::Worse:
7656 // Cand1 can't be better than Cand2.
7657 return false;
7658
7659 case ImplicitConversionSequence::Indistinguishable:
7660 // Do nothing
7661 break;
7662 }
7663 }
7664
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007665 return false;
7666}
7667
Mike Stump11289f42009-09-09 15:08:12 +00007668/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007669/// within an overload candidate set.
7670///
7671/// \param CandidateSet the set of candidate functions.
7672///
7673/// \param Loc the location of the function name (or operator symbol) for
7674/// which overload resolution occurs.
7675///
Mike Stump11289f42009-09-09 15:08:12 +00007676/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007677/// function, Best points to the candidate function found.
7678///
7679/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007680OverloadingResult
7681OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007682 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007683 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007684 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007685 Best = end();
7686 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7687 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007688 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007689 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007690 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007691 }
7692
7693 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007694 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007695 return OR_No_Viable_Function;
7696
7697 // Make sure that this function is better than every other viable
7698 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007699 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007700 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007701 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007702 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007703 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007704 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007705 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007706 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007707 }
Mike Stump11289f42009-09-09 15:08:12 +00007708
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007709 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007710 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007711 (Best->Function->isDeleted() ||
7712 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007713 return OR_Deleted;
7714
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007715 return OR_Success;
7716}
7717
John McCall53262c92010-01-12 02:15:36 +00007718namespace {
7719
7720enum OverloadCandidateKind {
7721 oc_function,
7722 oc_method,
7723 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007724 oc_function_template,
7725 oc_method_template,
7726 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007727 oc_implicit_default_constructor,
7728 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007729 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007730 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007731 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007732 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007733};
7734
John McCalle1ac8d12010-01-13 00:25:19 +00007735OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7736 FunctionDecl *Fn,
7737 std::string &Description) {
7738 bool isTemplate = false;
7739
7740 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7741 isTemplate = true;
7742 Description = S.getTemplateArgumentBindingsText(
7743 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7744 }
John McCallfd0b2f82010-01-06 09:43:14 +00007745
7746 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007747 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007748 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007749
Sebastian Redl08905022011-02-05 19:23:19 +00007750 if (Ctor->getInheritedConstructor())
7751 return oc_implicit_inherited_constructor;
7752
Alexis Hunt119c10e2011-05-25 23:16:36 +00007753 if (Ctor->isDefaultConstructor())
7754 return oc_implicit_default_constructor;
7755
7756 if (Ctor->isMoveConstructor())
7757 return oc_implicit_move_constructor;
7758
7759 assert(Ctor->isCopyConstructor() &&
7760 "unexpected sort of implicit constructor");
7761 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007762 }
7763
7764 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7765 // This actually gets spelled 'candidate function' for now, but
7766 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007767 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007768 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007769
Alexis Hunt119c10e2011-05-25 23:16:36 +00007770 if (Meth->isMoveAssignmentOperator())
7771 return oc_implicit_move_assignment;
7772
Douglas Gregor12695102012-02-10 08:36:38 +00007773 if (Meth->isCopyAssignmentOperator())
7774 return oc_implicit_copy_assignment;
7775
7776 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7777 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007778 }
7779
John McCalle1ac8d12010-01-13 00:25:19 +00007780 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007781}
7782
Sebastian Redl08905022011-02-05 19:23:19 +00007783void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7784 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7785 if (!Ctor) return;
7786
7787 Ctor = Ctor->getInheritedConstructor();
7788 if (!Ctor) return;
7789
7790 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7791}
7792
John McCall53262c92010-01-12 02:15:36 +00007793} // end anonymous namespace
7794
7795// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007796void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007797 std::string FnDesc;
7798 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007799 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7800 << (unsigned) K << FnDesc;
7801 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7802 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007803 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007804}
7805
Douglas Gregorb491ed32011-02-19 21:32:49 +00007806//Notes the location of all overload candidates designated through
7807// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007808void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007809 assert(OverloadedExpr->getType() == Context.OverloadTy);
7810
7811 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7812 OverloadExpr *OvlExpr = Ovl.Expression;
7813
7814 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7815 IEnd = OvlExpr->decls_end();
7816 I != IEnd; ++I) {
7817 if (FunctionTemplateDecl *FunTmpl =
7818 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007819 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007820 } else if (FunctionDecl *Fun
7821 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007822 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007823 }
7824 }
7825}
7826
John McCall0d1da222010-01-12 00:44:57 +00007827/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7828/// "lead" diagnostic; it will be given two arguments, the source and
7829/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007830void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7831 Sema &S,
7832 SourceLocation CaretLoc,
7833 const PartialDiagnostic &PDiag) const {
7834 S.Diag(CaretLoc, PDiag)
7835 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007836 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007837 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7838 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007839 }
John McCall12f97bc2010-01-08 04:41:39 +00007840}
7841
John McCall0d1da222010-01-12 00:44:57 +00007842namespace {
7843
John McCall6a61b522010-01-13 09:16:55 +00007844void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7845 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7846 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007847 assert(Cand->Function && "for now, candidate must be a function");
7848 FunctionDecl *Fn = Cand->Function;
7849
7850 // There's a conversion slot for the object argument if this is a
7851 // non-constructor method. Note that 'I' corresponds the
7852 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007853 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007854 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007855 if (I == 0)
7856 isObjectArgument = true;
7857 else
7858 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007859 }
7860
John McCalle1ac8d12010-01-13 00:25:19 +00007861 std::string FnDesc;
7862 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7863
John McCall6a61b522010-01-13 09:16:55 +00007864 Expr *FromExpr = Conv.Bad.FromExpr;
7865 QualType FromTy = Conv.Bad.getFromType();
7866 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007867
John McCallfb7ad0f2010-02-02 02:42:52 +00007868 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007869 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007870 Expr *E = FromExpr->IgnoreParens();
7871 if (isa<UnaryOperator>(E))
7872 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007873 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007874
7875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7876 << (unsigned) FnKind << FnDesc
7877 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7878 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007879 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007880 return;
7881 }
7882
John McCall6d174642010-01-23 08:10:49 +00007883 // Do some hand-waving analysis to see if the non-viability is due
7884 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007885 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7886 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7887 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7888 CToTy = RT->getPointeeType();
7889 else {
7890 // TODO: detect and diagnose the full richness of const mismatches.
7891 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7892 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7893 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7894 }
7895
7896 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7897 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00007898 Qualifiers FromQs = CFromTy.getQualifiers();
7899 Qualifiers ToQs = CToTy.getQualifiers();
7900
7901 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7902 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7903 << (unsigned) FnKind << FnDesc
7904 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7905 << FromTy
7906 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7907 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007908 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007909 return;
7910 }
7911
John McCall31168b02011-06-15 23:02:42 +00007912 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007913 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007914 << (unsigned) FnKind << FnDesc
7915 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7916 << FromTy
7917 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7918 << (unsigned) isObjectArgument << I+1;
7919 MaybeEmitInheritedConstructorNote(S, Fn);
7920 return;
7921 }
7922
Douglas Gregoraec25842011-04-26 23:16:46 +00007923 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7924 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7925 << (unsigned) FnKind << FnDesc
7926 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7927 << FromTy
7928 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7929 << (unsigned) isObjectArgument << I+1;
7930 MaybeEmitInheritedConstructorNote(S, Fn);
7931 return;
7932 }
7933
John McCall47000992010-01-14 03:28:57 +00007934 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7935 assert(CVR && "unexpected qualifiers mismatch");
7936
7937 if (isObjectArgument) {
7938 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7939 << (unsigned) FnKind << FnDesc
7940 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7941 << FromTy << (CVR - 1);
7942 } else {
7943 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7944 << (unsigned) FnKind << FnDesc
7945 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7946 << FromTy << (CVR - 1) << I+1;
7947 }
Sebastian Redl08905022011-02-05 19:23:19 +00007948 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007949 return;
7950 }
7951
Sebastian Redla72462c2011-09-24 17:48:32 +00007952 // Special diagnostic for failure to convert an initializer list, since
7953 // telling the user that it has type void is not useful.
7954 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7955 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7956 << (unsigned) FnKind << FnDesc
7957 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7958 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7959 MaybeEmitInheritedConstructorNote(S, Fn);
7960 return;
7961 }
7962
John McCall6d174642010-01-23 08:10:49 +00007963 // Diagnose references or pointers to incomplete types differently,
7964 // since it's far from impossible that the incompleteness triggered
7965 // the failure.
7966 QualType TempFromTy = FromTy.getNonReferenceType();
7967 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7968 TempFromTy = PTy->getPointeeType();
7969 if (TempFromTy->isIncompleteType()) {
7970 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7971 << (unsigned) FnKind << FnDesc
7972 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7973 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007974 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007975 return;
7976 }
7977
Douglas Gregor56f2e342010-06-30 23:01:39 +00007978 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007979 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007980 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7981 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7982 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7983 FromPtrTy->getPointeeType()) &&
7984 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7985 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007987 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007988 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007989 }
7990 } else if (const ObjCObjectPointerType *FromPtrTy
7991 = FromTy->getAs<ObjCObjectPointerType>()) {
7992 if (const ObjCObjectPointerType *ToPtrTy
7993 = ToTy->getAs<ObjCObjectPointerType>())
7994 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7995 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7996 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7997 FromPtrTy->getPointeeType()) &&
7998 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007999 BaseToDerivedConversion = 2;
8000 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8001 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8002 !FromTy->isIncompleteType() &&
8003 !ToRefTy->getPointeeType()->isIncompleteType() &&
8004 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
8005 BaseToDerivedConversion = 3;
8006 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008007
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008008 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008009 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008010 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008011 << (unsigned) FnKind << FnDesc
8012 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008013 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008014 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008015 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008016 return;
8017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008019 if (isa<ObjCObjectPointerType>(CFromTy) &&
8020 isa<PointerType>(CToTy)) {
8021 Qualifiers FromQs = CFromTy.getQualifiers();
8022 Qualifiers ToQs = CToTy.getQualifiers();
8023 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8024 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8025 << (unsigned) FnKind << FnDesc
8026 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8027 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8028 MaybeEmitInheritedConstructorNote(S, Fn);
8029 return;
8030 }
8031 }
8032
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008033 // Emit the generic diagnostic and, optionally, add the hints to it.
8034 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8035 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008036 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008037 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8038 << (unsigned) (Cand->Fix.Kind);
8039
8040 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008041 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8042 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008043 FDiag << *HI;
8044 S.Diag(Fn->getLocation(), FDiag);
8045
Sebastian Redl08905022011-02-05 19:23:19 +00008046 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008047}
8048
8049void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8050 unsigned NumFormalArgs) {
8051 // TODO: treat calls to a missing default constructor as a special case
8052
8053 FunctionDecl *Fn = Cand->Function;
8054 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8055
8056 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008057
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008058 // With invalid overloaded operators, it's possible that we think we
8059 // have an arity mismatch when it fact it looks like we have the
8060 // right number of arguments, because only overloaded operators have
8061 // the weird behavior of overloading member and non-member functions.
8062 // Just don't report anything.
8063 if (Fn->isInvalidDecl() &&
8064 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8065 return;
8066
John McCall6a61b522010-01-13 09:16:55 +00008067 // at least / at most / exactly
8068 unsigned mode, modeCount;
8069 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008070 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8071 (Cand->FailureKind == ovl_fail_bad_deduction &&
8072 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008073 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008074 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008075 mode = 0; // "at least"
8076 else
8077 mode = 2; // "exactly"
8078 modeCount = MinParams;
8079 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008080 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8081 (Cand->FailureKind == ovl_fail_bad_deduction &&
8082 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008083 if (MinParams != FnTy->getNumArgs())
8084 mode = 1; // "at most"
8085 else
8086 mode = 2; // "exactly"
8087 modeCount = FnTy->getNumArgs();
8088 }
8089
8090 std::string Description;
8091 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8092
8093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008094 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00008095 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008096 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008097}
8098
John McCall8b9ed552010-02-01 18:53:26 +00008099/// Diagnose a failed template-argument deduction.
8100void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008101 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008102 FunctionDecl *Fn = Cand->Function; // pattern
8103
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008104 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008105 NamedDecl *ParamD;
8106 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8107 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8108 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008109 switch (Cand->DeductionFailure.Result) {
8110 case Sema::TDK_Success:
8111 llvm_unreachable("TDK_success while diagnosing bad deduction");
8112
8113 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008114 assert(ParamD && "no parameter found for incomplete deduction result");
8115 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8116 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008117 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008118 return;
8119 }
8120
John McCall42d7d192010-08-05 09:05:08 +00008121 case Sema::TDK_Underqualified: {
8122 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8123 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8124
8125 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8126
8127 // Param will have been canonicalized, but it should just be a
8128 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008129 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008130 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008131 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008132 assert(S.Context.hasSameType(Param, NonCanonParam));
8133
8134 // Arg has also been canonicalized, but there's nothing we can do
8135 // about that. It also doesn't matter as much, because it won't
8136 // have any template parameters in it (because deduction isn't
8137 // done on dependent types).
8138 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8139
8140 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8141 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008142 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008143 return;
8144 }
8145
8146 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008147 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008148 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008149 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008150 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008151 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008152 which = 1;
8153 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008154 which = 2;
8155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008156
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008157 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008158 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008159 << *Cand->DeductionFailure.getFirstArg()
8160 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008161 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008162 return;
8163 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008164
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008165 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008166 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008167 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008168 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008169 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8170 << ParamD->getDeclName();
8171 else {
8172 int index = 0;
8173 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8174 index = TTP->getIndex();
8175 else if (NonTypeTemplateParmDecl *NTTP
8176 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8177 index = NTTP->getIndex();
8178 else
8179 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008180 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008181 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8182 << (index + 1);
8183 }
Sebastian Redl08905022011-02-05 19:23:19 +00008184 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008185 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008186
Douglas Gregor02eb4832010-05-08 18:13:28 +00008187 case Sema::TDK_TooManyArguments:
8188 case Sema::TDK_TooFewArguments:
8189 DiagnoseArityMismatch(S, Cand, NumArgs);
8190 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008191
8192 case Sema::TDK_InstantiationDepth:
8193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008194 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008195 return;
8196
8197 case Sema::TDK_SubstitutionFailure: {
8198 std::string ArgString;
8199 if (TemplateArgumentList *Args
8200 = Cand->DeductionFailure.getTemplateArgumentList())
8201 ArgString = S.getTemplateArgumentBindingsText(
8202 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8203 *Args);
8204 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8205 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00008206 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008207 return;
8208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008209
John McCall8b9ed552010-02-01 18:53:26 +00008210 // TODO: diagnose these individually, then kill off
8211 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008212 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008213 case Sema::TDK_FailedOverloadResolution:
8214 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008215 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008216 return;
8217 }
8218}
8219
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008220/// CUDA: diagnose an invalid call across targets.
8221void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8222 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8223 FunctionDecl *Callee = Cand->Function;
8224
8225 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8226 CalleeTarget = S.IdentifyCUDATarget(Callee);
8227
8228 std::string FnDesc;
8229 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8230
8231 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8232 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8233}
8234
John McCall8b9ed552010-02-01 18:53:26 +00008235/// Generates a 'note' diagnostic for an overload candidate. We've
8236/// already generated a primary error at the call site.
8237///
8238/// It really does need to be a single diagnostic with its caret
8239/// pointed at the candidate declaration. Yes, this creates some
8240/// major challenges of technical writing. Yes, this makes pointing
8241/// out problems with specific arguments quite awkward. It's still
8242/// better than generating twenty screens of text for every failed
8243/// overload.
8244///
8245/// It would be great to be able to express per-candidate problems
8246/// more richly for those diagnostic clients that cared, but we'd
8247/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008248void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008249 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008250 FunctionDecl *Fn = Cand->Function;
8251
John McCall12f97bc2010-01-08 04:41:39 +00008252 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008253 if (Cand->Viable && (Fn->isDeleted() ||
8254 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008255 std::string FnDesc;
8256 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008257
8258 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008259 << FnKind << FnDesc
8260 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008261 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008262 return;
John McCall12f97bc2010-01-08 04:41:39 +00008263 }
8264
John McCalle1ac8d12010-01-13 00:25:19 +00008265 // We don't really have anything else to say about viable candidates.
8266 if (Cand->Viable) {
8267 S.NoteOverloadCandidate(Fn);
8268 return;
8269 }
John McCall0d1da222010-01-12 00:44:57 +00008270
John McCall6a61b522010-01-13 09:16:55 +00008271 switch (Cand->FailureKind) {
8272 case ovl_fail_too_many_arguments:
8273 case ovl_fail_too_few_arguments:
8274 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008275
John McCall6a61b522010-01-13 09:16:55 +00008276 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008277 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008278
John McCallfe796dd2010-01-23 05:17:32 +00008279 case ovl_fail_trivial_conversion:
8280 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008281 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008282 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008283
John McCall65eb8792010-02-25 01:37:24 +00008284 case ovl_fail_bad_conversion: {
8285 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008286 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008287 if (Cand->Conversions[I].isBad())
8288 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008289
John McCall6a61b522010-01-13 09:16:55 +00008290 // FIXME: this currently happens when we're called from SemaInit
8291 // when user-conversion overload fails. Figure out how to handle
8292 // those conditions and diagnose them well.
8293 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008294 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008295
8296 case ovl_fail_bad_target:
8297 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008298 }
John McCalld3224162010-01-08 00:58:21 +00008299}
8300
8301void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8302 // Desugar the type of the surrogate down to a function type,
8303 // retaining as many typedefs as possible while still showing
8304 // the function type (and, therefore, its parameter types).
8305 QualType FnType = Cand->Surrogate->getConversionType();
8306 bool isLValueReference = false;
8307 bool isRValueReference = false;
8308 bool isPointer = false;
8309 if (const LValueReferenceType *FnTypeRef =
8310 FnType->getAs<LValueReferenceType>()) {
8311 FnType = FnTypeRef->getPointeeType();
8312 isLValueReference = true;
8313 } else if (const RValueReferenceType *FnTypeRef =
8314 FnType->getAs<RValueReferenceType>()) {
8315 FnType = FnTypeRef->getPointeeType();
8316 isRValueReference = true;
8317 }
8318 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8319 FnType = FnTypePtr->getPointeeType();
8320 isPointer = true;
8321 }
8322 // Desugar down to a function type.
8323 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8324 // Reconstruct the pointer/reference as appropriate.
8325 if (isPointer) FnType = S.Context.getPointerType(FnType);
8326 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8327 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8328
8329 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8330 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008331 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008332}
8333
8334void NoteBuiltinOperatorCandidate(Sema &S,
8335 const char *Opc,
8336 SourceLocation OpLoc,
8337 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008338 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008339 std::string TypeStr("operator");
8340 TypeStr += Opc;
8341 TypeStr += "(";
8342 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008343 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008344 TypeStr += ")";
8345 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8346 } else {
8347 TypeStr += ", ";
8348 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8349 TypeStr += ")";
8350 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8351 }
8352}
8353
8354void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8355 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008356 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008357 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8358 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008359 if (ICS.isBad()) break; // all meaningless after first invalid
8360 if (!ICS.isAmbiguous()) continue;
8361
John McCall5c32be02010-08-24 20:38:10 +00008362 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008363 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008364 }
8365}
8366
John McCall3712d9e2010-01-15 23:32:50 +00008367SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8368 if (Cand->Function)
8369 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008370 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008371 return Cand->Surrogate->getLocation();
8372 return SourceLocation();
8373}
8374
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008375static unsigned
8376RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008377 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008378 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008379 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008380
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008381 case Sema::TDK_Incomplete:
8382 return 1;
8383
8384 case Sema::TDK_Underqualified:
8385 case Sema::TDK_Inconsistent:
8386 return 2;
8387
8388 case Sema::TDK_SubstitutionFailure:
8389 case Sema::TDK_NonDeducedMismatch:
8390 return 3;
8391
8392 case Sema::TDK_InstantiationDepth:
8393 case Sema::TDK_FailedOverloadResolution:
8394 return 4;
8395
8396 case Sema::TDK_InvalidExplicitArguments:
8397 return 5;
8398
8399 case Sema::TDK_TooManyArguments:
8400 case Sema::TDK_TooFewArguments:
8401 return 6;
8402 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008403 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008404}
8405
John McCallad2587a2010-01-12 00:48:53 +00008406struct CompareOverloadCandidatesForDisplay {
8407 Sema &S;
8408 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008409
8410 bool operator()(const OverloadCandidate *L,
8411 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008412 // Fast-path this check.
8413 if (L == R) return false;
8414
John McCall12f97bc2010-01-08 04:41:39 +00008415 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008416 if (L->Viable) {
8417 if (!R->Viable) return true;
8418
8419 // TODO: introduce a tri-valued comparison for overload
8420 // candidates. Would be more worthwhile if we had a sort
8421 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008422 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8423 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008424 } else if (R->Viable)
8425 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008426
John McCall3712d9e2010-01-15 23:32:50 +00008427 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008428
John McCall3712d9e2010-01-15 23:32:50 +00008429 // Criteria by which we can sort non-viable candidates:
8430 if (!L->Viable) {
8431 // 1. Arity mismatches come after other candidates.
8432 if (L->FailureKind == ovl_fail_too_many_arguments ||
8433 L->FailureKind == ovl_fail_too_few_arguments)
8434 return false;
8435 if (R->FailureKind == ovl_fail_too_many_arguments ||
8436 R->FailureKind == ovl_fail_too_few_arguments)
8437 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008438
John McCallfe796dd2010-01-23 05:17:32 +00008439 // 2. Bad conversions come first and are ordered by the number
8440 // of bad conversions and quality of good conversions.
8441 if (L->FailureKind == ovl_fail_bad_conversion) {
8442 if (R->FailureKind != ovl_fail_bad_conversion)
8443 return true;
8444
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008445 // The conversion that can be fixed with a smaller number of changes,
8446 // comes first.
8447 unsigned numLFixes = L->Fix.NumConversionsFixed;
8448 unsigned numRFixes = R->Fix.NumConversionsFixed;
8449 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8450 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008451 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008452 if (numLFixes < numRFixes)
8453 return true;
8454 else
8455 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008456 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008457
John McCallfe796dd2010-01-23 05:17:32 +00008458 // If there's any ordering between the defined conversions...
8459 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008460 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008461
8462 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008463 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008464 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008465 switch (CompareImplicitConversionSequences(S,
8466 L->Conversions[I],
8467 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008468 case ImplicitConversionSequence::Better:
8469 leftBetter++;
8470 break;
8471
8472 case ImplicitConversionSequence::Worse:
8473 leftBetter--;
8474 break;
8475
8476 case ImplicitConversionSequence::Indistinguishable:
8477 break;
8478 }
8479 }
8480 if (leftBetter > 0) return true;
8481 if (leftBetter < 0) return false;
8482
8483 } else if (R->FailureKind == ovl_fail_bad_conversion)
8484 return false;
8485
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008486 if (L->FailureKind == ovl_fail_bad_deduction) {
8487 if (R->FailureKind != ovl_fail_bad_deduction)
8488 return true;
8489
8490 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8491 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008492 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008493 } else if (R->FailureKind == ovl_fail_bad_deduction)
8494 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008495
John McCall3712d9e2010-01-15 23:32:50 +00008496 // TODO: others?
8497 }
8498
8499 // Sort everything else by location.
8500 SourceLocation LLoc = GetLocationForCandidate(L);
8501 SourceLocation RLoc = GetLocationForCandidate(R);
8502
8503 // Put candidates without locations (e.g. builtins) at the end.
8504 if (LLoc.isInvalid()) return false;
8505 if (RLoc.isInvalid()) return true;
8506
8507 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008508 }
8509};
8510
John McCallfe796dd2010-01-23 05:17:32 +00008511/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008512/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008513void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008514 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008515 assert(!Cand->Viable);
8516
8517 // Don't do anything on failures other than bad conversion.
8518 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8519
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008520 // We only want the FixIts if all the arguments can be corrected.
8521 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008522 // Use a implicit copy initialization to check conversion fixes.
8523 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008524
John McCallfe796dd2010-01-23 05:17:32 +00008525 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008526 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008527 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008528 while (true) {
8529 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8530 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008531 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008532 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008533 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008534 }
John McCallfe796dd2010-01-23 05:17:32 +00008535 }
8536
8537 if (ConvIdx == ConvCount)
8538 return;
8539
John McCall65eb8792010-02-25 01:37:24 +00008540 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8541 "remaining conversion is initialized?");
8542
Douglas Gregoradc7a702010-04-16 17:45:54 +00008543 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008544 // operation somehow.
8545 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008546
8547 const FunctionProtoType* Proto;
8548 unsigned ArgIdx = ConvIdx;
8549
8550 if (Cand->IsSurrogate) {
8551 QualType ConvType
8552 = Cand->Surrogate->getConversionType().getNonReferenceType();
8553 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8554 ConvType = ConvPtrType->getPointeeType();
8555 Proto = ConvType->getAs<FunctionProtoType>();
8556 ArgIdx--;
8557 } else if (Cand->Function) {
8558 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8559 if (isa<CXXMethodDecl>(Cand->Function) &&
8560 !isa<CXXConstructorDecl>(Cand->Function))
8561 ArgIdx--;
8562 } else {
8563 // Builtin binary operator with a bad first conversion.
8564 assert(ConvCount <= 3);
8565 for (; ConvIdx != ConvCount; ++ConvIdx)
8566 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008567 = TryCopyInitialization(S, Args[ConvIdx],
8568 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008569 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008570 /*InOverloadResolution*/ true,
8571 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008572 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008573 return;
8574 }
8575
8576 // Fill in the rest of the conversions.
8577 unsigned NumArgsInProto = Proto->getNumArgs();
8578 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008579 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008580 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008581 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008582 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008583 /*InOverloadResolution=*/true,
8584 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008585 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008586 // Store the FixIt in the candidate if it exists.
8587 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008588 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008589 }
John McCallfe796dd2010-01-23 05:17:32 +00008590 else
8591 Cand->Conversions[ConvIdx].setEllipsis();
8592 }
8593}
8594
John McCalld3224162010-01-08 00:58:21 +00008595} // end anonymous namespace
8596
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008597/// PrintOverloadCandidates - When overload resolution fails, prints
8598/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008599/// set.
John McCall5c32be02010-08-24 20:38:10 +00008600void OverloadCandidateSet::NoteCandidates(Sema &S,
8601 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008602 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008603 const char *Opc,
8604 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008605 // Sort the candidates by viability and position. Sorting directly would
8606 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008607 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008608 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8609 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008610 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008611 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008612 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008613 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008614 if (Cand->Function || Cand->IsSurrogate)
8615 Cands.push_back(Cand);
8616 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8617 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008618 }
8619 }
8620
John McCallad2587a2010-01-12 00:48:53 +00008621 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008622 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008623
John McCall0d1da222010-01-12 00:44:57 +00008624 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008625
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008626 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008627 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8628 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008629 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008630 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8631 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008632
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008633 // Set an arbitrary limit on the number of candidate functions we'll spam
8634 // the user with. FIXME: This limit should depend on details of the
8635 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008636 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008637 break;
8638 }
8639 ++CandsShown;
8640
John McCalld3224162010-01-08 00:58:21 +00008641 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008642 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008643 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008644 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008645 else {
8646 assert(Cand->Viable &&
8647 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008648 // Generally we only see ambiguities including viable builtin
8649 // operators if overload resolution got screwed up by an
8650 // ambiguous user-defined conversion.
8651 //
8652 // FIXME: It's quite possible for different conversions to see
8653 // different ambiguities, though.
8654 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008655 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008656 ReportedAmbiguousConversions = true;
8657 }
John McCalld3224162010-01-08 00:58:21 +00008658
John McCall0d1da222010-01-12 00:44:57 +00008659 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008660 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008661 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008662 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008663
8664 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008665 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008666}
8667
Douglas Gregorb491ed32011-02-19 21:32:49 +00008668// [PossiblyAFunctionType] --> [Return]
8669// NonFunctionType --> NonFunctionType
8670// R (A) --> R(A)
8671// R (*)(A) --> R (A)
8672// R (&)(A) --> R (A)
8673// R (S::*)(A) --> R (A)
8674QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8675 QualType Ret = PossiblyAFunctionType;
8676 if (const PointerType *ToTypePtr =
8677 PossiblyAFunctionType->getAs<PointerType>())
8678 Ret = ToTypePtr->getPointeeType();
8679 else if (const ReferenceType *ToTypeRef =
8680 PossiblyAFunctionType->getAs<ReferenceType>())
8681 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008682 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008683 PossiblyAFunctionType->getAs<MemberPointerType>())
8684 Ret = MemTypePtr->getPointeeType();
8685 Ret =
8686 Context.getCanonicalType(Ret).getUnqualifiedType();
8687 return Ret;
8688}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008689
Douglas Gregorb491ed32011-02-19 21:32:49 +00008690// A helper class to help with address of function resolution
8691// - allows us to avoid passing around all those ugly parameters
8692class AddressOfFunctionResolver
8693{
8694 Sema& S;
8695 Expr* SourceExpr;
8696 const QualType& TargetType;
8697 QualType TargetFunctionType; // Extracted function type from target type
8698
8699 bool Complain;
8700 //DeclAccessPair& ResultFunctionAccessPair;
8701 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008702
Douglas Gregorb491ed32011-02-19 21:32:49 +00008703 bool TargetTypeIsNonStaticMemberFunction;
8704 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008705
Douglas Gregorb491ed32011-02-19 21:32:49 +00008706 OverloadExpr::FindResult OvlExprInfo;
8707 OverloadExpr *OvlExpr;
8708 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008709 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008710
Douglas Gregorb491ed32011-02-19 21:32:49 +00008711public:
8712 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8713 const QualType& TargetType, bool Complain)
8714 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8715 Complain(Complain), Context(S.getASTContext()),
8716 TargetTypeIsNonStaticMemberFunction(
8717 !!TargetType->getAs<MemberPointerType>()),
8718 FoundNonTemplateFunction(false),
8719 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8720 OvlExpr(OvlExprInfo.Expression)
8721 {
8722 ExtractUnqualifiedFunctionTypeFromTargetType();
8723
8724 if (!TargetFunctionType->isFunctionType()) {
8725 if (OvlExpr->hasExplicitTemplateArgs()) {
8726 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008727 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008728 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008729
8730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8731 if (!Method->isStatic()) {
8732 // If the target type is a non-function type and the function
8733 // found is a non-static member function, pretend as if that was
8734 // the target, it's the only possible type to end up with.
8735 TargetTypeIsNonStaticMemberFunction = true;
8736
8737 // And skip adding the function if its not in the proper form.
8738 // We'll diagnose this due to an empty set of functions.
8739 if (!OvlExprInfo.HasFormOfMemberPointer)
8740 return;
8741 }
8742 }
8743
Douglas Gregorb491ed32011-02-19 21:32:49 +00008744 Matches.push_back(std::make_pair(dap,Fn));
8745 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008746 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008747 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008748 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008749
8750 if (OvlExpr->hasExplicitTemplateArgs())
8751 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008752
Douglas Gregorb491ed32011-02-19 21:32:49 +00008753 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8754 // C++ [over.over]p4:
8755 // If more than one function is selected, [...]
8756 if (Matches.size() > 1) {
8757 if (FoundNonTemplateFunction)
8758 EliminateAllTemplateMatches();
8759 else
8760 EliminateAllExceptMostSpecializedTemplate();
8761 }
8762 }
8763 }
8764
8765private:
8766 bool isTargetTypeAFunction() const {
8767 return TargetFunctionType->isFunctionType();
8768 }
8769
8770 // [ToType] [Return]
8771
8772 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8773 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8774 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8775 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8776 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8777 }
8778
8779 // return true if any matching specializations were found
8780 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8781 const DeclAccessPair& CurAccessFunPair) {
8782 if (CXXMethodDecl *Method
8783 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8784 // Skip non-static function templates when converting to pointer, and
8785 // static when converting to member pointer.
8786 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8787 return false;
8788 }
8789 else if (TargetTypeIsNonStaticMemberFunction)
8790 return false;
8791
8792 // C++ [over.over]p2:
8793 // If the name is a function template, template argument deduction is
8794 // done (14.8.2.2), and if the argument deduction succeeds, the
8795 // resulting template argument list is used to generate a single
8796 // function template specialization, which is added to the set of
8797 // overloaded functions considered.
8798 FunctionDecl *Specialization = 0;
8799 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8800 if (Sema::TemplateDeductionResult Result
8801 = S.DeduceTemplateArguments(FunctionTemplate,
8802 &OvlExplicitTemplateArgs,
8803 TargetFunctionType, Specialization,
8804 Info)) {
8805 // FIXME: make a note of the failed deduction for diagnostics.
8806 (void)Result;
8807 return false;
8808 }
8809
8810 // Template argument deduction ensures that we have an exact match.
8811 // This function template specicalization works.
8812 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8813 assert(TargetFunctionType
8814 == Context.getCanonicalType(Specialization->getType()));
8815 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8816 return true;
8817 }
8818
8819 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8820 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008821 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008822 // Skip non-static functions when converting to pointer, and static
8823 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008824 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8825 return false;
8826 }
8827 else if (TargetTypeIsNonStaticMemberFunction)
8828 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008829
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008830 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008831 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008832 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8833 if (S.CheckCUDATarget(Caller, FunDecl))
8834 return false;
8835
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008836 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008837 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8838 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008839 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8840 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008841 Matches.push_back(std::make_pair(CurAccessFunPair,
8842 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008843 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008844 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008845 }
Mike Stump11289f42009-09-09 15:08:12 +00008846 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008847
8848 return false;
8849 }
8850
8851 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8852 bool Ret = false;
8853
8854 // If the overload expression doesn't have the form of a pointer to
8855 // member, don't try to convert it to a pointer-to-member type.
8856 if (IsInvalidFormOfPointerToMemberFunction())
8857 return false;
8858
8859 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8860 E = OvlExpr->decls_end();
8861 I != E; ++I) {
8862 // Look through any using declarations to find the underlying function.
8863 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8864
8865 // C++ [over.over]p3:
8866 // Non-member functions and static member functions match
8867 // targets of type "pointer-to-function" or "reference-to-function."
8868 // Nonstatic member functions match targets of
8869 // type "pointer-to-member-function."
8870 // Note that according to DR 247, the containing class does not matter.
8871 if (FunctionTemplateDecl *FunctionTemplate
8872 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8873 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8874 Ret = true;
8875 }
8876 // If we have explicit template arguments supplied, skip non-templates.
8877 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8878 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8879 Ret = true;
8880 }
8881 assert(Ret || Matches.empty());
8882 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008883 }
8884
Douglas Gregorb491ed32011-02-19 21:32:49 +00008885 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008886 // [...] and any given function template specialization F1 is
8887 // eliminated if the set contains a second function template
8888 // specialization whose function template is more specialized
8889 // than the function template of F1 according to the partial
8890 // ordering rules of 14.5.5.2.
8891
8892 // The algorithm specified above is quadratic. We instead use a
8893 // two-pass algorithm (similar to the one used to identify the
8894 // best viable function in an overload set) that identifies the
8895 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008896
8897 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8898 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8899 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008900
John McCall58cc69d2010-01-27 01:50:18 +00008901 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008902 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8903 TPOC_Other, 0, SourceExpr->getLocStart(),
8904 S.PDiag(),
8905 S.PDiag(diag::err_addr_ovl_ambiguous)
8906 << Matches[0].second->getDeclName(),
8907 S.PDiag(diag::note_ovl_candidate)
8908 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008909 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008910
Douglas Gregorb491ed32011-02-19 21:32:49 +00008911 if (Result != MatchesCopy.end()) {
8912 // Make it the first and only element
8913 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8914 Matches[0].second = cast<FunctionDecl>(*Result);
8915 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008916 }
8917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008918
Douglas Gregorb491ed32011-02-19 21:32:49 +00008919 void EliminateAllTemplateMatches() {
8920 // [...] any function template specializations in the set are
8921 // eliminated if the set also contains a non-template function, [...]
8922 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8923 if (Matches[I].second->getPrimaryTemplate() == 0)
8924 ++I;
8925 else {
8926 Matches[I] = Matches[--N];
8927 Matches.set_size(N);
8928 }
8929 }
8930 }
8931
8932public:
8933 void ComplainNoMatchesFound() const {
8934 assert(Matches.empty());
8935 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8936 << OvlExpr->getName() << TargetFunctionType
8937 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008938 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008939 }
8940
8941 bool IsInvalidFormOfPointerToMemberFunction() const {
8942 return TargetTypeIsNonStaticMemberFunction &&
8943 !OvlExprInfo.HasFormOfMemberPointer;
8944 }
8945
8946 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8947 // TODO: Should we condition this on whether any functions might
8948 // have matched, or is it more appropriate to do that in callers?
8949 // TODO: a fixit wouldn't hurt.
8950 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8951 << TargetType << OvlExpr->getSourceRange();
8952 }
8953
8954 void ComplainOfInvalidConversion() const {
8955 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8956 << OvlExpr->getName() << TargetType;
8957 }
8958
8959 void ComplainMultipleMatchesFound() const {
8960 assert(Matches.size() > 1);
8961 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8962 << OvlExpr->getName()
8963 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008964 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008965 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008966
8967 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8968
Douglas Gregorb491ed32011-02-19 21:32:49 +00008969 int getNumMatches() const { return Matches.size(); }
8970
8971 FunctionDecl* getMatchingFunctionDecl() const {
8972 if (Matches.size() != 1) return 0;
8973 return Matches[0].second;
8974 }
8975
8976 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8977 if (Matches.size() != 1) return 0;
8978 return &Matches[0].first;
8979 }
8980};
8981
8982/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8983/// an overloaded function (C++ [over.over]), where @p From is an
8984/// expression with overloaded function type and @p ToType is the type
8985/// we're trying to resolve to. For example:
8986///
8987/// @code
8988/// int f(double);
8989/// int f(int);
8990///
8991/// int (*pfd)(double) = f; // selects f(double)
8992/// @endcode
8993///
8994/// This routine returns the resulting FunctionDecl if it could be
8995/// resolved, and NULL otherwise. When @p Complain is true, this
8996/// routine will emit diagnostics if there is an error.
8997FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008998Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8999 QualType TargetType,
9000 bool Complain,
9001 DeclAccessPair &FoundResult,
9002 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009003 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009004
9005 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9006 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009007 int NumMatches = Resolver.getNumMatches();
9008 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009009 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009010 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9011 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9012 else
9013 Resolver.ComplainNoMatchesFound();
9014 }
9015 else if (NumMatches > 1 && Complain)
9016 Resolver.ComplainMultipleMatchesFound();
9017 else if (NumMatches == 1) {
9018 Fn = Resolver.getMatchingFunctionDecl();
9019 assert(Fn);
9020 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00009021 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009022 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009023 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009024 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009025
9026 if (pHadMultipleCandidates)
9027 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009028 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009029}
9030
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009031/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009032/// resolve that overloaded function expression down to a single function.
9033///
9034/// This routine can only resolve template-ids that refer to a single function
9035/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009036/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009037/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009038FunctionDecl *
9039Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9040 bool Complain,
9041 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009042 // C++ [over.over]p1:
9043 // [...] [Note: any redundant set of parentheses surrounding the
9044 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009045 // C++ [over.over]p1:
9046 // [...] The overloaded function name can be preceded by the &
9047 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009048
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009049 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009050 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009051 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009052
9053 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009054 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009055
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009056 // Look through all of the overloaded functions, searching for one
9057 // whose type matches exactly.
9058 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009059 for (UnresolvedSetIterator I = ovl->decls_begin(),
9060 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009061 // C++0x [temp.arg.explicit]p3:
9062 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009063 // where deduction is not done, if a template argument list is
9064 // specified and it, along with any default template arguments,
9065 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009066 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009067 FunctionTemplateDecl *FunctionTemplate
9068 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009069
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009070 // C++ [over.over]p2:
9071 // If the name is a function template, template argument deduction is
9072 // done (14.8.2.2), and if the argument deduction succeeds, the
9073 // resulting template argument list is used to generate a single
9074 // function template specialization, which is added to the set of
9075 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009076 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009077 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009078 if (TemplateDeductionResult Result
9079 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9080 Specialization, Info)) {
9081 // FIXME: make a note of the failed deduction for diagnostics.
9082 (void)Result;
9083 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009084 }
9085
John McCall0009fcc2011-04-26 20:42:42 +00009086 assert(Specialization && "no specialization and no error?");
9087
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009088 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009089 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009090 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009091 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9092 << ovl->getName();
9093 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009094 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009095 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009096 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009097
John McCall0009fcc2011-04-26 20:42:42 +00009098 Matched = Specialization;
9099 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009101
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009102 return Matched;
9103}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009104
Douglas Gregor1beec452011-03-12 01:48:56 +00009105
9106
9107
John McCall50a2c2c2011-10-11 23:14:30 +00009108// Resolve and fix an overloaded expression that can be resolved
9109// because it identifies a single function template specialization.
9110//
Douglas Gregor1beec452011-03-12 01:48:56 +00009111// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009112//
9113// Return true if it was logically possible to so resolve the
9114// expression, regardless of whether or not it succeeded. Always
9115// returns true if 'complain' is set.
9116bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9117 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9118 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009119 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009120 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009121 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009122
John McCall50a2c2c2011-10-11 23:14:30 +00009123 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009124
John McCall0009fcc2011-04-26 20:42:42 +00009125 DeclAccessPair found;
9126 ExprResult SingleFunctionExpression;
9127 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9128 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009129 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009130 SrcExpr = ExprError();
9131 return true;
9132 }
John McCall0009fcc2011-04-26 20:42:42 +00009133
9134 // It is only correct to resolve to an instance method if we're
9135 // resolving a form that's permitted to be a pointer to member.
9136 // Otherwise we'll end up making a bound member expression, which
9137 // is illegal in all the contexts we resolve like this.
9138 if (!ovl.HasFormOfMemberPointer &&
9139 isa<CXXMethodDecl>(fn) &&
9140 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009141 if (!complain) return false;
9142
9143 Diag(ovl.Expression->getExprLoc(),
9144 diag::err_bound_member_function)
9145 << 0 << ovl.Expression->getSourceRange();
9146
9147 // TODO: I believe we only end up here if there's a mix of
9148 // static and non-static candidates (otherwise the expression
9149 // would have 'bound member' type, not 'overload' type).
9150 // Ideally we would note which candidate was chosen and why
9151 // the static candidates were rejected.
9152 SrcExpr = ExprError();
9153 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009154 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009155
John McCall0009fcc2011-04-26 20:42:42 +00009156 // Fix the expresion to refer to 'fn'.
9157 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009158 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009159
9160 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009161 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009162 SingleFunctionExpression =
9163 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009164 if (SingleFunctionExpression.isInvalid()) {
9165 SrcExpr = ExprError();
9166 return true;
9167 }
9168 }
John McCall0009fcc2011-04-26 20:42:42 +00009169 }
9170
9171 if (!SingleFunctionExpression.isUsable()) {
9172 if (complain) {
9173 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9174 << ovl.Expression->getName()
9175 << DestTypeForComplaining
9176 << OpRangeForComplaining
9177 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009178 NoteAllOverloadCandidates(SrcExpr.get());
9179
9180 SrcExpr = ExprError();
9181 return true;
9182 }
9183
9184 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009185 }
9186
John McCall50a2c2c2011-10-11 23:14:30 +00009187 SrcExpr = SingleFunctionExpression;
9188 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009189}
9190
Douglas Gregorcabea402009-09-22 15:41:20 +00009191/// \brief Add a single candidate to the overload set.
9192static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009193 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009194 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009195 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009196 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009197 bool PartialOverloading,
9198 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009199 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009200 if (isa<UsingShadowDecl>(Callee))
9201 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9202
Douglas Gregorcabea402009-09-22 15:41:20 +00009203 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009204 if (ExplicitTemplateArgs) {
9205 assert(!KnownValid && "Explicit template arguments?");
9206 return;
9207 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009208 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9209 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009210 return;
John McCalld14a8642009-11-21 08:51:07 +00009211 }
9212
9213 if (FunctionTemplateDecl *FuncTemplate
9214 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009215 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009216 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009217 return;
9218 }
9219
Richard Smith95ce4f62011-06-26 22:19:54 +00009220 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009221}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009222
Douglas Gregorcabea402009-09-22 15:41:20 +00009223/// \brief Add the overload candidates named by callee and/or found by argument
9224/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009225void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009226 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009227 OverloadCandidateSet &CandidateSet,
9228 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009229
9230#ifndef NDEBUG
9231 // Verify that ArgumentDependentLookup is consistent with the rules
9232 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009233 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009234 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9235 // and let Y be the lookup set produced by argument dependent
9236 // lookup (defined as follows). If X contains
9237 //
9238 // -- a declaration of a class member, or
9239 //
9240 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009241 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009242 //
9243 // -- a declaration that is neither a function or a function
9244 // template
9245 //
9246 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009247
John McCall57500772009-12-16 12:17:52 +00009248 if (ULE->requiresADL()) {
9249 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9250 E = ULE->decls_end(); I != E; ++I) {
9251 assert(!(*I)->getDeclContext()->isRecord());
9252 assert(isa<UsingShadowDecl>(*I) ||
9253 !(*I)->getDeclContext()->isFunctionOrMethod());
9254 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009255 }
9256 }
9257#endif
9258
John McCall57500772009-12-16 12:17:52 +00009259 // It would be nice to avoid this copy.
9260 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009261 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009262 if (ULE->hasExplicitTemplateArgs()) {
9263 ULE->copyTemplateArgumentsInto(TABuffer);
9264 ExplicitTemplateArgs = &TABuffer;
9265 }
9266
9267 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9268 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009269 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9270 CandidateSet, PartialOverloading,
9271 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009272
John McCall57500772009-12-16 12:17:52 +00009273 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009274 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009275 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009276 Args, ExplicitTemplateArgs,
9277 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009278 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009279}
John McCalld681c392009-12-16 08:11:27 +00009280
Richard Smith998a5912011-06-05 22:42:48 +00009281/// Attempt to recover from an ill-formed use of a non-dependent name in a
9282/// template, where the non-dependent name was declared after the template
9283/// was defined. This is common in code written for a compilers which do not
9284/// correctly implement two-stage name lookup.
9285///
9286/// Returns true if a viable candidate was found and a diagnostic was issued.
9287static bool
9288DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9289 const CXXScopeSpec &SS, LookupResult &R,
9290 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009291 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009292 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9293 return false;
9294
9295 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009296 if (DC->isTransparentContext())
9297 continue;
9298
Richard Smith998a5912011-06-05 22:42:48 +00009299 SemaRef.LookupQualifiedName(R, DC);
9300
9301 if (!R.empty()) {
9302 R.suppressDiagnostics();
9303
9304 if (isa<CXXRecordDecl>(DC)) {
9305 // Don't diagnose names we find in classes; we get much better
9306 // diagnostics for these from DiagnoseEmptyLookup.
9307 R.clear();
9308 return false;
9309 }
9310
9311 OverloadCandidateSet Candidates(FnLoc);
9312 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9313 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009314 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009315 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009316
9317 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009318 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009319 // No viable functions. Don't bother the user with notes for functions
9320 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009321 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009322 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009323 }
Richard Smith998a5912011-06-05 22:42:48 +00009324
9325 // Find the namespaces where ADL would have looked, and suggest
9326 // declaring the function there instead.
9327 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9328 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009329 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009330 AssociatedNamespaces,
9331 AssociatedClasses);
9332 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009333 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009334 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009335 for (Sema::AssociatedNamespaceSet::iterator
9336 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009337 end = AssociatedNamespaces.end(); it != end; ++it) {
9338 if (!Std->Encloses(*it))
9339 SuggestedNamespaces.insert(*it);
9340 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009341 } else {
9342 // Lacking the 'std::' namespace, use all of the associated namespaces.
9343 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009344 }
9345
9346 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9347 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009348 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009349 SemaRef.Diag(Best->Function->getLocation(),
9350 diag::note_not_found_by_two_phase_lookup)
9351 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009352 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009353 SemaRef.Diag(Best->Function->getLocation(),
9354 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009355 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009356 } else {
9357 // FIXME: It would be useful to list the associated namespaces here,
9358 // but the diagnostics infrastructure doesn't provide a way to produce
9359 // a localized representation of a list of items.
9360 SemaRef.Diag(Best->Function->getLocation(),
9361 diag::note_not_found_by_two_phase_lookup)
9362 << R.getLookupName() << 2;
9363 }
9364
9365 // Try to recover by calling this function.
9366 return true;
9367 }
9368
9369 R.clear();
9370 }
9371
9372 return false;
9373}
9374
9375/// Attempt to recover from ill-formed use of a non-dependent operator in a
9376/// template, where the non-dependent operator was declared after the template
9377/// was defined.
9378///
9379/// Returns true if a viable candidate was found and a diagnostic was issued.
9380static bool
9381DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9382 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009383 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009384 DeclarationName OpName =
9385 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9386 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9387 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009388 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009389}
9390
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009391namespace {
9392// Callback to limit the allowed keywords and to only accept typo corrections
9393// that are keywords or whose decls refer to functions (or template functions)
9394// that accept the given number of arguments.
9395class RecoveryCallCCC : public CorrectionCandidateCallback {
9396 public:
9397 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9398 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009399 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009400 WantRemainingKeywords = false;
9401 }
9402
9403 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9404 if (!candidate.getCorrectionDecl())
9405 return candidate.isKeyword();
9406
9407 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9408 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9409 FunctionDecl *FD = 0;
9410 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9411 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9412 FD = FTD->getTemplatedDecl();
9413 if (!HasExplicitTemplateArgs && !FD) {
9414 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9415 // If the Decl is neither a function nor a template function,
9416 // determine if it is a pointer or reference to a function. If so,
9417 // check against the number of arguments expected for the pointee.
9418 QualType ValType = cast<ValueDecl>(ND)->getType();
9419 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9420 ValType = ValType->getPointeeType();
9421 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9422 if (FPT->getNumArgs() == NumArgs)
9423 return true;
9424 }
9425 }
9426 if (FD && FD->getNumParams() >= NumArgs &&
9427 FD->getMinRequiredArguments() <= NumArgs)
9428 return true;
9429 }
9430 return false;
9431 }
9432
9433 private:
9434 unsigned NumArgs;
9435 bool HasExplicitTemplateArgs;
9436};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009437
9438// Callback that effectively disabled typo correction
9439class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9440 public:
9441 NoTypoCorrectionCCC() {
9442 WantTypeSpecifiers = false;
9443 WantExpressionKeywords = false;
9444 WantCXXNamedCasts = false;
9445 WantRemainingKeywords = false;
9446 }
9447
9448 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9449 return false;
9450 }
9451};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009452}
9453
John McCalld681c392009-12-16 08:11:27 +00009454/// Attempts to recover from a call where no functions were found.
9455///
9456/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009457static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009458BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009459 UnresolvedLookupExpr *ULE,
9460 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009461 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009462 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009463 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009464
9465 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009466 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009467 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009468
John McCall57500772009-12-16 12:17:52 +00009469 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009470 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009471 if (ULE->hasExplicitTemplateArgs()) {
9472 ULE->copyTemplateArgumentsInto(TABuffer);
9473 ExplicitTemplateArgs = &TABuffer;
9474 }
9475
John McCalld681c392009-12-16 08:11:27 +00009476 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9477 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009478 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009479 NoTypoCorrectionCCC RejectAll;
9480 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9481 (CorrectionCandidateCallback*)&Validator :
9482 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009483 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009484 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009485 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009486 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009487 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009488 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009489
John McCall57500772009-12-16 12:17:52 +00009490 assert(!R.empty() && "lookup results empty despite recovery");
9491
9492 // Build an implicit member call if appropriate. Just drop the
9493 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009494 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009495 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009496 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9497 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009498 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009499 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009500 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009501 else
9502 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9503
9504 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009505 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009506
9507 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009508 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009509 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009510 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009511 MultiExprArg(Args.data(), Args.size()),
9512 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009513}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009514
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009515/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009516/// (which eventually refers to the declaration Func) and the call
9517/// arguments Args/NumArgs, attempt to resolve the function call down
9518/// to a specific function. If overload resolution succeeds, returns
9519/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009520/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009521/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009522ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009523Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009524 SourceLocation LParenLoc,
9525 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009526 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009527 Expr *ExecConfig,
9528 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009529#ifndef NDEBUG
9530 if (ULE->requiresADL()) {
9531 // To do ADL, we must have found an unqualified name.
9532 assert(!ULE->getQualifier() && "qualified name with ADL");
9533
9534 // We don't perform ADL for implicit declarations of builtins.
9535 // Verify that this was correctly set up.
9536 FunctionDecl *F;
9537 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9538 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9539 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009540 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009541
John McCall57500772009-12-16 12:17:52 +00009542 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009543 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009544 } else
9545 assert(!ULE->isStdAssociatedNamespace() &&
9546 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009547#endif
9548
John McCall4124c492011-10-17 18:40:02 +00009549 UnbridgedCastsSet UnbridgedCasts;
9550 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9551 return ExprError();
9552
John McCallbc077cf2010-02-08 23:07:23 +00009553 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009554
John McCall57500772009-12-16 12:17:52 +00009555 // Add the functions denoted by the callee to the set of candidate
9556 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009557 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9558 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009559
9560 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009561 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9562 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009563 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009564 // In Microsoft mode, if we are inside a template class member function then
9565 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009566 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009567 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009568 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009569 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009570 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9571 Context.DependentTy, VK_RValue,
9572 RParenLoc);
9573 CE->setTypeDependent(true);
9574 return Owned(CE);
9575 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009576 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9577 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009578 RParenLoc, /*EmptyLookup=*/true,
9579 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009580 }
John McCalld681c392009-12-16 08:11:27 +00009581
John McCall4124c492011-10-17 18:40:02 +00009582 UnbridgedCasts.restore();
9583
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009584 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009585 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009586 case OR_Success: {
9587 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009588 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009589 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009590 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009591 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009592 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9593 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009594 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009595
Richard Smith998a5912011-06-05 22:42:48 +00009596 case OR_No_Viable_Function: {
9597 // Try to recover by looking for viable functions which the user might
9598 // have meant to call.
9599 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009600 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9601 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009602 /*EmptyLookup=*/false,
9603 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009604 if (!Recovery.isInvalid())
9605 return Recovery;
9606
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009607 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009608 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009609 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009610 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9611 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009612 break;
Richard Smith998a5912011-06-05 22:42:48 +00009613 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009614
9615 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009616 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009617 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009618 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9619 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009620 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009621
9622 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009623 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009624 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009625 << Best->Function->isDeleted()
9626 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009627 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009628 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009629 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9630 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009631
9632 // We emitted an error for the unvailable/deleted function call but keep
9633 // the call in the AST.
9634 FunctionDecl *FDecl = Best->Function;
9635 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9636 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9637 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009638 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009639 }
9640
Douglas Gregorb412e172010-07-25 18:17:45 +00009641 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009642 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009643}
9644
John McCall4c4c1df2010-01-26 03:27:55 +00009645static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009646 return Functions.size() > 1 ||
9647 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9648}
9649
Douglas Gregor084d8552009-03-13 23:49:33 +00009650/// \brief Create a unary operation that may resolve to an overloaded
9651/// operator.
9652///
9653/// \param OpLoc The location of the operator itself (e.g., '*').
9654///
9655/// \param OpcIn The UnaryOperator::Opcode that describes this
9656/// operator.
9657///
9658/// \param Functions The set of non-member functions that will be
9659/// considered by overload resolution. The caller needs to build this
9660/// set based on the context using, e.g.,
9661/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9662/// set should not contain any member functions; those will be added
9663/// by CreateOverloadedUnaryOp().
9664///
9665/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009666ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009667Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9668 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009669 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009670 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009671
9672 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9673 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9674 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009675 // TODO: provide better source location info.
9676 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009677
John McCall4124c492011-10-17 18:40:02 +00009678 if (checkPlaceholderForOverload(*this, Input))
9679 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009680
Douglas Gregor084d8552009-03-13 23:49:33 +00009681 Expr *Args[2] = { Input, 0 };
9682 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009683
Douglas Gregor084d8552009-03-13 23:49:33 +00009684 // For post-increment and post-decrement, add the implicit '0' as
9685 // the second argument, so that we know this is a post-increment or
9686 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009687 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009688 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009689 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9690 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009691 NumArgs = 2;
9692 }
9693
9694 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009695 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009696 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009697 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009698 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009699 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009700 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009701
John McCall58cc69d2010-01-27 01:50:18 +00009702 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009703 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009704 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009705 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009706 /*ADL*/ true, IsOverloaded(Fns),
9707 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009708 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009709 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009710 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009711 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009712 OpLoc));
9713 }
9714
9715 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009716 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009717
9718 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009719 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9720 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009721
9722 // Add operator candidates that are member functions.
9723 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9724
John McCall4c4c1df2010-01-26 03:27:55 +00009725 // Add candidates from ADL.
9726 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009727 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009728 /*ExplicitTemplateArgs*/ 0,
9729 CandidateSet);
9730
Douglas Gregor084d8552009-03-13 23:49:33 +00009731 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009732 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009733
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009734 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9735
Douglas Gregor084d8552009-03-13 23:49:33 +00009736 // Perform overload resolution.
9737 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009738 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009739 case OR_Success: {
9740 // We found a built-in operator or an overloaded operator.
9741 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009742
Douglas Gregor084d8552009-03-13 23:49:33 +00009743 if (FnDecl) {
9744 // We matched an overloaded operator. Build a call to that
9745 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009746
Eli Friedmanfa0df832012-02-02 03:46:19 +00009747 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009748
Douglas Gregor084d8552009-03-13 23:49:33 +00009749 // Convert the arguments.
9750 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009751 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009752
John Wiegley01296292011-04-08 18:41:53 +00009753 ExprResult InputRes =
9754 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9755 Best->FoundDecl, Method);
9756 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009757 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009758 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009759 } else {
9760 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009761 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009762 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009763 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009764 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009765 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009766 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009767 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009768 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009769 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009770 }
9771
John McCall4fa0d5f2010-05-06 18:15:07 +00009772 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9773
John McCall7decc9e2010-11-18 06:31:45 +00009774 // Determine the result type.
9775 QualType ResultTy = FnDecl->getResultType();
9776 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9777 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009778
Douglas Gregor084d8552009-03-13 23:49:33 +00009779 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009780 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009781 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009782 if (FnExpr.isInvalid())
9783 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009784
Eli Friedman030eee42009-11-18 03:58:17 +00009785 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009786 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009787 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009788 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009789
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009790 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009791 FnDecl))
9792 return ExprError();
9793
John McCallb268a282010-08-23 23:25:46 +00009794 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009795 } else {
9796 // We matched a built-in operator. Convert the arguments, then
9797 // break out so that we will build the appropriate built-in
9798 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009799 ExprResult InputRes =
9800 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9801 Best->Conversions[0], AA_Passing);
9802 if (InputRes.isInvalid())
9803 return ExprError();
9804 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009805 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009806 }
John Wiegley01296292011-04-08 18:41:53 +00009807 }
9808
9809 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009810 // This is an erroneous use of an operator which can be overloaded by
9811 // a non-member function. Check for non-member operators which were
9812 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009813 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9814 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +00009815 // FIXME: Recover by calling the found function.
9816 return ExprError();
9817
John Wiegley01296292011-04-08 18:41:53 +00009818 // No viable function; fall through to handling this as a
9819 // built-in operator, which will produce an error message for us.
9820 break;
9821
9822 case OR_Ambiguous:
9823 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9824 << UnaryOperator::getOpcodeStr(Opc)
9825 << Input->getType()
9826 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009827 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9828 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +00009829 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9830 return ExprError();
9831
9832 case OR_Deleted:
9833 Diag(OpLoc, diag::err_ovl_deleted_oper)
9834 << Best->Function->isDeleted()
9835 << UnaryOperator::getOpcodeStr(Opc)
9836 << getDeletedOrUnavailableSuffix(Best->Function)
9837 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009838 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9839 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009840 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009841 return ExprError();
9842 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009843
9844 // Either we found no viable overloaded operator or we matched a
9845 // built-in operator. In either case, fall through to trying to
9846 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009847 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009848}
9849
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009850/// \brief Create a binary operation that may resolve to an overloaded
9851/// operator.
9852///
9853/// \param OpLoc The location of the operator itself (e.g., '+').
9854///
9855/// \param OpcIn The BinaryOperator::Opcode that describes this
9856/// operator.
9857///
9858/// \param Functions The set of non-member functions that will be
9859/// considered by overload resolution. The caller needs to build this
9860/// set based on the context using, e.g.,
9861/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9862/// set should not contain any member functions; those will be added
9863/// by CreateOverloadedBinOp().
9864///
9865/// \param LHS Left-hand argument.
9866/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009867ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009868Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009869 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009870 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009871 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009872 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009873 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009874
9875 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9876 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9877 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9878
9879 // If either side is type-dependent, create an appropriate dependent
9880 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009881 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009882 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009883 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009884 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009885 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009886 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009887 Context.DependentTy,
9888 VK_RValue, OK_Ordinary,
9889 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009890
Douglas Gregor5287f092009-11-05 00:51:44 +00009891 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9892 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009893 VK_LValue,
9894 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009895 Context.DependentTy,
9896 Context.DependentTy,
9897 OpLoc));
9898 }
John McCall4c4c1df2010-01-26 03:27:55 +00009899
9900 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009901 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009902 // TODO: provide better source location info in DNLoc component.
9903 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009904 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009905 = UnresolvedLookupExpr::Create(Context, NamingClass,
9906 NestedNameSpecifierLoc(), OpNameInfo,
9907 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009908 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009909 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009910 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009911 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009912 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009913 OpLoc));
9914 }
9915
John McCall4124c492011-10-17 18:40:02 +00009916 // Always do placeholder-like conversions on the RHS.
9917 if (checkPlaceholderForOverload(*this, Args[1]))
9918 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009919
John McCall526ab472011-10-25 17:37:35 +00009920 // Do placeholder-like conversion on the LHS; note that we should
9921 // not get here with a PseudoObject LHS.
9922 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009923 if (checkPlaceholderForOverload(*this, Args[0]))
9924 return ExprError();
9925
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009926 // If this is the assignment operator, we only perform overload resolution
9927 // if the left-hand side is a class or enumeration type. This is actually
9928 // a hack. The standard requires that we do overload resolution between the
9929 // various built-in candidates, but as DR507 points out, this can lead to
9930 // problems. So we do it this way, which pretty much follows what GCC does.
9931 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009932 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009933 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009934
John McCalle26a8722010-12-04 08:14:53 +00009935 // If this is the .* operator, which is not overloadable, just
9936 // create a built-in binary operator.
9937 if (Opc == BO_PtrMemD)
9938 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9939
Douglas Gregor084d8552009-03-13 23:49:33 +00009940 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009941 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009942
9943 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009944 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009945
9946 // Add operator candidates that are member functions.
9947 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9948
John McCall4c4c1df2010-01-26 03:27:55 +00009949 // Add candidates from ADL.
9950 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009951 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +00009952 /*ExplicitTemplateArgs*/ 0,
9953 CandidateSet);
9954
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009955 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009956 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009957
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009958 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9959
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009960 // Perform overload resolution.
9961 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009962 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009963 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009964 // We found a built-in operator or an overloaded operator.
9965 FunctionDecl *FnDecl = Best->Function;
9966
9967 if (FnDecl) {
9968 // We matched an overloaded operator. Build a call to that
9969 // operator.
9970
Eli Friedmanfa0df832012-02-02 03:46:19 +00009971 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009972
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009973 // Convert the arguments.
9974 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009975 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009976 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009977
Chandler Carruth8e543b32010-12-12 08:17:55 +00009978 ExprResult Arg1 =
9979 PerformCopyInitialization(
9980 InitializedEntity::InitializeParameter(Context,
9981 FnDecl->getParamDecl(0)),
9982 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009983 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009984 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009985
John Wiegley01296292011-04-08 18:41:53 +00009986 ExprResult Arg0 =
9987 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9988 Best->FoundDecl, Method);
9989 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009990 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009991 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009992 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009993 } else {
9994 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009995 ExprResult Arg0 = PerformCopyInitialization(
9996 InitializedEntity::InitializeParameter(Context,
9997 FnDecl->getParamDecl(0)),
9998 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009999 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010000 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010001
Chandler Carruth8e543b32010-12-12 08:17:55 +000010002 ExprResult Arg1 =
10003 PerformCopyInitialization(
10004 InitializedEntity::InitializeParameter(Context,
10005 FnDecl->getParamDecl(1)),
10006 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010007 if (Arg1.isInvalid())
10008 return ExprError();
10009 Args[0] = LHS = Arg0.takeAs<Expr>();
10010 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010011 }
10012
John McCall4fa0d5f2010-05-06 18:15:07 +000010013 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10014
John McCall7decc9e2010-11-18 06:31:45 +000010015 // Determine the result type.
10016 QualType ResultTy = FnDecl->getResultType();
10017 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10018 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010019
10020 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010021 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10022 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010023 if (FnExpr.isInvalid())
10024 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010025
John McCallb268a282010-08-23 23:25:46 +000010026 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010027 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010028 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010029
10030 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010031 FnDecl))
10032 return ExprError();
10033
John McCallb268a282010-08-23 23:25:46 +000010034 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010035 } else {
10036 // We matched a built-in operator. Convert the arguments, then
10037 // break out so that we will build the appropriate built-in
10038 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010039 ExprResult ArgsRes0 =
10040 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10041 Best->Conversions[0], AA_Passing);
10042 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010043 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010044 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010045
John Wiegley01296292011-04-08 18:41:53 +000010046 ExprResult ArgsRes1 =
10047 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10048 Best->Conversions[1], AA_Passing);
10049 if (ArgsRes1.isInvalid())
10050 return ExprError();
10051 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010052 break;
10053 }
10054 }
10055
Douglas Gregor66950a32009-09-30 21:46:01 +000010056 case OR_No_Viable_Function: {
10057 // C++ [over.match.oper]p9:
10058 // If the operator is the operator , [...] and there are no
10059 // viable functions, then the operator is assumed to be the
10060 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010061 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010062 break;
10063
Chandler Carruth8e543b32010-12-12 08:17:55 +000010064 // For class as left operand for assignment or compound assigment
10065 // operator do not fall through to handling in built-in, but report that
10066 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010067 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010068 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010069 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010070 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10071 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010072 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010073 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010074 // This is an erroneous use of an operator which can be overloaded by
10075 // a non-member function. Check for non-member operators which were
10076 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010077 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010078 // FIXME: Recover by calling the found function.
10079 return ExprError();
10080
Douglas Gregor66950a32009-09-30 21:46:01 +000010081 // No viable function; try to create a built-in operation, which will
10082 // produce an error. Then, show the non-viable candidates.
10083 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010085 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010086 "C++ binary operator overloading is missing candidates!");
10087 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010088 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010089 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010090 return move(Result);
10091 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010092
10093 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010094 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010095 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010096 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010097 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010098 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010099 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010100 return ExprError();
10101
10102 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010103 if (isImplicitlyDeleted(Best->Function)) {
10104 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10105 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10106 << getSpecialMember(Method)
10107 << BinaryOperator::getOpcodeStr(Opc)
10108 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010109
10110 if (getSpecialMember(Method) != CXXInvalid) {
10111 // The user probably meant to call this special member. Just
10112 // explain why it's deleted.
10113 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010114 return ExprError();
10115 }
10116 } else {
10117 Diag(OpLoc, diag::err_ovl_deleted_oper)
10118 << Best->Function->isDeleted()
10119 << BinaryOperator::getOpcodeStr(Opc)
10120 << getDeletedOrUnavailableSuffix(Best->Function)
10121 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10122 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010123 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010124 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010125 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010126 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010127
Douglas Gregor66950a32009-09-30 21:46:01 +000010128 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010129 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010130}
10131
John McCalldadc5752010-08-24 06:29:42 +000010132ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010133Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10134 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010135 Expr *Base, Expr *Idx) {
10136 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010137 DeclarationName OpName =
10138 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10139
10140 // If either side is type-dependent, create an appropriate dependent
10141 // expression.
10142 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10143
John McCall58cc69d2010-01-27 01:50:18 +000010144 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010145 // CHECKME: no 'operator' keyword?
10146 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10147 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010148 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010149 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010150 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010151 /*ADL*/ true, /*Overloaded*/ false,
10152 UnresolvedSetIterator(),
10153 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010154 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010155
Sebastian Redladba46e2009-10-29 20:17:01 +000010156 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10157 Args, 2,
10158 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010159 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010160 RLoc));
10161 }
10162
John McCall4124c492011-10-17 18:40:02 +000010163 // Handle placeholders on both operands.
10164 if (checkPlaceholderForOverload(*this, Args[0]))
10165 return ExprError();
10166 if (checkPlaceholderForOverload(*this, Args[1]))
10167 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010168
Sebastian Redladba46e2009-10-29 20:17:01 +000010169 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010170 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010171
10172 // Subscript can only be overloaded as a member function.
10173
10174 // Add operator candidates that are member functions.
10175 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10176
10177 // Add builtin operator candidates.
10178 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10179
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010180 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10181
Sebastian Redladba46e2009-10-29 20:17:01 +000010182 // Perform overload resolution.
10183 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010184 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010185 case OR_Success: {
10186 // We found a built-in operator or an overloaded operator.
10187 FunctionDecl *FnDecl = Best->Function;
10188
10189 if (FnDecl) {
10190 // We matched an overloaded operator. Build a call to that
10191 // operator.
10192
Eli Friedmanfa0df832012-02-02 03:46:19 +000010193 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010194
John McCalla0296f72010-03-19 07:35:19 +000010195 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010196 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010197
Sebastian Redladba46e2009-10-29 20:17:01 +000010198 // Convert the arguments.
10199 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010200 ExprResult Arg0 =
10201 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10202 Best->FoundDecl, Method);
10203 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010204 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010205 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010206
Anders Carlssona68e51e2010-01-29 18:37:50 +000010207 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010208 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010209 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010210 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010211 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010212 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010213 Owned(Args[1]));
10214 if (InputInit.isInvalid())
10215 return ExprError();
10216
10217 Args[1] = InputInit.takeAs<Expr>();
10218
Sebastian Redladba46e2009-10-29 20:17:01 +000010219 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010220 QualType ResultTy = FnDecl->getResultType();
10221 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10222 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010223
10224 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010225 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10226 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010227 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10228 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010229 OpLocInfo.getLoc(),
10230 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010231 if (FnExpr.isInvalid())
10232 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010233
John McCallb268a282010-08-23 23:25:46 +000010234 CXXOperatorCallExpr *TheCall =
10235 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010236 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010237 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010238
John McCallb268a282010-08-23 23:25:46 +000010239 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010240 FnDecl))
10241 return ExprError();
10242
John McCallb268a282010-08-23 23:25:46 +000010243 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010244 } else {
10245 // We matched a built-in operator. Convert the arguments, then
10246 // break out so that we will build the appropriate built-in
10247 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010248 ExprResult ArgsRes0 =
10249 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10250 Best->Conversions[0], AA_Passing);
10251 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010252 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010253 Args[0] = ArgsRes0.take();
10254
10255 ExprResult ArgsRes1 =
10256 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10257 Best->Conversions[1], AA_Passing);
10258 if (ArgsRes1.isInvalid())
10259 return ExprError();
10260 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010261
10262 break;
10263 }
10264 }
10265
10266 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010267 if (CandidateSet.empty())
10268 Diag(LLoc, diag::err_ovl_no_oper)
10269 << Args[0]->getType() << /*subscript*/ 0
10270 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10271 else
10272 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10273 << Args[0]->getType()
10274 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010275 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010276 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010277 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010278 }
10279
10280 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010281 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010282 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010283 << Args[0]->getType() << Args[1]->getType()
10284 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010285 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010286 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010287 return ExprError();
10288
10289 case OR_Deleted:
10290 Diag(LLoc, diag::err_ovl_deleted_oper)
10291 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010292 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010293 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010294 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010295 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010296 return ExprError();
10297 }
10298
10299 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010300 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010301}
10302
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010303/// BuildCallToMemberFunction - Build a call to a member
10304/// function. MemExpr is the expression that refers to the member
10305/// function (and includes the object parameter), Args/NumArgs are the
10306/// arguments to the function call (not including the object
10307/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010308/// expression refers to a non-static member function or an overloaded
10309/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010310ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010311Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10312 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010313 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010314 assert(MemExprE->getType() == Context.BoundMemberTy ||
10315 MemExprE->getType() == Context.OverloadTy);
10316
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010317 // Dig out the member expression. This holds both the object
10318 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010319 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010320
John McCall0009fcc2011-04-26 20:42:42 +000010321 // Determine whether this is a call to a pointer-to-member function.
10322 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10323 assert(op->getType() == Context.BoundMemberTy);
10324 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10325
10326 QualType fnType =
10327 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10328
10329 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10330 QualType resultType = proto->getCallResultType(Context);
10331 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10332
10333 // Check that the object type isn't more qualified than the
10334 // member function we're calling.
10335 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10336
10337 QualType objectType = op->getLHS()->getType();
10338 if (op->getOpcode() == BO_PtrMemI)
10339 objectType = objectType->castAs<PointerType>()->getPointeeType();
10340 Qualifiers objectQuals = objectType.getQualifiers();
10341
10342 Qualifiers difference = objectQuals - funcQuals;
10343 difference.removeObjCGCAttr();
10344 difference.removeAddressSpace();
10345 if (difference) {
10346 std::string qualsString = difference.getAsString();
10347 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10348 << fnType.getUnqualifiedType()
10349 << qualsString
10350 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10351 }
10352
10353 CXXMemberCallExpr *call
10354 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10355 resultType, valueKind, RParenLoc);
10356
10357 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010358 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010359 call, 0))
10360 return ExprError();
10361
10362 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10363 return ExprError();
10364
10365 return MaybeBindToTemporary(call);
10366 }
10367
John McCall4124c492011-10-17 18:40:02 +000010368 UnbridgedCastsSet UnbridgedCasts;
10369 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10370 return ExprError();
10371
John McCall10eae182009-11-30 22:42:35 +000010372 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010373 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010374 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010375 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010376 if (isa<MemberExpr>(NakedMemExpr)) {
10377 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010378 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010379 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010380 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010381 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010382 } else {
10383 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010384 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010385
John McCall6e9f8f62009-12-03 04:06:58 +000010386 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010387 Expr::Classification ObjectClassification
10388 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10389 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010390
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010391 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010392 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010393
John McCall2d74de92009-12-01 22:10:20 +000010394 // FIXME: avoid copy.
10395 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10396 if (UnresExpr->hasExplicitTemplateArgs()) {
10397 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10398 TemplateArgs = &TemplateArgsBuffer;
10399 }
10400
John McCall10eae182009-11-30 22:42:35 +000010401 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10402 E = UnresExpr->decls_end(); I != E; ++I) {
10403
John McCall6e9f8f62009-12-03 04:06:58 +000010404 NamedDecl *Func = *I;
10405 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10406 if (isa<UsingShadowDecl>(Func))
10407 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10408
Douglas Gregor02824322011-01-26 19:30:28 +000010409
Francois Pichet64225792011-01-18 05:04:39 +000010410 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010411 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010412 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10413 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010414 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010415 // If explicit template arguments were provided, we can't call a
10416 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010417 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010418 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010419
John McCalla0296f72010-03-19 07:35:19 +000010420 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010421 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010422 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010423 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010424 } else {
John McCall10eae182009-11-30 22:42:35 +000010425 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010426 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010427 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010428 llvm::makeArrayRef(Args, NumArgs),
10429 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010430 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010431 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010432 }
Mike Stump11289f42009-09-09 15:08:12 +000010433
John McCall10eae182009-11-30 22:42:35 +000010434 DeclarationName DeclName = UnresExpr->getMemberName();
10435
John McCall4124c492011-10-17 18:40:02 +000010436 UnbridgedCasts.restore();
10437
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010438 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010439 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010440 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010441 case OR_Success:
10442 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010443 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010444 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010445 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010446 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010447 break;
10448
10449 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010450 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010451 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010452 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010453 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10454 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010455 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010456 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010457
10458 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010459 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010460 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010461 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10462 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010463 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010464 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010465
10466 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010467 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010468 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010469 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010470 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010471 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010472 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10473 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010474 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010475 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010476 }
10477
John McCall16df1e52010-03-30 21:47:33 +000010478 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010479
John McCall2d74de92009-12-01 22:10:20 +000010480 // If overload resolution picked a static member, build a
10481 // non-member call based on that function.
10482 if (Method->isStatic()) {
10483 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10484 Args, NumArgs, RParenLoc);
10485 }
10486
John McCall10eae182009-11-30 22:42:35 +000010487 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010488 }
10489
John McCall7decc9e2010-11-18 06:31:45 +000010490 QualType ResultType = Method->getResultType();
10491 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10492 ResultType = ResultType.getNonLValueExprType(Context);
10493
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010494 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010495 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010496 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010497 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010498
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010499 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010500 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010501 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010502 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010503
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010504 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010505 // We only need to do this if there was actually an overload; otherwise
10506 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010507 if (!Method->isStatic()) {
10508 ExprResult ObjectArg =
10509 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10510 FoundDecl, Method);
10511 if (ObjectArg.isInvalid())
10512 return ExprError();
10513 MemExpr->setBase(ObjectArg.take());
10514 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010515
10516 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010517 const FunctionProtoType *Proto =
10518 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010519 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010520 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010521 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010522
Eli Friedmanff4b4072012-02-18 04:48:30 +000010523 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10524
John McCallb268a282010-08-23 23:25:46 +000010525 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010526 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010527
Anders Carlsson47061ee2011-05-06 14:25:31 +000010528 if ((isa<CXXConstructorDecl>(CurContext) ||
10529 isa<CXXDestructorDecl>(CurContext)) &&
10530 TheCall->getMethodDecl()->isPure()) {
10531 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10532
Chandler Carruth59259262011-06-27 08:31:58 +000010533 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010534 Diag(MemExpr->getLocStart(),
10535 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10536 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10537 << MD->getParent()->getDeclName();
10538
10539 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010540 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010541 }
John McCallb268a282010-08-23 23:25:46 +000010542 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010543}
10544
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010545/// BuildCallToObjectOfClassType - Build a call to an object of class
10546/// type (C++ [over.call.object]), which can end up invoking an
10547/// overloaded function call operator (@c operator()) or performing a
10548/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010549ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010550Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010551 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010552 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010553 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010554 if (checkPlaceholderForOverload(*this, Obj))
10555 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010556 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010557
10558 UnbridgedCastsSet UnbridgedCasts;
10559 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10560 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010561
John Wiegley01296292011-04-08 18:41:53 +000010562 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10563 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010564
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010565 // C++ [over.call.object]p1:
10566 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010567 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010568 // candidate functions includes at least the function call
10569 // operators of T. The function call operators of T are obtained by
10570 // ordinary lookup of the name operator() in the context of
10571 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010572 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010573 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010574
John Wiegley01296292011-04-08 18:41:53 +000010575 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +000010576 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010577 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010578 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010579
John McCall27b18f82009-11-17 02:14:36 +000010580 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10581 LookupQualifiedName(R, Record->getDecl());
10582 R.suppressDiagnostics();
10583
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010584 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010585 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010586 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10587 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010588 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010590
Douglas Gregorab7897a2008-11-19 22:57:39 +000010591 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010592 // In addition, for each (non-explicit in C++0x) conversion function
10593 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010594 //
10595 // operator conversion-type-id () cv-qualifier;
10596 //
10597 // where cv-qualifier is the same cv-qualification as, or a
10598 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010599 // denotes the type "pointer to function of (P1,...,Pn) returning
10600 // R", or the type "reference to pointer to function of
10601 // (P1,...,Pn) returning R", or the type "reference to function
10602 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010603 // is also considered as a candidate function. Similarly,
10604 // surrogate call functions are added to the set of candidate
10605 // functions for each conversion function declared in an
10606 // accessible base class provided the function is not hidden
10607 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010608 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010609 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010610 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010611 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010612 NamedDecl *D = *I;
10613 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10614 if (isa<UsingShadowDecl>(D))
10615 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010616
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010617 // Skip over templated conversion functions; they aren't
10618 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010619 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010620 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010621
John McCall6e9f8f62009-12-03 04:06:58 +000010622 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010623 if (!Conv->isExplicit()) {
10624 // Strip the reference type (if any) and then the pointer type (if
10625 // any) to get down to what might be a function type.
10626 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10627 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10628 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010629
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010630 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10631 {
10632 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010633 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10634 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010635 }
10636 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010637 }
Mike Stump11289f42009-09-09 15:08:12 +000010638
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010639 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10640
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010641 // Perform overload resolution.
10642 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010643 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010644 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010645 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010646 // Overload resolution succeeded; we'll build the appropriate call
10647 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010648 break;
10649
10650 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010651 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010652 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010653 << Object.get()->getType() << /*call*/ 1
10654 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010655 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010656 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010657 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010658 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010659 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10660 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010661 break;
10662
10663 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010664 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010665 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010666 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010667 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10668 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010669 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010670
10671 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010672 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010673 diag::err_ovl_deleted_object_call)
10674 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010675 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010676 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010677 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010678 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10679 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010680 break;
Mike Stump11289f42009-09-09 15:08:12 +000010681 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010682
Douglas Gregorb412e172010-07-25 18:17:45 +000010683 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010684 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010685
John McCall4124c492011-10-17 18:40:02 +000010686 UnbridgedCasts.restore();
10687
Douglas Gregorab7897a2008-11-19 22:57:39 +000010688 if (Best->Function == 0) {
10689 // Since there is no function declaration, this is one of the
10690 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010691 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010692 = cast<CXXConversionDecl>(
10693 Best->Conversions[0].UserDefined.ConversionFunction);
10694
John Wiegley01296292011-04-08 18:41:53 +000010695 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010696 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010697
Douglas Gregorab7897a2008-11-19 22:57:39 +000010698 // We selected one of the surrogate functions that converts the
10699 // object parameter to a function pointer. Perform the conversion
10700 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010701
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010702 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010703 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010704 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10705 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010706 if (Call.isInvalid())
10707 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010708 // Record usage of conversion in an implicit cast.
10709 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10710 CK_UserDefinedConversion,
10711 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010712
Douglas Gregor668443e2011-01-20 00:18:04 +000010713 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010714 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010715 }
10716
Eli Friedmanfa0df832012-02-02 03:46:19 +000010717 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010718 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010719 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010720
Douglas Gregorab7897a2008-11-19 22:57:39 +000010721 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10722 // that calls this method, using Object for the implicit object
10723 // parameter and passing along the remaining arguments.
10724 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010725 const FunctionProtoType *Proto =
10726 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010727
10728 unsigned NumArgsInProto = Proto->getNumArgs();
10729 unsigned NumArgsToCheck = NumArgs;
10730
10731 // Build the full argument list for the method call (the
10732 // implicit object parameter is placed at the beginning of the
10733 // list).
10734 Expr **MethodArgs;
10735 if (NumArgs < NumArgsInProto) {
10736 NumArgsToCheck = NumArgsInProto;
10737 MethodArgs = new Expr*[NumArgsInProto + 1];
10738 } else {
10739 MethodArgs = new Expr*[NumArgs + 1];
10740 }
John Wiegley01296292011-04-08 18:41:53 +000010741 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010742 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10743 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010744
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010745 DeclarationNameInfo OpLocInfo(
10746 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10747 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010748 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010749 HadMultipleCandidates,
10750 OpLocInfo.getLoc(),
10751 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010752 if (NewFn.isInvalid())
10753 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010754
10755 // Once we've built TheCall, all of the expressions are properly
10756 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010757 QualType ResultTy = Method->getResultType();
10758 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10759 ResultTy = ResultTy.getNonLValueExprType(Context);
10760
John McCallb268a282010-08-23 23:25:46 +000010761 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010762 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010763 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010764 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010765 delete [] MethodArgs;
10766
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010767 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010768 Method))
10769 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010770
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010771 // We may have default arguments. If so, we need to allocate more
10772 // slots in the call for them.
10773 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010774 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010775 else if (NumArgs > NumArgsInProto)
10776 NumArgsToCheck = NumArgsInProto;
10777
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010778 bool IsError = false;
10779
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010780 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010781 ExprResult ObjRes =
10782 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10783 Best->FoundDecl, Method);
10784 if (ObjRes.isInvalid())
10785 IsError = true;
10786 else
10787 Object = move(ObjRes);
10788 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010789
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010790 // Check the argument types.
10791 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010792 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010793 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010794 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010795
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010796 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010797
John McCalldadc5752010-08-24 06:29:42 +000010798 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010799 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010800 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010801 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010802 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010803
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010804 IsError |= InputInit.isInvalid();
10805 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010806 } else {
John McCalldadc5752010-08-24 06:29:42 +000010807 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010808 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10809 if (DefArg.isInvalid()) {
10810 IsError = true;
10811 break;
10812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010813
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010814 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010815 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010816
10817 TheCall->setArg(i + 1, Arg);
10818 }
10819
10820 // If this is a variadic call, handle args passed through "...".
10821 if (Proto->isVariadic()) {
10822 // Promote the arguments (C99 6.5.2.2p7).
10823 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010824 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10825 IsError |= Arg.isInvalid();
10826 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010827 }
10828 }
10829
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010830 if (IsError) return true;
10831
Eli Friedmanff4b4072012-02-18 04:48:30 +000010832 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10833
John McCallb268a282010-08-23 23:25:46 +000010834 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010835 return true;
10836
John McCalle172be52010-08-24 06:09:16 +000010837 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010838}
10839
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010840/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010841/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010842/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010843ExprResult
John McCallb268a282010-08-23 23:25:46 +000010844Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010845 assert(Base->getType()->isRecordType() &&
10846 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010847
John McCall4124c492011-10-17 18:40:02 +000010848 if (checkPlaceholderForOverload(*this, Base))
10849 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010850
John McCallbc077cf2010-02-08 23:07:23 +000010851 SourceLocation Loc = Base->getExprLoc();
10852
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010853 // C++ [over.ref]p1:
10854 //
10855 // [...] An expression x->m is interpreted as (x.operator->())->m
10856 // for a class object x of type T if T::operator->() exists and if
10857 // the operator is selected as the best match function by the
10858 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010859 DeclarationName OpName =
10860 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010861 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010862 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010863
John McCallbc077cf2010-02-08 23:07:23 +000010864 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010865 PDiag(diag::err_typecheck_incomplete_tag)
10866 << Base->getSourceRange()))
10867 return ExprError();
10868
John McCall27b18f82009-11-17 02:14:36 +000010869 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10870 LookupQualifiedName(R, BaseRecord->getDecl());
10871 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010872
10873 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010874 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010875 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10876 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010877 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010878
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010879 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10880
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010881 // Perform overload resolution.
10882 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010883 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010884 case OR_Success:
10885 // Overload resolution succeeded; we'll build the call below.
10886 break;
10887
10888 case OR_No_Viable_Function:
10889 if (CandidateSet.empty())
10890 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010891 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010892 else
10893 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010894 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010895 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010896 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010897
10898 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010899 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10900 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010901 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010902 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010903
10904 case OR_Deleted:
10905 Diag(OpLoc, diag::err_ovl_deleted_oper)
10906 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010907 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010908 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010909 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010911 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010912 }
10913
Eli Friedmanfa0df832012-02-02 03:46:19 +000010914 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010915 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010916 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010917
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010918 // Convert the object parameter.
10919 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010920 ExprResult BaseResult =
10921 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10922 Best->FoundDecl, Method);
10923 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010924 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010925 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010926
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010927 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010928 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010929 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010930 if (FnExpr.isInvalid())
10931 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010932
John McCall7decc9e2010-11-18 06:31:45 +000010933 QualType ResultTy = Method->getResultType();
10934 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10935 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010936 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010937 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010938 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010939
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010940 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010941 Method))
10942 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010943
10944 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010945}
10946
Richard Smithbcc22fc2012-03-09 08:00:36 +000010947/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10948/// a literal operator described by the provided lookup results.
10949ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10950 DeclarationNameInfo &SuffixInfo,
10951 ArrayRef<Expr*> Args,
10952 SourceLocation LitEndLoc,
10953 TemplateArgumentListInfo *TemplateArgs) {
10954 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000010955
Richard Smithbcc22fc2012-03-09 08:00:36 +000010956 OverloadCandidateSet CandidateSet(UDSuffixLoc);
10957 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10958 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000010959
Richard Smithbcc22fc2012-03-09 08:00:36 +000010960 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10961
Richard Smithbcc22fc2012-03-09 08:00:36 +000010962 // Perform overload resolution. This will usually be trivial, but might need
10963 // to perform substitutions for a literal operator template.
10964 OverloadCandidateSet::iterator Best;
10965 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
10966 case OR_Success:
10967 case OR_Deleted:
10968 break;
10969
10970 case OR_No_Viable_Function:
10971 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
10972 << R.getLookupName();
10973 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
10974 return ExprError();
10975
10976 case OR_Ambiguous:
10977 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
10978 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
10979 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000010980 }
10981
Richard Smithbcc22fc2012-03-09 08:00:36 +000010982 FunctionDecl *FD = Best->Function;
10983 MarkFunctionReferenced(UDSuffixLoc, FD);
10984 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000010985
Richard Smithbcc22fc2012-03-09 08:00:36 +000010986 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
10987 SuffixInfo.getLoc(),
10988 SuffixInfo.getInfo());
10989 if (Fn.isInvalid())
10990 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000010991
10992 // Check the argument types. This should almost always be a no-op, except
10993 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000010994 Expr *ConvArgs[2];
10995 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
10996 ExprResult InputInit = PerformCopyInitialization(
10997 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
10998 SourceLocation(), Args[ArgIdx]);
10999 if (InputInit.isInvalid())
11000 return true;
11001 ConvArgs[ArgIdx] = InputInit.take();
11002 }
11003
Richard Smithc67fdd42012-03-07 08:35:16 +000011004 QualType ResultTy = FD->getResultType();
11005 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11006 ResultTy = ResultTy.getNonLValueExprType(Context);
11007
Richard Smithc67fdd42012-03-07 08:35:16 +000011008 UserDefinedLiteral *UDL =
11009 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11010 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11011
11012 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11013 return ExprError();
11014
11015 if (CheckFunctionCall(FD, UDL))
11016 return ExprError();
11017
11018 return MaybeBindToTemporary(UDL);
11019}
11020
Douglas Gregorcd695e52008-11-10 20:40:00 +000011021/// FixOverloadedFunctionReference - E is an expression that refers to
11022/// a C++ overloaded function (possibly with some parentheses and
11023/// perhaps a '&' around it). We have resolved the overloaded function
11024/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011025/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011026Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011027 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011028 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011029 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11030 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011031 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011032 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011033
Douglas Gregor51c538b2009-11-20 19:42:02 +000011034 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011035 }
11036
Douglas Gregor51c538b2009-11-20 19:42:02 +000011037 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011038 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11039 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011040 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011041 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011042 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011043 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011044 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011045 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011046
11047 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011048 ICE->getCastKind(),
11049 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011050 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011051 }
11052
Douglas Gregor51c538b2009-11-20 19:42:02 +000011053 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011054 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011055 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011056 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11057 if (Method->isStatic()) {
11058 // Do nothing: static member functions aren't any different
11059 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011060 } else {
John McCalle66edc12009-11-24 19:00:30 +000011061 // Fix the sub expression, which really has to be an
11062 // UnresolvedLookupExpr holding an overloaded member function
11063 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011064 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11065 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011066 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011067 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011068
John McCalld14a8642009-11-21 08:51:07 +000011069 assert(isa<DeclRefExpr>(SubExpr)
11070 && "fixed to something other than a decl ref");
11071 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11072 && "fixed to a member ref with no nested name qualifier");
11073
11074 // We have taken the address of a pointer to member
11075 // function. Perform the computation here so that we get the
11076 // appropriate pointer to member type.
11077 QualType ClassType
11078 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11079 QualType MemPtrType
11080 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11081
John McCall7decc9e2010-11-18 06:31:45 +000011082 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11083 VK_RValue, OK_Ordinary,
11084 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011085 }
11086 }
John McCall16df1e52010-03-30 21:47:33 +000011087 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11088 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011089 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011090 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011091
John McCalle3027922010-08-25 11:45:40 +000011092 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011093 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011094 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011095 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011096 }
John McCalld14a8642009-11-21 08:51:07 +000011097
11098 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011099 // FIXME: avoid copy.
11100 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011101 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011102 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11103 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011104 }
11105
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011106 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11107 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011108 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011109 Fn,
John McCall113bee02012-03-10 09:33:50 +000011110 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011111 ULE->getNameLoc(),
11112 Fn->getType(),
11113 VK_LValue,
11114 Found.getDecl(),
11115 TemplateArgs);
11116 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11117 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011118 }
11119
John McCall10eae182009-11-30 22:42:35 +000011120 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011121 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011122 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11123 if (MemExpr->hasExplicitTemplateArgs()) {
11124 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11125 TemplateArgs = &TemplateArgsBuffer;
11126 }
John McCall6b51f282009-11-23 01:53:49 +000011127
John McCall2d74de92009-12-01 22:10:20 +000011128 Expr *Base;
11129
John McCall7decc9e2010-11-18 06:31:45 +000011130 // If we're filling in a static method where we used to have an
11131 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011132 if (MemExpr->isImplicitAccess()) {
11133 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011134 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11135 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011136 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011137 Fn,
John McCall113bee02012-03-10 09:33:50 +000011138 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011139 MemExpr->getMemberLoc(),
11140 Fn->getType(),
11141 VK_LValue,
11142 Found.getDecl(),
11143 TemplateArgs);
11144 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11145 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011146 } else {
11147 SourceLocation Loc = MemExpr->getMemberLoc();
11148 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011149 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011150 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011151 Base = new (Context) CXXThisExpr(Loc,
11152 MemExpr->getBaseType(),
11153 /*isImplicit=*/true);
11154 }
John McCall2d74de92009-12-01 22:10:20 +000011155 } else
John McCallc3007a22010-10-26 07:05:15 +000011156 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011157
John McCall4adb38c2011-04-27 00:36:17 +000011158 ExprValueKind valueKind;
11159 QualType type;
11160 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11161 valueKind = VK_LValue;
11162 type = Fn->getType();
11163 } else {
11164 valueKind = VK_RValue;
11165 type = Context.BoundMemberTy;
11166 }
11167
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011168 MemberExpr *ME = MemberExpr::Create(Context, Base,
11169 MemExpr->isArrow(),
11170 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011171 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011172 Fn,
11173 Found,
11174 MemExpr->getMemberNameInfo(),
11175 TemplateArgs,
11176 type, valueKind, OK_Ordinary);
11177 ME->setHadMultipleCandidates(true);
11178 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011180
John McCallc3007a22010-10-26 07:05:15 +000011181 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011182}
11183
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011184ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011185 DeclAccessPair Found,
11186 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011187 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011188}
11189
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011190} // end namespace clang