blob: 9527c0f2982d669216385f860a252e5aa055da3a [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()){
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 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.
291NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue) const {
Richard Smith66e05fe2012-01-18 05:21:49 +0000295 assert(Ctx.getLangOptions().CPlusPlus && "narrowing check outside C++");
296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
301 switch (Second) {
302 // -- from a floating-point type to an integer type, or
303 //
304 // -- from an integer type or unscoped enumeration type to a floating-point
305 // type, except where the source is a constant expression and the actual
306 // value after conversion will fit into the target type and will produce
307 // the original value when converted back to the original type, or
308 case ICK_Floating_Integral:
309 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
310 return NK_Type_Narrowing;
311 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
312 llvm::APSInt IntConstantValue;
313 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
314 if (Initializer &&
315 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
316 // Convert the integer to the floating type.
317 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
318 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
319 llvm::APFloat::rmNearestTiesToEven);
320 // And back.
321 llvm::APSInt ConvertedValue = IntConstantValue;
322 bool ignored;
323 Result.convertToInteger(ConvertedValue,
324 llvm::APFloat::rmTowardZero, &ignored);
325 // If the resulting value is different, this was a narrowing conversion.
326 if (IntConstantValue != ConvertedValue) {
327 ConstantValue = APValue(IntConstantValue);
328 return NK_Constant_Narrowing;
329 }
330 } else {
331 // Variables are always narrowings.
332 return NK_Variable_Narrowing;
333 }
334 }
335 return NK_Not_Narrowing;
336
337 // -- from long double to double or float, or from double to float, except
338 // where the source is a constant expression and the actual value after
339 // conversion is within the range of values that can be represented (even
340 // if it cannot be represented exactly), or
341 case ICK_Floating_Conversion:
342 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
343 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
344 // FromType is larger than ToType.
345 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
346 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
347 // Constant!
348 assert(ConstantValue.isFloat());
349 llvm::APFloat FloatVal = ConstantValue.getFloat();
350 // Convert the source value into the target type.
351 bool ignored;
352 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
353 Ctx.getFloatTypeSemantics(ToType),
354 llvm::APFloat::rmNearestTiesToEven, &ignored);
355 // If there was no overflow, the source value is within the range of
356 // values that can be represented.
357 if (ConvertStatus & llvm::APFloat::opOverflow)
358 return NK_Constant_Narrowing;
359 } else {
360 return NK_Variable_Narrowing;
361 }
362 }
363 return NK_Not_Narrowing;
364
365 // -- from an integer type or unscoped enumeration type to an integer type
366 // that cannot represent all the values of the original type, except where
367 // the source is a constant expression and the actual value after
368 // conversion will fit into the target type and will produce the original
369 // value when converted back to the original type.
370 case ICK_Boolean_Conversion: // Bools are integers too.
371 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
372 // Boolean conversions can be from pointers and pointers to members
373 // [conv.bool], and those aren't considered narrowing conversions.
374 return NK_Not_Narrowing;
375 } // Otherwise, fall through to the integral case.
376 case ICK_Integral_Conversion: {
377 assert(FromType->isIntegralOrUnscopedEnumerationType());
378 assert(ToType->isIntegralOrUnscopedEnumerationType());
379 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
380 const unsigned FromWidth = Ctx.getIntWidth(FromType);
381 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
382 const unsigned ToWidth = Ctx.getIntWidth(ToType);
383
384 if (FromWidth > ToWidth ||
385 (FromWidth == ToWidth && FromSigned != ToSigned)) {
386 // Not all values of FromType can be represented in ToType.
387 llvm::APSInt InitializerValue;
388 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
389 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
390 ConstantValue = APValue(InitializerValue);
391
392 // Add a bit to the InitializerValue so we don't have to worry about
393 // signed vs. unsigned comparisons.
394 InitializerValue = InitializerValue.extend(
395 InitializerValue.getBitWidth() + 1);
396 // Convert the initializer to and from the target width and signed-ness.
397 llvm::APSInt ConvertedValue = InitializerValue;
398 ConvertedValue = ConvertedValue.trunc(ToWidth);
399 ConvertedValue.setIsSigned(ToSigned);
400 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
401 ConvertedValue.setIsSigned(InitializerValue.isSigned());
402 // If the result is different, this was a narrowing conversion.
403 if (ConvertedValue != InitializerValue)
404 return NK_Constant_Narrowing;
405 } else {
406 // Variables are always narrowings.
407 return NK_Variable_Narrowing;
408 }
409 }
410 return NK_Not_Narrowing;
411 }
412
413 default:
414 // Other kinds of conversions are not narrowings.
415 return NK_Not_Narrowing;
416 }
417}
418
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000419/// DebugPrint - Print this standard conversion sequence to standard
420/// error. Useful for debugging overloading issues.
421void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000422 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000423 bool PrintedSomething = false;
424 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000425 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000426 PrintedSomething = true;
427 }
428
429 if (Second != ICK_Identity) {
430 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000431 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000432 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000434
435 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000436 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000437 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000438 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000439 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000442 PrintedSomething = true;
443 }
444
445 if (Third != ICK_Identity) {
446 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000448 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000449 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455 }
456}
457
458/// DebugPrint - Print this user-defined conversion sequence to standard
459/// error. Useful for debugging overloading issues.
460void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000461 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 if (Before.First || Before.Second || Before.Third) {
463 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000464 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000466 if (ConversionFunction)
467 OS << '\'' << *ConversionFunction << '\'';
468 else
469 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472 After.DebugPrint();
473 }
474}
475
476/// DebugPrint - Print this implicit conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 switch (ConversionKind) {
481 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 Standard.DebugPrint();
484 break;
485 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000486 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 UserDefined.DebugPrint();
488 break;
489 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 break;
John McCall0d1da222010-01-12 00:44:57 +0000492 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000493 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000494 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 break;
498 }
499
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000500 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501}
502
John McCall0d1da222010-01-12 00:44:57 +0000503void AmbiguousConversionSequence::construct() {
504 new (&conversions()) ConversionSet();
505}
506
507void AmbiguousConversionSequence::destruct() {
508 conversions().~ConversionSet();
509}
510
511void
512AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
513 FromTypePtr = O.FromTypePtr;
514 ToTypePtr = O.ToTypePtr;
515 new (&conversions()) ConversionSet(O.conversions());
516}
517
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518namespace {
519 // Structure used by OverloadCandidate::DeductionFailureInfo to store
520 // template parameter and template argument information.
521 struct DFIParamWithArguments {
522 TemplateParameter Param;
523 TemplateArgument FirstArg;
524 TemplateArgument SecondArg;
525 };
526}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000528/// \brief Convert from Sema's representation of template deduction information
529/// to the form used in overload-candidate information.
530OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000531static MakeDeductionFailureInfo(ASTContext &Context,
532 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000533 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534 OverloadCandidate::DeductionFailureInfo Result;
535 Result.Result = static_cast<unsigned>(TDK);
536 Result.Data = 0;
537 switch (TDK) {
538 case Sema::TDK_Success:
539 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000540 case Sema::TDK_TooManyArguments:
541 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000544 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000545 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000546 Result.Data = Info.Param.getOpaqueValue();
547 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000548
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000549 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000550 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000551 // FIXME: Should allocate from normal heap so that we can free this later.
552 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 Saved->Param = Info.Param;
554 Saved->FirstArg = Info.FirstArg;
555 Saved->SecondArg = Info.SecondArg;
556 Result.Data = Saved;
557 break;
558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000560 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000561 Result.Data = Info.take();
562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000569 return Result;
570}
John McCall0d1da222010-01-12 00:44:57 +0000571
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572void OverloadCandidate::DeductionFailureInfo::Destroy() {
573 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
574 case Sema::TDK_Success:
575 case Sema::TDK_InstantiationDepth:
576 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000577 case Sema::TDK_TooManyArguments:
578 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000579 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000582 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000583 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000584 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 Data = 0;
586 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000587
588 case Sema::TDK_SubstitutionFailure:
589 // FIXME: Destroy the template arugment list?
590 Data = 0;
591 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregor461761d2010-05-08 18:20:53 +0000593 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000595 case Sema::TDK_FailedOverloadResolution:
596 break;
597 }
598}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
600TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000601OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
602 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
603 case Sema::TDK_Success:
604 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000611 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613
614 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000615 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000618 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
621 break;
622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 return TemplateParameter();
625}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregord09efd42010-05-08 20:07:26 +0000627TemplateArgumentList *
628OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
631 case Sema::TDK_InstantiationDepth:
632 case Sema::TDK_TooManyArguments:
633 case Sema::TDK_TooFewArguments:
634 case Sema::TDK_Incomplete:
635 case Sema::TDK_InvalidExplicitArguments:
636 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000637 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000638 return 0;
639
640 case Sema::TDK_SubstitutionFailure:
641 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregord09efd42010-05-08 20:07:26 +0000643 // Unhandled
644 case Sema::TDK_NonDeducedMismatch:
645 case Sema::TDK_FailedOverloadResolution:
646 break;
647 }
648
649 return 0;
650}
651
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
654 case Sema::TDK_Success:
655 case Sema::TDK_InstantiationDepth:
656 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000657 case Sema::TDK_TooManyArguments:
658 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000659 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000660 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 return 0;
662
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000664 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000666
Douglas Gregor461761d2010-05-08 18:20:53 +0000667 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000668 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 case Sema::TDK_FailedOverloadResolution:
670 break;
671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000675
676const TemplateArgument *
677OverloadCandidate::DeductionFailureInfo::getSecondArg() {
678 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
679 case Sema::TDK_Success:
680 case Sema::TDK_InstantiationDepth:
681 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000682 case Sema::TDK_TooManyArguments:
683 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000685 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000686 return 0;
687
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000689 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
691
Douglas Gregor461761d2010-05-08 18:20:53 +0000692 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 case Sema::TDK_FailedOverloadResolution:
695 break;
696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000698 return 0;
699}
700
701void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000702 for (iterator i = begin(), e = end(); i != e; ++i)
703 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
704 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000705 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000706 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 Functions.clear();
708}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
John McCall4124c492011-10-17 18:40:02 +0000710namespace {
711 class UnbridgedCastsSet {
712 struct Entry {
713 Expr **Addr;
714 Expr *Saved;
715 };
716 SmallVector<Entry, 2> Entries;
717
718 public:
719 void save(Sema &S, Expr *&E) {
720 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
721 Entry entry = { &E, E };
722 Entries.push_back(entry);
723 E = S.stripARCUnbridgedCast(E);
724 }
725
726 void restore() {
727 for (SmallVectorImpl<Entry>::iterator
728 i = Entries.begin(), e = Entries.end(); i != e; ++i)
729 *i->Addr = i->Saved;
730 }
731 };
732}
733
734/// checkPlaceholderForOverload - Do any interesting placeholder-like
735/// preprocessing on the given expression.
736///
737/// \param unbridgedCasts a collection to which to add unbridged casts;
738/// without this, they will be immediately diagnosed as errors
739///
740/// Return true on unrecoverable error.
741static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
742 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000743 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
744 // We can't handle overloaded expressions here because overload
745 // resolution might reasonably tweak them.
746 if (placeholder->getKind() == BuiltinType::Overload) return false;
747
748 // If the context potentially accepts unbridged ARC casts, strip
749 // the unbridged cast and add it to the collection for later restoration.
750 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
751 unbridgedCasts) {
752 unbridgedCasts->save(S, E);
753 return false;
754 }
755
756 // Go ahead and check everything else.
757 ExprResult result = S.CheckPlaceholderExpr(E);
758 if (result.isInvalid())
759 return true;
760
761 E = result.take();
762 return false;
763 }
764
765 // Nothing to do.
766 return false;
767}
768
769/// checkArgPlaceholdersForOverload - Check a set of call operands for
770/// placeholders.
771static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
772 unsigned numArgs,
773 UnbridgedCastsSet &unbridged) {
774 for (unsigned i = 0; i != numArgs; ++i)
775 if (checkPlaceholderForOverload(S, args[i], &unbridged))
776 return true;
777
778 return false;
779}
780
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000781// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000782// overload of the declarations in Old. This routine returns false if
783// New and Old cannot be overloaded, e.g., if New has the same
784// signature as some function in Old (C++ 1.3.10) or if the Old
785// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000786// it does return false, MatchedDecl will point to the decl that New
787// cannot be overloaded with. This decl may be a UsingShadowDecl on
788// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789//
790// Example: Given the following input:
791//
792// void f(int, float); // #1
793// void f(int, int); // #2
794// int f(int, int); // #3
795//
796// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000797// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000798//
John McCall3d988d92009-12-02 08:47:38 +0000799// When we process #2, Old contains only the FunctionDecl for #1. By
800// comparing the parameter types, we see that #1 and #2 are overloaded
801// (since they have different signatures), so this routine returns
802// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803//
John McCall3d988d92009-12-02 08:47:38 +0000804// When we process #3, Old is an overload set containing #1 and #2. We
805// compare the signatures of #3 to #1 (they're overloaded, so we do
806// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
807// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808// signature), IsOverload returns false and MatchedDecl will be set to
809// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000810//
811// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
812// into a class by a using declaration. The rules for whether to hide
813// shadow declarations ignore some properties which otherwise figure
814// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000815Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000816Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
817 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000818 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000819 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000820 NamedDecl *OldD = *I;
821
822 bool OldIsUsingDecl = false;
823 if (isa<UsingShadowDecl>(OldD)) {
824 OldIsUsingDecl = true;
825
826 // We can always introduce two using declarations into the same
827 // context, even if they have identical signatures.
828 if (NewIsUsingDecl) continue;
829
830 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
831 }
832
833 // If either declaration was introduced by a using declaration,
834 // we'll need to use slightly different rules for matching.
835 // Essentially, these rules are the normal rules, except that
836 // function templates hide function templates with different
837 // return types or template parameter lists.
838 bool UseMemberUsingDeclRules =
839 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
840
John McCall3d988d92009-12-02 08:47:38 +0000841 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000842 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
843 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
844 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
845 continue;
846 }
847
John McCalldaa3d6b2009-12-09 03:35:25 +0000848 Match = *I;
849 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000850 }
John McCall3d988d92009-12-02 08:47:38 +0000851 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000852 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
853 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
854 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
855 continue;
856 }
857
John McCalldaa3d6b2009-12-09 03:35:25 +0000858 Match = *I;
859 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000860 }
John McCalla8987a2942010-11-10 03:01:53 +0000861 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000862 // We can overload with these, which can show up when doing
863 // redeclaration checks for UsingDecls.
864 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000865 } else if (isa<TagDecl>(OldD)) {
866 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000867 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
868 // Optimistically assume that an unresolved using decl will
869 // overload; if it doesn't, we'll have to diagnose during
870 // template instantiation.
871 } else {
John McCall1f82f242009-11-18 22:49:29 +0000872 // (C++ 13p1):
873 // Only function declarations can be overloaded; object and type
874 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000875 Match = *I;
876 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000877 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 }
John McCall1f82f242009-11-18 22:49:29 +0000879
John McCalldaa3d6b2009-12-09 03:35:25 +0000880 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000881}
882
John McCalle9cccd82010-06-16 08:42:20 +0000883bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
884 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000885 // If both of the functions are extern "C", then they are not
886 // overloads.
887 if (Old->isExternC() && New->isExternC())
888 return false;
889
John McCall1f82f242009-11-18 22:49:29 +0000890 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
891 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
892
893 // C++ [temp.fct]p2:
894 // A function template can be overloaded with other function templates
895 // and with normal (non-template) functions.
896 if ((OldTemplate == 0) != (NewTemplate == 0))
897 return true;
898
899 // Is the function New an overload of the function Old?
900 QualType OldQType = Context.getCanonicalType(Old->getType());
901 QualType NewQType = Context.getCanonicalType(New->getType());
902
903 // Compare the signatures (C++ 1.3.10) of the two functions to
904 // determine whether they are overloads. If we find any mismatch
905 // in the signature, they are overloads.
906
907 // If either of these functions is a K&R-style function (no
908 // prototype), then we consider them to have matching signatures.
909 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
910 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
911 return false;
912
John McCall424cec92011-01-19 06:33:43 +0000913 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
914 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000915
916 // The signature of a function includes the types of its
917 // parameters (C++ 1.3.10), which includes the presence or absence
918 // of the ellipsis; see C++ DR 357).
919 if (OldQType != NewQType &&
920 (OldType->getNumArgs() != NewType->getNumArgs() ||
921 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000922 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000923 return true;
924
925 // C++ [temp.over.link]p4:
926 // The signature of a function template consists of its function
927 // signature, its return type and its template parameter list. The names
928 // of the template parameters are significant only for establishing the
929 // relationship between the template parameters and the rest of the
930 // signature.
931 //
932 // We check the return type and template parameter lists for function
933 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000934 //
935 // However, we don't consider either of these when deciding whether
936 // a member introduced by a shadow declaration is hidden.
937 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000938 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
939 OldTemplate->getTemplateParameters(),
940 false, TPL_TemplateMatch) ||
941 OldType->getResultType() != NewType->getResultType()))
942 return true;
943
944 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000945 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000946 //
947 // As part of this, also check whether one of the member functions
948 // is static, in which case they are not overloads (C++
949 // 13.1p2). While not part of the definition of the signature,
950 // this check is important to determine whether these functions
951 // can be overloaded.
952 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
953 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
954 if (OldMethod && NewMethod &&
955 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000956 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000957 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
958 if (!UseUsingDeclRules &&
959 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
960 (OldMethod->getRefQualifier() == RQ_None ||
961 NewMethod->getRefQualifier() == RQ_None)) {
962 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963 // - Member function declarations with the same name and the same
964 // parameter-type-list as well as member function template
965 // declarations with the same name, the same parameter-type-list, and
966 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000967 // them, but not all, have a ref-qualifier (8.3.5).
968 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
969 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
970 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972
John McCall1f82f242009-11-18 22:49:29 +0000973 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975
John McCall1f82f242009-11-18 22:49:29 +0000976 // The signatures match; this is not an overload.
977 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000978}
979
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000980/// \brief Checks availability of the function depending on the current
981/// function context. Inside an unavailable function, unavailability is ignored.
982///
983/// \returns true if \arg FD is unavailable and current context is inside
984/// an available function, false otherwise.
985bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
986 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
987}
988
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000989/// \brief Tries a user-defined conversion from From to ToType.
990///
991/// Produces an implicit conversion sequence for when a standard conversion
992/// is not an option. See TryImplicitConversion for more information.
993static ImplicitConversionSequence
994TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
995 bool SuppressUserConversions,
996 bool AllowExplicit,
997 bool InOverloadResolution,
998 bool CStyle,
999 bool AllowObjCWritebackConversion) {
1000 ImplicitConversionSequence ICS;
1001
1002 if (SuppressUserConversions) {
1003 // We're not in the case above, so there is no conversion that
1004 // we can perform.
1005 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1006 return ICS;
1007 }
1008
1009 // Attempt user-defined conversion.
1010 OverloadCandidateSet Conversions(From->getExprLoc());
1011 OverloadingResult UserDefResult
1012 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1013 AllowExplicit);
1014
1015 if (UserDefResult == OR_Success) {
1016 ICS.setUserDefined();
1017 // C++ [over.ics.user]p4:
1018 // A conversion of an expression of class type to the same class
1019 // type is given Exact Match rank, and a conversion of an
1020 // expression of class type to a base class of that type is
1021 // given Conversion rank, in spite of the fact that a copy
1022 // constructor (i.e., a user-defined conversion function) is
1023 // called for those cases.
1024 if (CXXConstructorDecl *Constructor
1025 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1026 QualType FromCanon
1027 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1028 QualType ToCanon
1029 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1030 if (Constructor->isCopyConstructor() &&
1031 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1032 // Turn this into a "standard" conversion sequence, so that it
1033 // gets ranked with standard conversion sequences.
1034 ICS.setStandard();
1035 ICS.Standard.setAsIdentityConversion();
1036 ICS.Standard.setFromType(From->getType());
1037 ICS.Standard.setAllToTypes(ToType);
1038 ICS.Standard.CopyConstructor = Constructor;
1039 if (ToCanon != FromCanon)
1040 ICS.Standard.Second = ICK_Derived_To_Base;
1041 }
1042 }
1043
1044 // C++ [over.best.ics]p4:
1045 // However, when considering the argument of a user-defined
1046 // conversion function that is a candidate by 13.3.1.3 when
1047 // invoked for the copying of the temporary in the second step
1048 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1049 // 13.3.1.6 in all cases, only standard conversion sequences and
1050 // ellipsis conversion sequences are allowed.
1051 if (SuppressUserConversions && ICS.isUserDefined()) {
1052 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1053 }
1054 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1055 ICS.setAmbiguous();
1056 ICS.Ambiguous.setFromType(From->getType());
1057 ICS.Ambiguous.setToType(ToType);
1058 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1059 Cand != Conversions.end(); ++Cand)
1060 if (Cand->Viable)
1061 ICS.Ambiguous.addConversion(Cand->Function);
1062 } else {
1063 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1064 }
1065
1066 return ICS;
1067}
1068
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001069/// TryImplicitConversion - Attempt to perform an implicit conversion
1070/// from the given expression (Expr) to the given type (ToType). This
1071/// function returns an implicit conversion sequence that can be used
1072/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073///
1074/// void f(float f);
1075/// void g(int i) { f(i); }
1076///
1077/// this routine would produce an implicit conversion sequence to
1078/// describe the initialization of f from i, which will be a standard
1079/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1080/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1081//
1082/// Note that this routine only determines how the conversion can be
1083/// performed; it does not actually perform the conversion. As such,
1084/// it will not produce any diagnostics if no conversion is available,
1085/// but will instead return an implicit conversion sequence of kind
1086/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001087///
1088/// If @p SuppressUserConversions, then user-defined conversions are
1089/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001090/// If @p AllowExplicit, then explicit user-defined conversions are
1091/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001092///
1093/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1094/// writeback conversion, which allows __autoreleasing id* parameters to
1095/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001096static ImplicitConversionSequence
1097TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1098 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001100 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001101 bool CStyle,
1102 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001104 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001105 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001106 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001107 return ICS;
1108 }
1109
John McCall5c32be02010-08-24 20:38:10 +00001110 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001111 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001112 return ICS;
1113 }
1114
Douglas Gregor836a7e82010-08-11 02:15:33 +00001115 // C++ [over.ics.user]p4:
1116 // A conversion of an expression of class type to the same class
1117 // type is given Exact Match rank, and a conversion of an
1118 // expression of class type to a base class of that type is
1119 // given Conversion rank, in spite of the fact that a copy/move
1120 // constructor (i.e., a user-defined conversion function) is
1121 // called for those cases.
1122 QualType FromType = From->getType();
1123 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001124 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1125 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001126 ICS.setStandard();
1127 ICS.Standard.setAsIdentityConversion();
1128 ICS.Standard.setFromType(FromType);
1129 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001130
Douglas Gregor5ab11652010-04-17 22:01:05 +00001131 // We don't actually check at this point whether there is a valid
1132 // copy/move constructor, since overloading just assumes that it
1133 // exists. When we actually perform initialization, we'll find the
1134 // appropriate constructor to copy the returned object, if needed.
1135 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136
Douglas Gregor5ab11652010-04-17 22:01:05 +00001137 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001138 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001139 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Douglas Gregor836a7e82010-08-11 02:15:33 +00001141 return ICS;
1142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001144 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1145 AllowExplicit, InOverloadResolution, CStyle,
1146 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147}
1148
John McCall31168b02011-06-15 23:02:42 +00001149ImplicitConversionSequence
1150Sema::TryImplicitConversion(Expr *From, QualType ToType,
1151 bool SuppressUserConversions,
1152 bool AllowExplicit,
1153 bool InOverloadResolution,
1154 bool CStyle,
1155 bool AllowObjCWritebackConversion) {
1156 return clang::TryImplicitConversion(*this, From, ToType,
1157 SuppressUserConversions, AllowExplicit,
1158 InOverloadResolution, CStyle,
1159 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001160}
1161
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001162/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001163/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001164/// converted expression. Flavor is the kind of conversion we're
1165/// performing, used in the error message. If @p AllowExplicit,
1166/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001167ExprResult
1168Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001169 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001170 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001171 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001172}
1173
John Wiegley01296292011-04-08 18:41:53 +00001174ExprResult
1175Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001176 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001177 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001178 if (checkPlaceholderForOverload(*this, From))
1179 return ExprError();
1180
John McCall31168b02011-06-15 23:02:42 +00001181 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1182 bool AllowObjCWritebackConversion
1183 = getLangOptions().ObjCAutoRefCount &&
1184 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001185
John McCall5c32be02010-08-24 20:38:10 +00001186 ICS = clang::TryImplicitConversion(*this, From, ToType,
1187 /*SuppressUserConversions=*/false,
1188 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001189 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001190 /*CStyle=*/false,
1191 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001192 return PerformImplicitConversion(From, ToType, ICS, Action);
1193}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194
1195/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001196/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001197bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1198 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001199 if (Context.hasSameUnqualifiedType(FromType, ToType))
1200 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001201
John McCall991eb4b2010-12-21 00:44:39 +00001202 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1203 // where F adds one of the following at most once:
1204 // - a pointer
1205 // - a member pointer
1206 // - a block pointer
1207 CanQualType CanTo = Context.getCanonicalType(ToType);
1208 CanQualType CanFrom = Context.getCanonicalType(FromType);
1209 Type::TypeClass TyClass = CanTo->getTypeClass();
1210 if (TyClass != CanFrom->getTypeClass()) return false;
1211 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1212 if (TyClass == Type::Pointer) {
1213 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1214 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1215 } else if (TyClass == Type::BlockPointer) {
1216 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1217 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1218 } else if (TyClass == Type::MemberPointer) {
1219 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1220 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1221 } else {
1222 return false;
1223 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001224
John McCall991eb4b2010-12-21 00:44:39 +00001225 TyClass = CanTo->getTypeClass();
1226 if (TyClass != CanFrom->getTypeClass()) return false;
1227 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1228 return false;
1229 }
1230
1231 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1232 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1233 if (!EInfo.getNoReturn()) return false;
1234
1235 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1236 assert(QualType(FromFn, 0).isCanonical());
1237 if (QualType(FromFn, 0) != CanTo) return false;
1238
1239 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001240 return true;
1241}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242
Douglas Gregor46188682010-05-18 22:42:18 +00001243/// \brief Determine whether the conversion from FromType to ToType is a valid
1244/// vector conversion.
1245///
1246/// \param ICK Will be set to the vector conversion kind, if this is a vector
1247/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001248static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1249 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001250 // We need at least one of these types to be a vector type to have a vector
1251 // conversion.
1252 if (!ToType->isVectorType() && !FromType->isVectorType())
1253 return false;
1254
1255 // Identical types require no conversions.
1256 if (Context.hasSameUnqualifiedType(FromType, ToType))
1257 return false;
1258
1259 // There are no conversions between extended vector types, only identity.
1260 if (ToType->isExtVectorType()) {
1261 // There are no conversions between extended vector types other than the
1262 // identity conversion.
1263 if (FromType->isExtVectorType())
1264 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Douglas Gregor46188682010-05-18 22:42:18 +00001266 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001267 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001268 ICK = ICK_Vector_Splat;
1269 return true;
1270 }
1271 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001272
1273 // We can perform the conversion between vector types in the following cases:
1274 // 1)vector types are equivalent AltiVec and GCC vector types
1275 // 2)lax vector conversions are permitted and the vector types are of the
1276 // same size
1277 if (ToType->isVectorType() && FromType->isVectorType()) {
1278 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001279 (Context.getLangOptions().LaxVectorConversions &&
1280 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001281 ICK = ICK_Vector_Conversion;
1282 return true;
1283 }
Douglas Gregor46188682010-05-18 22:42:18 +00001284 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001285
Douglas Gregor46188682010-05-18 22:42:18 +00001286 return false;
1287}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001288
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001289/// IsStandardConversion - Determines whether there is a standard
1290/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1291/// expression From to the type ToType. Standard conversion sequences
1292/// only consider non-class types; for conversions that involve class
1293/// types, use TryImplicitConversion. If a conversion exists, SCS will
1294/// contain the standard conversion sequence required to perform this
1295/// conversion and this routine will return true. Otherwise, this
1296/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001297static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1298 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001299 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001300 bool CStyle,
1301 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001304 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001305 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001306 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001307 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001308 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001309 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001310
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001311 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001312 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001313 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001314 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001315 return false;
1316
Mike Stump11289f42009-09-09 15:08:12 +00001317 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001318 }
1319
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001320 // The first conversion can be an lvalue-to-rvalue conversion,
1321 // array-to-pointer conversion, or function-to-pointer conversion
1322 // (C++ 4p1).
1323
John McCall5c32be02010-08-24 20:38:10 +00001324 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001325 DeclAccessPair AccessPair;
1326 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001327 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001328 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001329 // We were able to resolve the address of the overloaded function,
1330 // so we can convert to the type of that function.
1331 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001332
1333 // we can sometimes resolve &foo<int> regardless of ToType, so check
1334 // if the type matches (identity) or we are converting to bool
1335 if (!S.Context.hasSameUnqualifiedType(
1336 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1337 QualType resultTy;
1338 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001339 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001340 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1341 // otherwise, only a boolean conversion is standard
1342 if (!ToType->isBooleanType())
1343 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Chandler Carruthffce2452011-03-29 08:08:18 +00001346 // Check if the "from" expression is taking the address of an overloaded
1347 // function and recompute the FromType accordingly. Take advantage of the
1348 // fact that non-static member functions *must* have such an address-of
1349 // expression.
1350 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1351 if (Method && !Method->isStatic()) {
1352 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1353 "Non-unary operator on non-static member address");
1354 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1355 == UO_AddrOf &&
1356 "Non-address-of operator on non-static member address");
1357 const Type *ClassType
1358 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1359 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001360 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1361 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1362 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001363 "Non-address-of operator for overloaded function expression");
1364 FromType = S.Context.getPointerType(FromType);
1365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366
Douglas Gregor980fb162010-04-29 18:24:40 +00001367 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001368 assert(S.Context.hasSameType(
1369 FromType,
1370 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001371 } else {
1372 return false;
1373 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001374 }
John McCall154a2fd2011-08-30 00:57:29 +00001375 // Lvalue-to-rvalue conversion (C++11 4.1):
1376 // A glvalue (3.10) of a non-function, non-array type T can
1377 // be converted to a prvalue.
1378 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001379 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001380 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001381 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001382 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001383
1384 // If T is a non-class type, the type of the rvalue is the
1385 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001386 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1387 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001388 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001389 } else if (FromType->isArrayType()) {
1390 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001391 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001392
1393 // An lvalue or rvalue of type "array of N T" or "array of unknown
1394 // bound of T" can be converted to an rvalue of type "pointer to
1395 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001396 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001397
John McCall5c32be02010-08-24 20:38:10 +00001398 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001399 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001400 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001401
1402 // For the purpose of ranking in overload resolution
1403 // (13.3.3.1.1), this conversion is considered an
1404 // array-to-pointer conversion followed by a qualification
1405 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001406 SCS.Second = ICK_Identity;
1407 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001408 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001409 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001410 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001411 }
John McCall086a4642010-11-24 05:12:34 +00001412 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001413 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001414 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001415
1416 // An lvalue of function type T can be converted to an rvalue of
1417 // type "pointer to T." The result is a pointer to the
1418 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001419 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001420 } else {
1421 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001422 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001423 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001424 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001425
1426 // The second conversion can be an integral promotion, floating
1427 // point promotion, integral conversion, floating point conversion,
1428 // floating-integral conversion, pointer conversion,
1429 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001430 // For overloading in C, this can also be a "compatible-type"
1431 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001432 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001433 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001434 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435 // The unqualified versions of the types are the same: there's no
1436 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001437 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001438 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001439 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001440 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001441 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001442 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001443 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001445 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001446 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001447 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001448 SCS.Second = ICK_Complex_Promotion;
1449 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001450 } else if (ToType->isBooleanType() &&
1451 (FromType->isArithmeticType() ||
1452 FromType->isAnyPointerType() ||
1453 FromType->isBlockPointerType() ||
1454 FromType->isMemberPointerType() ||
1455 FromType->isNullPtrType())) {
1456 // Boolean conversions (C++ 4.12).
1457 SCS.Second = ICK_Boolean_Conversion;
1458 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001459 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001460 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001461 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001462 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001463 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001464 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001465 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001466 SCS.Second = ICK_Complex_Conversion;
1467 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001468 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1469 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001470 // Complex-real conversions (C99 6.3.1.7)
1471 SCS.Second = ICK_Complex_Real;
1472 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001473 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001474 // Floating point conversions (C++ 4.8).
1475 SCS.Second = ICK_Floating_Conversion;
1476 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001478 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001479 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001480 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001481 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001482 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001484 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001485 SCS.Second = ICK_Block_Pointer_Conversion;
1486 } else if (AllowObjCWritebackConversion &&
1487 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1488 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001489 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1490 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001491 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001492 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001493 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001494 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001496 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001497 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001498 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001499 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001500 SCS.Second = SecondICK;
1501 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001502 } else if (!S.getLangOptions().CPlusPlus &&
1503 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001504 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001505 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001506 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001507 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001508 // Treat a conversion that strips "noreturn" as an identity conversion.
1509 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001510 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1511 InOverloadResolution,
1512 SCS, CStyle)) {
1513 SCS.Second = ICK_TransparentUnionConversion;
1514 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001515 } else {
1516 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001517 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001518 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001519 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001520
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001521 QualType CanonFrom;
1522 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001524 bool ObjCLifetimeConversion;
1525 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1526 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001528 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001530 CanonFrom = S.Context.getCanonicalType(FromType);
1531 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001532 } else {
1533 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001534 SCS.Third = ICK_Identity;
1535
Mike Stump11289f42009-09-09 15:08:12 +00001536 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001537 // [...] Any difference in top-level cv-qualification is
1538 // subsumed by the initialization itself and does not constitute
1539 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001540 CanonFrom = S.Context.getCanonicalType(FromType);
1541 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001542 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001543 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001544 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001545 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1546 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001547 FromType = ToType;
1548 CanonFrom = CanonTo;
1549 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001551 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001552
1553 // If we have not converted the argument type to the parameter type,
1554 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001555 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001560
1561static bool
1562IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1563 QualType &ToType,
1564 bool InOverloadResolution,
1565 StandardConversionSequence &SCS,
1566 bool CStyle) {
1567
1568 const RecordType *UT = ToType->getAsUnionType();
1569 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1570 return false;
1571 // The field to initialize within the transparent union.
1572 RecordDecl *UD = UT->getDecl();
1573 // It's compatible if the expression matches any of the fields.
1574 for (RecordDecl::field_iterator it = UD->field_begin(),
1575 itend = UD->field_end();
1576 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001577 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1578 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001579 ToType = it->getType();
1580 return true;
1581 }
1582 }
1583 return false;
1584}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585
1586/// IsIntegralPromotion - Determines whether the conversion from the
1587/// expression From (whose potentially-adjusted type is FromType) to
1588/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1589/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001590bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001591 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001592 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001593 if (!To) {
1594 return false;
1595 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596
1597 // An rvalue of type char, signed char, unsigned char, short int, or
1598 // unsigned short int can be converted to an rvalue of type int if
1599 // int can represent all the values of the source type; otherwise,
1600 // the source rvalue can be converted to an rvalue of type unsigned
1601 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001602 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1603 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604 if (// We can promote any signed, promotable integer type to an int
1605 (FromType->isSignedIntegerType() ||
1606 // We can promote any unsigned integer type whose size is
1607 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001608 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001609 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001610 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001611 }
1612
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001613 return To->getKind() == BuiltinType::UInt;
1614 }
1615
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616 // C++0x [conv.prom]p3:
1617 // A prvalue of an unscoped enumeration type whose underlying type is not
1618 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1619 // following types that can represent all the values of the enumeration
1620 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1621 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001622 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001624 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001625 // with lowest integer conversion rank (4.13) greater than the rank of long
1626 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001627 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001628 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1629 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1630 // provided for a scoped enumeration.
1631 if (FromEnumType->getDecl()->isScoped())
1632 return false;
1633
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001634 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001635 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001636 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001637 return Context.hasSameUnqualifiedType(ToType,
1638 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001639 }
John McCall56774992009-12-09 09:09:27 +00001640
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001641 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1643 // to an rvalue a prvalue of the first of the following types that can
1644 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001645 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001646 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001647 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001649 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001651 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001652 // Determine whether the type we're converting from is signed or
1653 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001654 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657 // The types we'll try to promote to, in the appropriate
1658 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001659 QualType PromoteTypes[6] = {
1660 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001661 Context.LongTy, Context.UnsignedLongTy ,
1662 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001664 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1666 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001667 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1669 // We found the type that we can promote to. If this is the
1670 // type we wanted, we have a promotion. Otherwise, no
1671 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001672 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 }
1674 }
1675 }
1676
1677 // An rvalue for an integral bit-field (9.6) can be converted to an
1678 // rvalue of type int if int can represent all the values of the
1679 // bit-field; otherwise, it can be converted to unsigned int if
1680 // unsigned int can represent all the values of the bit-field. If
1681 // the bit-field is larger yet, no integral promotion applies to
1682 // it. If the bit-field has an enumerated type, it is treated as any
1683 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001684 // FIXME: We should delay checking of bit-fields until we actually perform the
1685 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001686 using llvm::APSInt;
1687 if (From)
1688 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001689 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001690 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001691 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1692 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1693 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001694
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001695 // Are we promoting to an int from a bitfield that fits in an int?
1696 if (BitWidth < ToSize ||
1697 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1698 return To->getKind() == BuiltinType::Int;
1699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001701 // Are we promoting to an unsigned int from an unsigned bitfield
1702 // that fits into an unsigned int?
1703 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1704 return To->getKind() == BuiltinType::UInt;
1705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001707 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711 // An rvalue of type bool can be converted to an rvalue of type int,
1712 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001713 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001715 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001716
1717 return false;
1718}
1719
1720/// IsFloatingPointPromotion - Determines whether the conversion from
1721/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1722/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001723bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001724 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1725 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001726 /// An rvalue of type float can be converted to an rvalue of type
1727 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001728 if (FromBuiltin->getKind() == BuiltinType::Float &&
1729 ToBuiltin->getKind() == BuiltinType::Double)
1730 return true;
1731
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001732 // C99 6.3.1.5p1:
1733 // When a float is promoted to double or long double, or a
1734 // double is promoted to long double [...].
1735 if (!getLangOptions().CPlusPlus &&
1736 (FromBuiltin->getKind() == BuiltinType::Float ||
1737 FromBuiltin->getKind() == BuiltinType::Double) &&
1738 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1739 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001740
1741 // Half can be promoted to float.
1742 if (FromBuiltin->getKind() == BuiltinType::Half &&
1743 ToBuiltin->getKind() == BuiltinType::Float)
1744 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001745 }
1746
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747 return false;
1748}
1749
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001750/// \brief Determine if a conversion is a complex promotion.
1751///
1752/// A complex promotion is defined as a complex -> complex conversion
1753/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001754/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001755bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001756 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001757 if (!FromComplex)
1758 return false;
1759
John McCall9dd450b2009-09-21 23:43:11 +00001760 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001761 if (!ToComplex)
1762 return false;
1763
1764 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001765 ToComplex->getElementType()) ||
1766 IsIntegralPromotion(0, FromComplex->getElementType(),
1767 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001768}
1769
Douglas Gregor237f96c2008-11-26 23:31:11 +00001770/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1771/// the pointer type FromPtr to a pointer to type ToPointee, with the
1772/// same type qualifiers as FromPtr has on its pointee type. ToType,
1773/// if non-empty, will be a pointer to ToType that may or may not have
1774/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001775///
Mike Stump11289f42009-09-09 15:08:12 +00001776static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001777BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001778 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001779 ASTContext &Context,
1780 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001781 assert((FromPtr->getTypeClass() == Type::Pointer ||
1782 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1783 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
John McCall31168b02011-06-15 23:02:42 +00001785 /// Conversions to 'id' subsume cv-qualifier conversions.
1786 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001787 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788
1789 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001790 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001791 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001792 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001793
John McCall31168b02011-06-15 23:02:42 +00001794 if (StripObjCLifetime)
1795 Quals.removeObjCLifetime();
1796
Mike Stump11289f42009-09-09 15:08:12 +00001797 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001798 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001799 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001800 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001801 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001802
1803 // Build a pointer to ToPointee. It has the right qualifiers
1804 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001805 if (isa<ObjCObjectPointerType>(ToType))
1806 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001807 return Context.getPointerType(ToPointee);
1808 }
1809
1810 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001811 QualType QualifiedCanonToPointee
1812 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001813
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001814 if (isa<ObjCObjectPointerType>(ToType))
1815 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1816 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001817}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818
Mike Stump11289f42009-09-09 15:08:12 +00001819static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001820 bool InOverloadResolution,
1821 ASTContext &Context) {
1822 // Handle value-dependent integral null pointer constants correctly.
1823 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1824 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001825 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001826 return !InOverloadResolution;
1827
Douglas Gregor56751b52009-09-25 04:25:58 +00001828 return Expr->isNullPointerConstant(Context,
1829 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1830 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001831}
Mike Stump11289f42009-09-09 15:08:12 +00001832
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833/// IsPointerConversion - Determines whether the conversion of the
1834/// expression From, which has the (possibly adjusted) type FromType,
1835/// can be converted to the type ToType via a pointer conversion (C++
1836/// 4.10). If so, returns true and places the converted type (that
1837/// might differ from ToType in its cv-qualifiers at some level) into
1838/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001839///
Douglas Gregora29dc052008-11-27 01:19:21 +00001840/// This routine also supports conversions to and from block pointers
1841/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1842/// pointers to interfaces. FIXME: Once we've determined the
1843/// appropriate overloading rules for Objective-C, we may want to
1844/// split the Objective-C checks into a different routine; however,
1845/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001846/// conversions, so for now they live here. IncompatibleObjC will be
1847/// set if the conversion is an allowed Objective-C conversion that
1848/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001849bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001850 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001851 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001852 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001853 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001854 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1855 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001856 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001857
Mike Stump11289f42009-09-09 15:08:12 +00001858 // Conversion from a null pointer constant to any Objective-C pointer type.
1859 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001860 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001861 ConvertedType = ToType;
1862 return true;
1863 }
1864
Douglas Gregor231d1c62008-11-27 00:15:41 +00001865 // Blocks: Block pointers can be converted to void*.
1866 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001868 ConvertedType = ToType;
1869 return true;
1870 }
1871 // Blocks: A null pointer constant can be converted to a block
1872 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001873 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001874 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001875 ConvertedType = ToType;
1876 return true;
1877 }
1878
Sebastian Redl576fd422009-05-10 18:38:11 +00001879 // If the left-hand-side is nullptr_t, the right side can be a null
1880 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001881 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001882 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001883 ConvertedType = ToType;
1884 return true;
1885 }
1886
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001887 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888 if (!ToTypePtr)
1889 return false;
1890
1891 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001892 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001893 ConvertedType = ToType;
1894 return true;
1895 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001898 // , including objective-c pointers.
1899 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001900 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1901 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001902 ConvertedType = BuildSimilarlyQualifiedPointerType(
1903 FromType->getAs<ObjCObjectPointerType>(),
1904 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001905 ToType, Context);
1906 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001907 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001908 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001909 if (!FromTypePtr)
1910 return false;
1911
1912 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001913
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001915 // pointer conversion, so don't do all of the work below.
1916 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1917 return false;
1918
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001919 // An rvalue of type "pointer to cv T," where T is an object type,
1920 // can be converted to an rvalue of type "pointer to cv void" (C++
1921 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001922 if (FromPointeeType->isIncompleteOrObjectType() &&
1923 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001924 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001925 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001926 ToType, Context,
1927 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001928 return true;
1929 }
1930
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001931 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001932 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001933 ToPointeeType->isVoidType()) {
1934 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1935 ToPointeeType,
1936 ToType, Context);
1937 return true;
1938 }
1939
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001940 // When we're overloading in C, we allow a special kind of pointer
1941 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001942 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001943 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001944 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001945 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001946 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001947 return true;
1948 }
1949
Douglas Gregor5c407d92008-10-23 00:40:37 +00001950 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001951 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001952 // An rvalue of type "pointer to cv D," where D is a class type,
1953 // can be converted to an rvalue of type "pointer to cv B," where
1954 // B is a base class (clause 10) of D. If B is an inaccessible
1955 // (clause 11) or ambiguous (10.2) base class of D, a program that
1956 // necessitates this conversion is ill-formed. The result of the
1957 // conversion is a pointer to the base class sub-object of the
1958 // derived class object. The null pointer value is converted to
1959 // the null pointer value of the destination type.
1960 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001961 // Note that we do not check for ambiguity or inaccessibility
1962 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001963 if (getLangOptions().CPlusPlus &&
1964 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001965 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001966 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001967 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001969 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001970 ToType, Context);
1971 return true;
1972 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001973
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001974 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1975 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1977 ToPointeeType,
1978 ToType, Context);
1979 return true;
1980 }
1981
Douglas Gregora119f102008-12-19 19:13:09 +00001982 return false;
1983}
Douglas Gregoraec25842011-04-26 23:16:46 +00001984
1985/// \brief Adopt the given qualifiers for the given type.
1986static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1987 Qualifiers TQs = T.getQualifiers();
1988
1989 // Check whether qualifiers already match.
1990 if (TQs == Qs)
1991 return T;
1992
1993 if (Qs.compatiblyIncludes(TQs))
1994 return Context.getQualifiedType(T, Qs);
1995
1996 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1997}
Douglas Gregora119f102008-12-19 19:13:09 +00001998
1999/// isObjCPointerConversion - Determines whether this is an
2000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2001/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002003 QualType& ConvertedType,
2004 bool &IncompatibleObjC) {
2005 if (!getLangOptions().ObjC1)
2006 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007
Douglas Gregoraec25842011-04-26 23:16:46 +00002008 // The set of qualifiers on the type we're converting from.
2009 Qualifiers FromQualifiers = FromType.getQualifiers();
2010
Steve Naroff7cae42b2009-07-10 23:34:53 +00002011 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002012 const ObjCObjectPointerType* ToObjCPtr =
2013 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002014 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002015 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002016
Steve Naroff7cae42b2009-07-10 23:34:53 +00002017 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002018 // If the pointee types are the same (ignoring qualifications),
2019 // then this is not a pointer conversion.
2020 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2021 FromObjCPtr->getPointeeType()))
2022 return false;
2023
Douglas Gregoraec25842011-04-26 23:16:46 +00002024 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002025 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002026 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002027 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002028 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002029 return true;
2030 }
2031 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002032 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002033 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002034 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002035 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002036 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002037 return true;
2038 }
2039 // Objective C++: We're able to convert from a pointer to an
2040 // interface to a pointer to a different interface.
2041 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002042 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2043 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2044 if (getLangOptions().CPlusPlus && LHS && RHS &&
2045 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2046 FromObjCPtr->getPointeeType()))
2047 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002049 ToObjCPtr->getPointeeType(),
2050 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002051 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002052 return true;
2053 }
2054
2055 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2056 // Okay: this is some kind of implicit downcast of Objective-C
2057 // interfaces, which is permitted. However, we're going to
2058 // complain about it.
2059 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002061 ToObjCPtr->getPointeeType(),
2062 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002063 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002064 return true;
2065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002067 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002068 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002069 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002070 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002072 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002073 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002074 // to a block pointer type.
2075 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002076 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002077 return true;
2078 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002079 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002082 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002084 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002085 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002086 return true;
2087 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002088 else
Douglas Gregora119f102008-12-19 19:13:09 +00002089 return false;
2090
Douglas Gregor033f56d2008-12-23 00:53:59 +00002091 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002092 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002093 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002094 else if (const BlockPointerType *FromBlockPtr =
2095 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002096 FromPointeeType = FromBlockPtr->getPointeeType();
2097 else
Douglas Gregora119f102008-12-19 19:13:09 +00002098 return false;
2099
Douglas Gregora119f102008-12-19 19:13:09 +00002100 // If we have pointers to pointers, recursively check whether this
2101 // is an Objective-C conversion.
2102 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2103 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2104 IncompatibleObjC)) {
2105 // We always complain about this conversion.
2106 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002107 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002108 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002109 return true;
2110 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002111 // Allow conversion of pointee being objective-c pointer to another one;
2112 // as in I* to id.
2113 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2114 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2115 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2116 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002117
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002118 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002119 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002120 return true;
2121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122
Douglas Gregor033f56d2008-12-23 00:53:59 +00002123 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002124 // differences in the argument and result types are in Objective-C
2125 // pointer conversions. If so, we permit the conversion (but
2126 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002127 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002128 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002129 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002130 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002131 if (FromFunctionType && ToFunctionType) {
2132 // If the function types are exactly the same, this isn't an
2133 // Objective-C pointer conversion.
2134 if (Context.getCanonicalType(FromPointeeType)
2135 == Context.getCanonicalType(ToPointeeType))
2136 return false;
2137
2138 // Perform the quick checks that will tell us whether these
2139 // function types are obviously different.
2140 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2141 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2142 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2143 return false;
2144
2145 bool HasObjCConversion = false;
2146 if (Context.getCanonicalType(FromFunctionType->getResultType())
2147 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2148 // Okay, the types match exactly. Nothing to do.
2149 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2150 ToFunctionType->getResultType(),
2151 ConvertedType, IncompatibleObjC)) {
2152 // Okay, we have an Objective-C pointer conversion.
2153 HasObjCConversion = true;
2154 } else {
2155 // Function types are too different. Abort.
2156 return false;
2157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158
Douglas Gregora119f102008-12-19 19:13:09 +00002159 // Check argument types.
2160 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2161 ArgIdx != NumArgs; ++ArgIdx) {
2162 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2163 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2164 if (Context.getCanonicalType(FromArgType)
2165 == Context.getCanonicalType(ToArgType)) {
2166 // Okay, the types match exactly. Nothing to do.
2167 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2168 ConvertedType, IncompatibleObjC)) {
2169 // Okay, we have an Objective-C pointer conversion.
2170 HasObjCConversion = true;
2171 } else {
2172 // Argument types are too different. Abort.
2173 return false;
2174 }
2175 }
2176
2177 if (HasObjCConversion) {
2178 // We had an Objective-C conversion. Allow this pointer
2179 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002180 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002181 IncompatibleObjC = true;
2182 return true;
2183 }
2184 }
2185
Sebastian Redl72b597d2009-01-25 19:43:20 +00002186 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188
John McCall31168b02011-06-15 23:02:42 +00002189/// \brief Determine whether this is an Objective-C writeback conversion,
2190/// used for parameter passing when performing automatic reference counting.
2191///
2192/// \param FromType The type we're converting form.
2193///
2194/// \param ToType The type we're converting to.
2195///
2196/// \param ConvertedType The type that will be produced after applying
2197/// this conversion.
2198bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2199 QualType &ConvertedType) {
2200 if (!getLangOptions().ObjCAutoRefCount ||
2201 Context.hasSameUnqualifiedType(FromType, ToType))
2202 return false;
2203
2204 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2205 QualType ToPointee;
2206 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2207 ToPointee = ToPointer->getPointeeType();
2208 else
2209 return false;
2210
2211 Qualifiers ToQuals = ToPointee.getQualifiers();
2212 if (!ToPointee->isObjCLifetimeType() ||
2213 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2214 !ToQuals.withoutObjCGLifetime().empty())
2215 return false;
2216
2217 // Argument must be a pointer to __strong to __weak.
2218 QualType FromPointee;
2219 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2220 FromPointee = FromPointer->getPointeeType();
2221 else
2222 return false;
2223
2224 Qualifiers FromQuals = FromPointee.getQualifiers();
2225 if (!FromPointee->isObjCLifetimeType() ||
2226 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2227 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2228 return false;
2229
2230 // Make sure that we have compatible qualifiers.
2231 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2232 if (!ToQuals.compatiblyIncludes(FromQuals))
2233 return false;
2234
2235 // Remove qualifiers from the pointee type we're converting from; they
2236 // aren't used in the compatibility check belong, and we'll be adding back
2237 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2238 FromPointee = FromPointee.getUnqualifiedType();
2239
2240 // The unqualified form of the pointee types must be compatible.
2241 ToPointee = ToPointee.getUnqualifiedType();
2242 bool IncompatibleObjC;
2243 if (Context.typesAreCompatible(FromPointee, ToPointee))
2244 FromPointee = ToPointee;
2245 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2246 IncompatibleObjC))
2247 return false;
2248
2249 /// \brief Construct the type we're converting to, which is a pointer to
2250 /// __autoreleasing pointee.
2251 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2252 ConvertedType = Context.getPointerType(FromPointee);
2253 return true;
2254}
2255
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002256bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2257 QualType& ConvertedType) {
2258 QualType ToPointeeType;
2259 if (const BlockPointerType *ToBlockPtr =
2260 ToType->getAs<BlockPointerType>())
2261 ToPointeeType = ToBlockPtr->getPointeeType();
2262 else
2263 return false;
2264
2265 QualType FromPointeeType;
2266 if (const BlockPointerType *FromBlockPtr =
2267 FromType->getAs<BlockPointerType>())
2268 FromPointeeType = FromBlockPtr->getPointeeType();
2269 else
2270 return false;
2271 // We have pointer to blocks, check whether the only
2272 // differences in the argument and result types are in Objective-C
2273 // pointer conversions. If so, we permit the conversion.
2274
2275 const FunctionProtoType *FromFunctionType
2276 = FromPointeeType->getAs<FunctionProtoType>();
2277 const FunctionProtoType *ToFunctionType
2278 = ToPointeeType->getAs<FunctionProtoType>();
2279
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002280 if (!FromFunctionType || !ToFunctionType)
2281 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002282
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002283 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002284 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002285
2286 // Perform the quick checks that will tell us whether these
2287 // function types are obviously different.
2288 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2289 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2290 return false;
2291
2292 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2293 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2294 if (FromEInfo != ToEInfo)
2295 return false;
2296
2297 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002298 if (Context.hasSameType(FromFunctionType->getResultType(),
2299 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002300 // Okay, the types match exactly. Nothing to do.
2301 } else {
2302 QualType RHS = FromFunctionType->getResultType();
2303 QualType LHS = ToFunctionType->getResultType();
2304 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2305 !RHS.hasQualifiers() && LHS.hasQualifiers())
2306 LHS = LHS.getUnqualifiedType();
2307
2308 if (Context.hasSameType(RHS,LHS)) {
2309 // OK exact match.
2310 } else if (isObjCPointerConversion(RHS, LHS,
2311 ConvertedType, IncompatibleObjC)) {
2312 if (IncompatibleObjC)
2313 return false;
2314 // Okay, we have an Objective-C pointer conversion.
2315 }
2316 else
2317 return false;
2318 }
2319
2320 // Check argument types.
2321 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2322 ArgIdx != NumArgs; ++ArgIdx) {
2323 IncompatibleObjC = false;
2324 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2325 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2326 if (Context.hasSameType(FromArgType, ToArgType)) {
2327 // Okay, the types match exactly. Nothing to do.
2328 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2329 ConvertedType, IncompatibleObjC)) {
2330 if (IncompatibleObjC)
2331 return false;
2332 // Okay, we have an Objective-C pointer conversion.
2333 } else
2334 // Argument types are too different. Abort.
2335 return false;
2336 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002337 if (LangOpts.ObjCAutoRefCount &&
2338 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2339 ToFunctionType))
2340 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002341
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002342 ConvertedType = ToType;
2343 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002344}
2345
Richard Trieucaff2472011-11-23 22:32:32 +00002346enum {
2347 ft_default,
2348 ft_different_class,
2349 ft_parameter_arity,
2350 ft_parameter_mismatch,
2351 ft_return_type,
2352 ft_qualifer_mismatch
2353};
2354
2355/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2356/// function types. Catches different number of parameter, mismatch in
2357/// parameter types, and different return types.
2358void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2359 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002360 // If either type is not valid, include no extra info.
2361 if (FromType.isNull() || ToType.isNull()) {
2362 PDiag << ft_default;
2363 return;
2364 }
2365
Richard Trieucaff2472011-11-23 22:32:32 +00002366 // Get the function type from the pointers.
2367 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2368 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2369 *ToMember = ToType->getAs<MemberPointerType>();
2370 if (FromMember->getClass() != ToMember->getClass()) {
2371 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2372 << QualType(FromMember->getClass(), 0);
2373 return;
2374 }
2375 FromType = FromMember->getPointeeType();
2376 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002377 }
2378
Richard Trieu96ed5b62011-12-13 23:19:45 +00002379 if (FromType->isPointerType())
2380 FromType = FromType->getPointeeType();
2381 if (ToType->isPointerType())
2382 ToType = ToType->getPointeeType();
2383
2384 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002385 FromType = FromType.getNonReferenceType();
2386 ToType = ToType.getNonReferenceType();
2387
Richard Trieucaff2472011-11-23 22:32:32 +00002388 // Don't print extra info for non-specialized template functions.
2389 if (FromType->isInstantiationDependentType() &&
2390 !FromType->getAs<TemplateSpecializationType>()) {
2391 PDiag << ft_default;
2392 return;
2393 }
2394
Richard Trieu96ed5b62011-12-13 23:19:45 +00002395 // No extra info for same types.
2396 if (Context.hasSameType(FromType, ToType)) {
2397 PDiag << ft_default;
2398 return;
2399 }
2400
Richard Trieucaff2472011-11-23 22:32:32 +00002401 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2402 *ToFunction = ToType->getAs<FunctionProtoType>();
2403
2404 // Both types need to be function types.
2405 if (!FromFunction || !ToFunction) {
2406 PDiag << ft_default;
2407 return;
2408 }
2409
2410 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2411 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2412 << FromFunction->getNumArgs();
2413 return;
2414 }
2415
2416 // Handle different parameter types.
2417 unsigned ArgPos;
2418 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2419 PDiag << ft_parameter_mismatch << ArgPos + 1
2420 << ToFunction->getArgType(ArgPos)
2421 << FromFunction->getArgType(ArgPos);
2422 return;
2423 }
2424
2425 // Handle different return type.
2426 if (!Context.hasSameType(FromFunction->getResultType(),
2427 ToFunction->getResultType())) {
2428 PDiag << ft_return_type << ToFunction->getResultType()
2429 << FromFunction->getResultType();
2430 return;
2431 }
2432
2433 unsigned FromQuals = FromFunction->getTypeQuals(),
2434 ToQuals = ToFunction->getTypeQuals();
2435 if (FromQuals != ToQuals) {
2436 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2437 return;
2438 }
2439
2440 // Unable to find a difference, so add no extra info.
2441 PDiag << ft_default;
2442}
2443
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002444/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002445/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002446/// they have same number of arguments. This routine assumes that Objective-C
2447/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002448/// If the parameters are different, ArgPos will have the the parameter index
2449/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002451 const FunctionProtoType *NewType,
2452 unsigned *ArgPos) {
2453 if (!getLangOptions().ObjC1) {
2454 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2455 N = NewType->arg_type_begin(),
2456 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2457 if (!Context.hasSameType(*O, *N)) {
2458 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2459 return false;
2460 }
2461 }
2462 return true;
2463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002465 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2466 N = NewType->arg_type_begin(),
2467 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2468 QualType ToType = (*O);
2469 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002470 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002471 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2472 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002473 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2474 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2475 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2476 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002477 continue;
2478 }
John McCall8b07ec22010-05-15 11:32:37 +00002479 else if (const ObjCObjectPointerType *PTTo =
2480 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002481 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002482 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002483 if (Context.hasSameUnqualifiedType(
2484 PTTo->getObjectType()->getBaseType(),
2485 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002486 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002487 }
Richard Trieucaff2472011-11-23 22:32:32 +00002488 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002490 }
2491 }
2492 return true;
2493}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002494
Douglas Gregor39c16d42008-10-24 04:54:22 +00002495/// CheckPointerConversion - Check the pointer conversion from the
2496/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002497/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002498/// conversions for which IsPointerConversion has already returned
2499/// true. It returns true and produces a diagnostic if there was an
2500/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002501bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002502 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002503 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002504 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002505 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002506 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002507
John McCall8cb679e2010-11-15 09:13:47 +00002508 Kind = CK_BitCast;
2509
Chandler Carruthffab8732011-04-09 07:32:05 +00002510 if (!IsCStyleOrFunctionalCast &&
2511 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2512 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2513 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002514 PDiag(diag::warn_impcast_bool_to_null_pointer)
2515 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002516
John McCall9320b872011-09-09 05:25:32 +00002517 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2518 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002519 QualType FromPointeeType = FromPtrType->getPointeeType(),
2520 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002521
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002522 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2523 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002524 // We must have a derived-to-base conversion. Check an
2525 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002526 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2527 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002528 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002529 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002530 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002531
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002532 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002533 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002534 }
2535 }
John McCall9320b872011-09-09 05:25:32 +00002536 } else if (const ObjCObjectPointerType *ToPtrType =
2537 ToType->getAs<ObjCObjectPointerType>()) {
2538 if (const ObjCObjectPointerType *FromPtrType =
2539 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002540 // Objective-C++ conversions are always okay.
2541 // FIXME: We should have a different class of conversions for the
2542 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002543 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002544 return false;
John McCall9320b872011-09-09 05:25:32 +00002545 } else if (FromType->isBlockPointerType()) {
2546 Kind = CK_BlockPointerToObjCPointerCast;
2547 } else {
2548 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002549 }
John McCall9320b872011-09-09 05:25:32 +00002550 } else if (ToType->isBlockPointerType()) {
2551 if (!FromType->isBlockPointerType())
2552 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002553 }
John McCall8cb679e2010-11-15 09:13:47 +00002554
2555 // We shouldn't fall into this case unless it's valid for other
2556 // reasons.
2557 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2558 Kind = CK_NullToPointer;
2559
Douglas Gregor39c16d42008-10-24 04:54:22 +00002560 return false;
2561}
2562
Sebastian Redl72b597d2009-01-25 19:43:20 +00002563/// IsMemberPointerConversion - Determines whether the conversion of the
2564/// expression From, which has the (possibly adjusted) type FromType, can be
2565/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2566/// If so, returns true and places the converted type (that might differ from
2567/// ToType in its cv-qualifiers at some level) into ConvertedType.
2568bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002570 bool InOverloadResolution,
2571 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002572 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002573 if (!ToTypePtr)
2574 return false;
2575
2576 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002577 if (From->isNullPointerConstant(Context,
2578 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2579 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002580 ConvertedType = ToType;
2581 return true;
2582 }
2583
2584 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002585 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002586 if (!FromTypePtr)
2587 return false;
2588
2589 // A pointer to member of B can be converted to a pointer to member of D,
2590 // where D is derived from B (C++ 4.11p2).
2591 QualType FromClass(FromTypePtr->getClass(), 0);
2592 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002593
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002594 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2595 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2596 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002597 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2598 ToClass.getTypePtr());
2599 return true;
2600 }
2601
2602 return false;
2603}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002604
Sebastian Redl72b597d2009-01-25 19:43:20 +00002605/// CheckMemberPointerConversion - Check the member pointer conversion from the
2606/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002607/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002608/// for which IsMemberPointerConversion has already returned true. It returns
2609/// true and produces a diagnostic if there was an error, or returns false
2610/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002611bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002612 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002613 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002614 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002615 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002616 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002617 if (!FromPtrType) {
2618 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002619 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002620 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002621 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002622 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002623 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002624 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002625
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002626 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002627 assert(ToPtrType && "No member pointer cast has a target type "
2628 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002629
Sebastian Redled8f2002009-01-28 18:33:18 +00002630 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2631 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002632
Sebastian Redled8f2002009-01-28 18:33:18 +00002633 // FIXME: What about dependent types?
2634 assert(FromClass->isRecordType() && "Pointer into non-class.");
2635 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002636
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002637 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002638 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002639 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2640 assert(DerivationOkay &&
2641 "Should not have been called if derivation isn't OK.");
2642 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002643
Sebastian Redled8f2002009-01-28 18:33:18 +00002644 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2645 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002646 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2647 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2648 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2649 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002650 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002651
Douglas Gregor89ee6822009-02-28 01:32:25 +00002652 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002653 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2654 << FromClass << ToClass << QualType(VBase, 0)
2655 << From->getSourceRange();
2656 return true;
2657 }
2658
John McCall5b0829a2010-02-10 09:31:12 +00002659 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002660 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2661 Paths.front(),
2662 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002663
Anders Carlssond7923c62009-08-22 23:33:40 +00002664 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002665 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002666 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002667 return false;
2668}
2669
Douglas Gregor9a657932008-10-21 23:43:52 +00002670/// IsQualificationConversion - Determines whether the conversion from
2671/// an rvalue of type FromType to ToType is a qualification conversion
2672/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002673///
2674/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2675/// when the qualification conversion involves a change in the Objective-C
2676/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002677bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002679 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002680 FromType = Context.getCanonicalType(FromType);
2681 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002682 ObjCLifetimeConversion = false;
2683
Douglas Gregor9a657932008-10-21 23:43:52 +00002684 // If FromType and ToType are the same type, this is not a
2685 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002686 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002687 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002688
Douglas Gregor9a657932008-10-21 23:43:52 +00002689 // (C++ 4.4p4):
2690 // A conversion can add cv-qualifiers at levels other than the first
2691 // in multi-level pointers, subject to the following rules: [...]
2692 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002693 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002694 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002695 // Within each iteration of the loop, we check the qualifiers to
2696 // determine if this still looks like a qualification
2697 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002698 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002699 // until there are no more pointers or pointers-to-members left to
2700 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002701 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002702
Douglas Gregor90609aa2011-04-25 18:40:17 +00002703 Qualifiers FromQuals = FromType.getQualifiers();
2704 Qualifiers ToQuals = ToType.getQualifiers();
2705
John McCall31168b02011-06-15 23:02:42 +00002706 // Objective-C ARC:
2707 // Check Objective-C lifetime conversions.
2708 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2709 UnwrappedAnyPointer) {
2710 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2711 ObjCLifetimeConversion = true;
2712 FromQuals.removeObjCLifetime();
2713 ToQuals.removeObjCLifetime();
2714 } else {
2715 // Qualification conversions cannot cast between different
2716 // Objective-C lifetime qualifiers.
2717 return false;
2718 }
2719 }
2720
Douglas Gregorf30053d2011-05-08 06:09:53 +00002721 // Allow addition/removal of GC attributes but not changing GC attributes.
2722 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2723 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2724 FromQuals.removeObjCGCAttr();
2725 ToQuals.removeObjCGCAttr();
2726 }
2727
Douglas Gregor9a657932008-10-21 23:43:52 +00002728 // -- for every j > 0, if const is in cv 1,j then const is in cv
2729 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002730 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002731 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002732
Douglas Gregor9a657932008-10-21 23:43:52 +00002733 // -- if the cv 1,j and cv 2,j are different, then const is in
2734 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002735 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002736 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002737 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002738
Douglas Gregor9a657932008-10-21 23:43:52 +00002739 // Keep track of whether all prior cv-qualifiers in the "to" type
2740 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002741 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002742 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002743 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002744
2745 // We are left with FromType and ToType being the pointee types
2746 // after unwrapping the original FromType and ToType the same number
2747 // of types. If we unwrapped any pointers, and if FromType and
2748 // ToType have the same unqualified type (since we checked
2749 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002750 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002751}
2752
Douglas Gregor576e98c2009-01-30 23:27:23 +00002753/// Determines whether there is a user-defined conversion sequence
2754/// (C++ [over.ics.user]) that converts expression From to the type
2755/// ToType. If such a conversion exists, User will contain the
2756/// user-defined conversion sequence that performs such a conversion
2757/// and this routine will return true. Otherwise, this routine returns
2758/// false and User is unspecified.
2759///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002760/// \param AllowExplicit true if the conversion should consider C++0x
2761/// "explicit" conversion functions as well as non-explicit conversion
2762/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002763static OverloadingResult
2764IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2765 UserDefinedConversionSequence& User,
2766 OverloadCandidateSet& CandidateSet,
2767 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002768 // Whether we will only visit constructors.
2769 bool ConstructorsOnly = false;
2770
2771 // If the type we are conversion to is a class type, enumerate its
2772 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002773 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002774 // C++ [over.match.ctor]p1:
2775 // When objects of class type are direct-initialized (8.5), or
2776 // copy-initialized from an expression of the same or a
2777 // derived class type (8.5), overload resolution selects the
2778 // constructor. [...] For copy-initialization, the candidate
2779 // functions are all the converting constructors (12.3.1) of
2780 // that class. The argument list is the expression-list within
2781 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002782 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002783 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002784 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002785 ConstructorsOnly = true;
2786
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002787 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2788 // RequireCompleteType may have returned true due to some invalid decl
2789 // during template instantiation, but ToType may be complete enough now
2790 // to try to recover.
2791 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002792 // We're not going to find any constructors.
2793 } else if (CXXRecordDecl *ToRecordDecl
2794 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002795
2796 Expr **Args = &From;
2797 unsigned NumArgs = 1;
2798 bool ListInitializing = false;
2799 // If we're list-initializing, we pass the individual elements as
2800 // arguments, not the entire list.
2801 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2802 Args = InitList->getInits();
2803 NumArgs = InitList->getNumInits();
2804 ListInitializing = true;
2805 }
2806
Douglas Gregor89ee6822009-02-28 01:32:25 +00002807 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002808 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002809 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002810 NamedDecl *D = *Con;
2811 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2812
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002813 // Find the constructor (which may be a template).
2814 CXXConstructorDecl *Constructor = 0;
2815 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002816 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002817 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002818 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002819 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2820 else
John McCalla0296f72010-03-19 07:35:19 +00002821 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002823 bool Usable = !Constructor->isInvalidDecl();
2824 if (ListInitializing)
2825 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2826 else
2827 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2828 if (Usable) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002829 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002830 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2831 /*ExplicitArgs*/ 0,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002832 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002833 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002834 !ConstructorsOnly &&
2835 !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002836 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002837 // Allow one user-defined conversion when user specifies a
2838 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002839 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002840 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002841 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002842 !ConstructorsOnly && !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002843 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002844 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002845 }
2846 }
2847
Douglas Gregor5ab11652010-04-17 22:01:05 +00002848 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002849 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002850 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2851 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002852 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002853 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002854 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002855 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002856 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2857 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002858 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002859 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002860 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002861 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002862 DeclAccessPair FoundDecl = I.getPair();
2863 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002864 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2865 if (isa<UsingShadowDecl>(D))
2866 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2867
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002868 CXXConversionDecl *Conv;
2869 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002870 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2871 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002872 else
John McCallda4458e2010-03-31 01:36:47 +00002873 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002874
2875 if (AllowExplicit || !Conv->isExplicit()) {
2876 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002877 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2878 ActingContext, From, ToType,
2879 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002880 else
John McCall5c32be02010-08-24 20:38:10 +00002881 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2882 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002883 }
2884 }
2885 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002886 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002887
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002888 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2889
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002890 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002891 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002892 case OR_Success:
2893 // Record the standard conversion we used and the conversion function.
2894 if (CXXConstructorDecl *Constructor
2895 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002896 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00002897
John McCall5c32be02010-08-24 20:38:10 +00002898 // C++ [over.ics.user]p1:
2899 // If the user-defined conversion is specified by a
2900 // constructor (12.3.1), the initial standard conversion
2901 // sequence converts the source type to the type required by
2902 // the argument of the constructor.
2903 //
2904 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002905 if (isa<InitListExpr>(From)) {
2906 // Initializer lists don't have conversions as such.
2907 User.Before.setAsIdentityConversion();
2908 } else {
2909 if (Best->Conversions[0].isEllipsis())
2910 User.EllipsisConversion = true;
2911 else {
2912 User.Before = Best->Conversions[0].Standard;
2913 User.EllipsisConversion = false;
2914 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002915 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002916 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002917 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002918 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002919 User.After.setAsIdentityConversion();
2920 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2921 User.After.setAllToTypes(ToType);
2922 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00002923 }
2924 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00002925 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002926 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00002927
John McCall5c32be02010-08-24 20:38:10 +00002928 // C++ [over.ics.user]p1:
2929 //
2930 // [...] If the user-defined conversion is specified by a
2931 // conversion function (12.3.2), the initial standard
2932 // conversion sequence converts the source type to the
2933 // implicit object parameter of the conversion function.
2934 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002935 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002936 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002937 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002938 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002939
John McCall5c32be02010-08-24 20:38:10 +00002940 // C++ [over.ics.user]p2:
2941 // The second standard conversion sequence converts the
2942 // result of the user-defined conversion to the target type
2943 // for the sequence. Since an implicit conversion sequence
2944 // is an initialization, the special rules for
2945 // initialization by user-defined conversion apply when
2946 // selecting the best user-defined conversion for a
2947 // user-defined conversion sequence (see 13.3.3 and
2948 // 13.3.3.1).
2949 User.After = Best->FinalConversion;
2950 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002951 }
David Blaikie8a40f702012-01-17 06:56:22 +00002952 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002953
John McCall5c32be02010-08-24 20:38:10 +00002954 case OR_No_Viable_Function:
2955 return OR_No_Viable_Function;
2956 case OR_Deleted:
2957 // No conversion here! We're done.
2958 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959
John McCall5c32be02010-08-24 20:38:10 +00002960 case OR_Ambiguous:
2961 return OR_Ambiguous;
2962 }
2963
David Blaikie8a40f702012-01-17 06:56:22 +00002964 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002965}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002966
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002967bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002968Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002969 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002970 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002972 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002973 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002974 if (OvResult == OR_Ambiguous)
2975 Diag(From->getSourceRange().getBegin(),
2976 diag::err_typecheck_ambiguous_condition)
2977 << From->getType() << ToType << From->getSourceRange();
2978 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2979 Diag(From->getSourceRange().getBegin(),
2980 diag::err_typecheck_nonviable_condition)
2981 << From->getType() << ToType << From->getSourceRange();
2982 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002983 return false;
John McCall5c32be02010-08-24 20:38:10 +00002984 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002986}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002987
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002988/// CompareImplicitConversionSequences - Compare two implicit
2989/// conversion sequences to determine whether one is better than the
2990/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002991static ImplicitConversionSequence::CompareKind
2992CompareImplicitConversionSequences(Sema &S,
2993 const ImplicitConversionSequence& ICS1,
2994 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002995{
2996 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2997 // conversion sequences (as defined in 13.3.3.1)
2998 // -- a standard conversion sequence (13.3.3.1.1) is a better
2999 // conversion sequence than a user-defined conversion sequence or
3000 // an ellipsis conversion sequence, and
3001 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3002 // conversion sequence than an ellipsis conversion sequence
3003 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003004 //
John McCall0d1da222010-01-12 00:44:57 +00003005 // C++0x [over.best.ics]p10:
3006 // For the purpose of ranking implicit conversion sequences as
3007 // described in 13.3.3.2, the ambiguous conversion sequence is
3008 // treated as a user-defined sequence that is indistinguishable
3009 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003010 if (ICS1.getKindRank() < ICS2.getKindRank())
3011 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003012 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003013 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003014
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003015 // The following checks require both conversion sequences to be of
3016 // the same kind.
3017 if (ICS1.getKind() != ICS2.getKind())
3018 return ImplicitConversionSequence::Indistinguishable;
3019
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003020 ImplicitConversionSequence::CompareKind Result =
3021 ImplicitConversionSequence::Indistinguishable;
3022
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003023 // Two implicit conversion sequences of the same form are
3024 // indistinguishable conversion sequences unless one of the
3025 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003026 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003027 Result = CompareStandardConversionSequences(S,
3028 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003029 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003030 // User-defined conversion sequence U1 is a better conversion
3031 // sequence than another user-defined conversion sequence U2 if
3032 // they contain the same user-defined conversion function or
3033 // constructor and if the second standard conversion sequence of
3034 // U1 is better than the second standard conversion sequence of
3035 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003036 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003037 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003038 Result = CompareStandardConversionSequences(S,
3039 ICS1.UserDefined.After,
3040 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003041 }
3042
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003043 // List-initialization sequence L1 is a better conversion sequence than
3044 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3045 // for some X and L2 does not.
3046 if (Result == ImplicitConversionSequence::Indistinguishable &&
3047 ICS1.isListInitializationSequence() &&
3048 ICS2.isListInitializationSequence()) {
3049 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
3050 }
3051
3052 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003053}
3054
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003055static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3056 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3057 Qualifiers Quals;
3058 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003061
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003062 return Context.hasSameUnqualifiedType(T1, T2);
3063}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003065// Per 13.3.3.2p3, compare the given standard conversion sequences to
3066// determine if one is a proper subset of the other.
3067static ImplicitConversionSequence::CompareKind
3068compareStandardConversionSubsets(ASTContext &Context,
3069 const StandardConversionSequence& SCS1,
3070 const StandardConversionSequence& SCS2) {
3071 ImplicitConversionSequence::CompareKind Result
3072 = ImplicitConversionSequence::Indistinguishable;
3073
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003075 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003076 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3077 return ImplicitConversionSequence::Better;
3078 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3079 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003080
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003081 if (SCS1.Second != SCS2.Second) {
3082 if (SCS1.Second == ICK_Identity)
3083 Result = ImplicitConversionSequence::Better;
3084 else if (SCS2.Second == ICK_Identity)
3085 Result = ImplicitConversionSequence::Worse;
3086 else
3087 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003088 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003089 return ImplicitConversionSequence::Indistinguishable;
3090
3091 if (SCS1.Third == SCS2.Third) {
3092 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3093 : ImplicitConversionSequence::Indistinguishable;
3094 }
3095
3096 if (SCS1.Third == ICK_Identity)
3097 return Result == ImplicitConversionSequence::Worse
3098 ? ImplicitConversionSequence::Indistinguishable
3099 : ImplicitConversionSequence::Better;
3100
3101 if (SCS2.Third == ICK_Identity)
3102 return Result == ImplicitConversionSequence::Better
3103 ? ImplicitConversionSequence::Indistinguishable
3104 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003105
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003106 return ImplicitConversionSequence::Indistinguishable;
3107}
3108
Douglas Gregore696ebb2011-01-26 14:52:12 +00003109/// \brief Determine whether one of the given reference bindings is better
3110/// than the other based on what kind of bindings they are.
3111static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3112 const StandardConversionSequence &SCS2) {
3113 // C++0x [over.ics.rank]p3b4:
3114 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3115 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003117 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003118 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003119 // reference*.
3120 //
3121 // FIXME: Rvalue references. We're going rogue with the above edits,
3122 // because the semantics in the current C++0x working paper (N3225 at the
3123 // time of this writing) break the standard definition of std::forward
3124 // and std::reference_wrapper when dealing with references to functions.
3125 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003126 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3127 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3128 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003129
Douglas Gregore696ebb2011-01-26 14:52:12 +00003130 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3131 SCS2.IsLvalueReference) ||
3132 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3133 !SCS2.IsLvalueReference);
3134}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003136/// CompareStandardConversionSequences - Compare two standard
3137/// conversion sequences to determine whether one is better than the
3138/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003139static ImplicitConversionSequence::CompareKind
3140CompareStandardConversionSequences(Sema &S,
3141 const StandardConversionSequence& SCS1,
3142 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003143{
3144 // Standard conversion sequence S1 is a better conversion sequence
3145 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3146
3147 // -- S1 is a proper subsequence of S2 (comparing the conversion
3148 // sequences in the canonical form defined by 13.3.3.1.1,
3149 // excluding any Lvalue Transformation; the identity conversion
3150 // sequence is considered to be a subsequence of any
3151 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003152 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003153 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003154 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003155
3156 // -- the rank of S1 is better than the rank of S2 (by the rules
3157 // defined below), or, if not that,
3158 ImplicitConversionRank Rank1 = SCS1.getRank();
3159 ImplicitConversionRank Rank2 = SCS2.getRank();
3160 if (Rank1 < Rank2)
3161 return ImplicitConversionSequence::Better;
3162 else if (Rank2 < Rank1)
3163 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003164
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003165 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3166 // are indistinguishable unless one of the following rules
3167 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003168
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003169 // A conversion that is not a conversion of a pointer, or
3170 // pointer to member, to bool is better than another conversion
3171 // that is such a conversion.
3172 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3173 return SCS2.isPointerConversionToBool()
3174 ? ImplicitConversionSequence::Better
3175 : ImplicitConversionSequence::Worse;
3176
Douglas Gregor5c407d92008-10-23 00:40:37 +00003177 // C++ [over.ics.rank]p4b2:
3178 //
3179 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003180 // conversion of B* to A* is better than conversion of B* to
3181 // void*, and conversion of A* to void* is better than conversion
3182 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003183 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003184 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003185 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003186 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003187 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3188 // Exactly one of the conversion sequences is a conversion to
3189 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003190 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3191 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003192 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3193 // Neither conversion sequence converts to a void pointer; compare
3194 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003195 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003196 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003197 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003198 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3199 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003200 // Both conversion sequences are conversions to void
3201 // pointers. Compare the source types to determine if there's an
3202 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003203 QualType FromType1 = SCS1.getFromType();
3204 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003205
3206 // Adjust the types we're converting from via the array-to-pointer
3207 // conversion, if we need to.
3208 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003209 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003210 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003211 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003212
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003213 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3214 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003215
John McCall5c32be02010-08-24 20:38:10 +00003216 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003217 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003218 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003219 return ImplicitConversionSequence::Worse;
3220
3221 // Objective-C++: If one interface is more specific than the
3222 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003223 const ObjCObjectPointerType* FromObjCPtr1
3224 = FromType1->getAs<ObjCObjectPointerType>();
3225 const ObjCObjectPointerType* FromObjCPtr2
3226 = FromType2->getAs<ObjCObjectPointerType>();
3227 if (FromObjCPtr1 && FromObjCPtr2) {
3228 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3229 FromObjCPtr2);
3230 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3231 FromObjCPtr1);
3232 if (AssignLeft != AssignRight) {
3233 return AssignLeft? ImplicitConversionSequence::Better
3234 : ImplicitConversionSequence::Worse;
3235 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003236 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003237 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003238
3239 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3240 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003241 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003242 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003243 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003244
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003245 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003246 // Check for a better reference binding based on the kind of bindings.
3247 if (isBetterReferenceBindingKind(SCS1, SCS2))
3248 return ImplicitConversionSequence::Better;
3249 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3250 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251
Sebastian Redlb28b4072009-03-22 23:49:27 +00003252 // C++ [over.ics.rank]p3b4:
3253 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3254 // which the references refer are the same type except for
3255 // top-level cv-qualifiers, and the type to which the reference
3256 // initialized by S2 refers is more cv-qualified than the type
3257 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003258 QualType T1 = SCS1.getToType(2);
3259 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003260 T1 = S.Context.getCanonicalType(T1);
3261 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003262 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003263 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3264 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003265 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003266 // Objective-C++ ARC: If the references refer to objects with different
3267 // lifetimes, prefer bindings that don't change lifetime.
3268 if (SCS1.ObjCLifetimeConversionBinding !=
3269 SCS2.ObjCLifetimeConversionBinding) {
3270 return SCS1.ObjCLifetimeConversionBinding
3271 ? ImplicitConversionSequence::Worse
3272 : ImplicitConversionSequence::Better;
3273 }
3274
Chandler Carruth8e543b32010-12-12 08:17:55 +00003275 // If the type is an array type, promote the element qualifiers to the
3276 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003277 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003278 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003279 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003280 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003281 if (T2.isMoreQualifiedThan(T1))
3282 return ImplicitConversionSequence::Better;
3283 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003284 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003285 }
3286 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003287
Francois Pichet08d2fa02011-09-18 21:37:37 +00003288 // In Microsoft mode, prefer an integral conversion to a
3289 // floating-to-integral conversion if the integral conversion
3290 // is between types of the same size.
3291 // For example:
3292 // void f(float);
3293 // void f(int);
3294 // int main {
3295 // long a;
3296 // f(a);
3297 // }
3298 // Here, MSVC will call f(int) instead of generating a compile error
3299 // as clang will do in standard mode.
3300 if (S.getLangOptions().MicrosoftMode &&
3301 SCS1.Second == ICK_Integral_Conversion &&
3302 SCS2.Second == ICK_Floating_Integral &&
3303 S.Context.getTypeSize(SCS1.getFromType()) ==
3304 S.Context.getTypeSize(SCS1.getToType(2)))
3305 return ImplicitConversionSequence::Better;
3306
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003307 return ImplicitConversionSequence::Indistinguishable;
3308}
3309
3310/// CompareQualificationConversions - Compares two standard conversion
3311/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003312/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3313ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003314CompareQualificationConversions(Sema &S,
3315 const StandardConversionSequence& SCS1,
3316 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003317 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003318 // -- S1 and S2 differ only in their qualification conversion and
3319 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3320 // cv-qualification signature of type T1 is a proper subset of
3321 // the cv-qualification signature of type T2, and S1 is not the
3322 // deprecated string literal array-to-pointer conversion (4.2).
3323 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3324 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3325 return ImplicitConversionSequence::Indistinguishable;
3326
3327 // FIXME: the example in the standard doesn't use a qualification
3328 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003329 QualType T1 = SCS1.getToType(2);
3330 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003331 T1 = S.Context.getCanonicalType(T1);
3332 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003333 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003334 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3335 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003336
3337 // If the types are the same, we won't learn anything by unwrapped
3338 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003339 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003340 return ImplicitConversionSequence::Indistinguishable;
3341
Chandler Carruth607f38e2009-12-29 07:16:59 +00003342 // If the type is an array type, promote the element qualifiers to the type
3343 // for comparison.
3344 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003345 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003346 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003347 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003348
Mike Stump11289f42009-09-09 15:08:12 +00003349 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003350 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003351
3352 // Objective-C++ ARC:
3353 // Prefer qualification conversions not involving a change in lifetime
3354 // to qualification conversions that do not change lifetime.
3355 if (SCS1.QualificationIncludesObjCLifetime !=
3356 SCS2.QualificationIncludesObjCLifetime) {
3357 Result = SCS1.QualificationIncludesObjCLifetime
3358 ? ImplicitConversionSequence::Worse
3359 : ImplicitConversionSequence::Better;
3360 }
3361
John McCall5c32be02010-08-24 20:38:10 +00003362 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003363 // Within each iteration of the loop, we check the qualifiers to
3364 // determine if this still looks like a qualification
3365 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003366 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003367 // until there are no more pointers or pointers-to-members left
3368 // to unwrap. This essentially mimics what
3369 // IsQualificationConversion does, but here we're checking for a
3370 // strict subset of qualifiers.
3371 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3372 // The qualifiers are the same, so this doesn't tell us anything
3373 // about how the sequences rank.
3374 ;
3375 else if (T2.isMoreQualifiedThan(T1)) {
3376 // T1 has fewer qualifiers, so it could be the better sequence.
3377 if (Result == ImplicitConversionSequence::Worse)
3378 // Neither has qualifiers that are a subset of the other's
3379 // qualifiers.
3380 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003381
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003382 Result = ImplicitConversionSequence::Better;
3383 } else if (T1.isMoreQualifiedThan(T2)) {
3384 // T2 has fewer qualifiers, so it could be the better sequence.
3385 if (Result == ImplicitConversionSequence::Better)
3386 // Neither has qualifiers that are a subset of the other's
3387 // qualifiers.
3388 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003389
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003390 Result = ImplicitConversionSequence::Worse;
3391 } else {
3392 // Qualifiers are disjoint.
3393 return ImplicitConversionSequence::Indistinguishable;
3394 }
3395
3396 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003397 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003398 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003399 }
3400
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003401 // Check that the winning standard conversion sequence isn't using
3402 // the deprecated string literal array to pointer conversion.
3403 switch (Result) {
3404 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003405 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003406 Result = ImplicitConversionSequence::Indistinguishable;
3407 break;
3408
3409 case ImplicitConversionSequence::Indistinguishable:
3410 break;
3411
3412 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003413 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003414 Result = ImplicitConversionSequence::Indistinguishable;
3415 break;
3416 }
3417
3418 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003419}
3420
Douglas Gregor5c407d92008-10-23 00:40:37 +00003421/// CompareDerivedToBaseConversions - Compares two standard conversion
3422/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003423/// various kinds of derived-to-base conversions (C++
3424/// [over.ics.rank]p4b3). As part of these checks, we also look at
3425/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003426ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003427CompareDerivedToBaseConversions(Sema &S,
3428 const StandardConversionSequence& SCS1,
3429 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003430 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003431 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003432 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003433 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003434
3435 // Adjust the types we're converting from via the array-to-pointer
3436 // conversion, if we need to.
3437 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003438 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003439 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003440 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003441
3442 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003443 FromType1 = S.Context.getCanonicalType(FromType1);
3444 ToType1 = S.Context.getCanonicalType(ToType1);
3445 FromType2 = S.Context.getCanonicalType(FromType2);
3446 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003447
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003448 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003449 //
3450 // If class B is derived directly or indirectly from class A and
3451 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003452 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003453 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003454 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003455 SCS2.Second == ICK_Pointer_Conversion &&
3456 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3457 FromType1->isPointerType() && FromType2->isPointerType() &&
3458 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003459 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003460 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003461 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003462 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003463 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003464 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003465 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003466 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003467
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003468 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003469 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003470 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003471 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003472 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003473 return ImplicitConversionSequence::Worse;
3474 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003475
3476 // -- conversion of B* to A* is better than conversion of C* to A*,
3477 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003478 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003479 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003480 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003481 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003482 }
3483 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3484 SCS2.Second == ICK_Pointer_Conversion) {
3485 const ObjCObjectPointerType *FromPtr1
3486 = FromType1->getAs<ObjCObjectPointerType>();
3487 const ObjCObjectPointerType *FromPtr2
3488 = FromType2->getAs<ObjCObjectPointerType>();
3489 const ObjCObjectPointerType *ToPtr1
3490 = ToType1->getAs<ObjCObjectPointerType>();
3491 const ObjCObjectPointerType *ToPtr2
3492 = ToType2->getAs<ObjCObjectPointerType>();
3493
3494 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3495 // Apply the same conversion ranking rules for Objective-C pointer types
3496 // that we do for C++ pointers to class types. However, we employ the
3497 // Objective-C pseudo-subtyping relationship used for assignment of
3498 // Objective-C pointer types.
3499 bool FromAssignLeft
3500 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3501 bool FromAssignRight
3502 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3503 bool ToAssignLeft
3504 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3505 bool ToAssignRight
3506 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3507
3508 // A conversion to an a non-id object pointer type or qualified 'id'
3509 // type is better than a conversion to 'id'.
3510 if (ToPtr1->isObjCIdType() &&
3511 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3512 return ImplicitConversionSequence::Worse;
3513 if (ToPtr2->isObjCIdType() &&
3514 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3515 return ImplicitConversionSequence::Better;
3516
3517 // A conversion to a non-id object pointer type is better than a
3518 // conversion to a qualified 'id' type
3519 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3520 return ImplicitConversionSequence::Worse;
3521 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3522 return ImplicitConversionSequence::Better;
3523
3524 // A conversion to an a non-Class object pointer type or qualified 'Class'
3525 // type is better than a conversion to 'Class'.
3526 if (ToPtr1->isObjCClassType() &&
3527 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3528 return ImplicitConversionSequence::Worse;
3529 if (ToPtr2->isObjCClassType() &&
3530 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3531 return ImplicitConversionSequence::Better;
3532
3533 // A conversion to a non-Class object pointer type is better than a
3534 // conversion to a qualified 'Class' type.
3535 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3536 return ImplicitConversionSequence::Worse;
3537 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3538 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003539
Douglas Gregor058d3de2011-01-31 18:51:41 +00003540 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3541 if (S.Context.hasSameType(FromType1, FromType2) &&
3542 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3543 (ToAssignLeft != ToAssignRight))
3544 return ToAssignLeft? ImplicitConversionSequence::Worse
3545 : ImplicitConversionSequence::Better;
3546
3547 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3548 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3549 (FromAssignLeft != FromAssignRight))
3550 return FromAssignLeft? ImplicitConversionSequence::Better
3551 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003552 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003553 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003554
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003555 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003556 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3557 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3558 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003560 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003562 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003564 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003566 ToType2->getAs<MemberPointerType>();
3567 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3568 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3569 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3570 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3571 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3572 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3573 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3574 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003575 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003576 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003577 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003578 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003579 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003580 return ImplicitConversionSequence::Better;
3581 }
3582 // conversion of B::* to C::* is better than conversion of A::* to C::*
3583 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003584 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003585 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003586 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003587 return ImplicitConversionSequence::Worse;
3588 }
3589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590
Douglas Gregor5ab11652010-04-17 22:01:05 +00003591 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003592 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003593 // -- binding of an expression of type C to a reference of type
3594 // B& is better than binding an expression of type C to a
3595 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003596 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3597 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3598 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003599 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003600 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003601 return ImplicitConversionSequence::Worse;
3602 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003603
Douglas Gregor2fe98832008-11-03 19:09:14 +00003604 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003605 // -- binding of an expression of type B to a reference of type
3606 // A& is better than binding an expression of type C to a
3607 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003608 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3609 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3610 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003611 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003612 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003613 return ImplicitConversionSequence::Worse;
3614 }
3615 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003616
Douglas Gregor5c407d92008-10-23 00:40:37 +00003617 return ImplicitConversionSequence::Indistinguishable;
3618}
3619
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003620/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3621/// determine whether they are reference-related,
3622/// reference-compatible, reference-compatible with added
3623/// qualification, or incompatible, for use in C++ initialization by
3624/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3625/// type, and the first type (T1) is the pointee type of the reference
3626/// type being initialized.
3627Sema::ReferenceCompareResult
3628Sema::CompareReferenceRelationship(SourceLocation Loc,
3629 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003630 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003631 bool &ObjCConversion,
3632 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003633 assert(!OrigT1->isReferenceType() &&
3634 "T1 must be the pointee type of the reference type");
3635 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3636
3637 QualType T1 = Context.getCanonicalType(OrigT1);
3638 QualType T2 = Context.getCanonicalType(OrigT2);
3639 Qualifiers T1Quals, T2Quals;
3640 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3641 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3642
3643 // C++ [dcl.init.ref]p4:
3644 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3645 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3646 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003647 DerivedToBase = false;
3648 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003649 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003650 if (UnqualT1 == UnqualT2) {
3651 // Nothing to do.
3652 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003653 IsDerivedFrom(UnqualT2, UnqualT1))
3654 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003655 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3656 UnqualT2->isObjCObjectOrInterfaceType() &&
3657 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3658 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003659 else
3660 return Ref_Incompatible;
3661
3662 // At this point, we know that T1 and T2 are reference-related (at
3663 // least).
3664
3665 // If the type is an array type, promote the element qualifiers to the type
3666 // for comparison.
3667 if (isa<ArrayType>(T1) && T1Quals)
3668 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3669 if (isa<ArrayType>(T2) && T2Quals)
3670 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3671
3672 // C++ [dcl.init.ref]p4:
3673 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3674 // reference-related to T2 and cv1 is the same cv-qualification
3675 // as, or greater cv-qualification than, cv2. For purposes of
3676 // overload resolution, cases for which cv1 is greater
3677 // cv-qualification than cv2 are identified as
3678 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003679 //
3680 // Note that we also require equivalence of Objective-C GC and address-space
3681 // qualifiers when performing these computations, so that e.g., an int in
3682 // address space 1 is not reference-compatible with an int in address
3683 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003684 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3685 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3686 T1Quals.removeObjCLifetime();
3687 T2Quals.removeObjCLifetime();
3688 ObjCLifetimeConversion = true;
3689 }
3690
Douglas Gregord517d552011-04-28 17:56:11 +00003691 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003692 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003693 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003694 return Ref_Compatible_With_Added_Qualification;
3695 else
3696 return Ref_Related;
3697}
3698
Douglas Gregor836a7e82010-08-11 02:15:33 +00003699/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003700/// with DeclType. Return true if something definite is found.
3701static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003702FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3703 QualType DeclType, SourceLocation DeclLoc,
3704 Expr *Init, QualType T2, bool AllowRvalues,
3705 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003706 assert(T2->isRecordType() && "Can only find conversions of record types.");
3707 CXXRecordDecl *T2RecordDecl
3708 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3709
3710 OverloadCandidateSet CandidateSet(DeclLoc);
3711 const UnresolvedSetImpl *Conversions
3712 = T2RecordDecl->getVisibleConversionFunctions();
3713 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3714 E = Conversions->end(); I != E; ++I) {
3715 NamedDecl *D = *I;
3716 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3717 if (isa<UsingShadowDecl>(D))
3718 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3719
3720 FunctionTemplateDecl *ConvTemplate
3721 = dyn_cast<FunctionTemplateDecl>(D);
3722 CXXConversionDecl *Conv;
3723 if (ConvTemplate)
3724 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3725 else
3726 Conv = cast<CXXConversionDecl>(D);
3727
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003728 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003729 // explicit conversions, skip it.
3730 if (!AllowExplicit && Conv->isExplicit())
3731 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732
Douglas Gregor836a7e82010-08-11 02:15:33 +00003733 if (AllowRvalues) {
3734 bool DerivedToBase = false;
3735 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003736 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003737
3738 // If we are initializing an rvalue reference, don't permit conversion
3739 // functions that return lvalues.
3740 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3741 const ReferenceType *RefType
3742 = Conv->getConversionType()->getAs<LValueReferenceType>();
3743 if (RefType && !RefType->getPointeeType()->isFunctionType())
3744 continue;
3745 }
3746
Douglas Gregor836a7e82010-08-11 02:15:33 +00003747 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003748 S.CompareReferenceRelationship(
3749 DeclLoc,
3750 Conv->getConversionType().getNonReferenceType()
3751 .getUnqualifiedType(),
3752 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003753 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003754 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003755 continue;
3756 } else {
3757 // If the conversion function doesn't return a reference type,
3758 // it can't be considered for this conversion. An rvalue reference
3759 // is only acceptable if its referencee is a function type.
3760
3761 const ReferenceType *RefType =
3762 Conv->getConversionType()->getAs<ReferenceType>();
3763 if (!RefType ||
3764 (!RefType->isLValueReferenceType() &&
3765 !RefType->getPointeeType()->isFunctionType()))
3766 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768
Douglas Gregor836a7e82010-08-11 02:15:33 +00003769 if (ConvTemplate)
3770 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003771 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003772 else
3773 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003774 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003775 }
3776
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003777 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3778
Sebastian Redld92badf2010-06-30 18:13:39 +00003779 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003780 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003781 case OR_Success:
3782 // C++ [over.ics.ref]p1:
3783 //
3784 // [...] If the parameter binds directly to the result of
3785 // applying a conversion function to the argument
3786 // expression, the implicit conversion sequence is a
3787 // user-defined conversion sequence (13.3.3.1.2), with the
3788 // second standard conversion sequence either an identity
3789 // conversion or, if the conversion function returns an
3790 // entity of a type that is a derived class of the parameter
3791 // type, a derived-to-base Conversion.
3792 if (!Best->FinalConversion.DirectBinding)
3793 return false;
3794
Chandler Carruth30141632011-02-25 19:41:05 +00003795 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003796 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003797 ICS.setUserDefined();
3798 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3799 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003800 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003801 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003802 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003803 ICS.UserDefined.EllipsisConversion = false;
3804 assert(ICS.UserDefined.After.ReferenceBinding &&
3805 ICS.UserDefined.After.DirectBinding &&
3806 "Expected a direct reference binding!");
3807 return true;
3808
3809 case OR_Ambiguous:
3810 ICS.setAmbiguous();
3811 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3812 Cand != CandidateSet.end(); ++Cand)
3813 if (Cand->Viable)
3814 ICS.Ambiguous.addConversion(Cand->Function);
3815 return true;
3816
3817 case OR_No_Viable_Function:
3818 case OR_Deleted:
3819 // There was no suitable conversion, or we found a deleted
3820 // conversion; continue with other checks.
3821 return false;
3822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823
David Blaikie8a40f702012-01-17 06:56:22 +00003824 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00003825}
3826
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003827/// \brief Compute an implicit conversion sequence for reference
3828/// initialization.
3829static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003830TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003831 SourceLocation DeclLoc,
3832 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003833 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003834 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3835
3836 // Most paths end in a failed conversion.
3837 ImplicitConversionSequence ICS;
3838 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3839
3840 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3841 QualType T2 = Init->getType();
3842
3843 // If the initializer is the address of an overloaded function, try
3844 // to resolve the overloaded function. If all goes well, T2 is the
3845 // type of the resulting function.
3846 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3847 DeclAccessPair Found;
3848 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3849 false, Found))
3850 T2 = Fn->getType();
3851 }
3852
3853 // Compute some basic properties of the types and the initializer.
3854 bool isRValRef = DeclType->isRValueReferenceType();
3855 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003856 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003857 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003858 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003859 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003860 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003861 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003862
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003863
Sebastian Redld92badf2010-06-30 18:13:39 +00003864 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003865 // A reference to type "cv1 T1" is initialized by an expression
3866 // of type "cv2 T2" as follows:
3867
Sebastian Redld92badf2010-06-30 18:13:39 +00003868 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003869 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003870 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3871 // reference-compatible with "cv2 T2," or
3872 //
3873 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3874 if (InitCategory.isLValue() &&
3875 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003876 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003877 // When a parameter of reference type binds directly (8.5.3)
3878 // to an argument expression, the implicit conversion sequence
3879 // is the identity conversion, unless the argument expression
3880 // has a type that is a derived class of the parameter type,
3881 // in which case the implicit conversion sequence is a
3882 // derived-to-base Conversion (13.3.3.1).
3883 ICS.setStandard();
3884 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003885 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3886 : ObjCConversion? ICK_Compatible_Conversion
3887 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003888 ICS.Standard.Third = ICK_Identity;
3889 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3890 ICS.Standard.setToType(0, T2);
3891 ICS.Standard.setToType(1, T1);
3892 ICS.Standard.setToType(2, T1);
3893 ICS.Standard.ReferenceBinding = true;
3894 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003895 ICS.Standard.IsLvalueReference = !isRValRef;
3896 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3897 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003898 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003899 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003900 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003901
Sebastian Redld92badf2010-06-30 18:13:39 +00003902 // Nothing more to do: the inaccessibility/ambiguity check for
3903 // derived-to-base conversions is suppressed when we're
3904 // computing the implicit conversion sequence (C++
3905 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003906 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003907 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003908
Sebastian Redld92badf2010-06-30 18:13:39 +00003909 // -- has a class type (i.e., T2 is a class type), where T1 is
3910 // not reference-related to T2, and can be implicitly
3911 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3912 // is reference-compatible with "cv3 T3" 92) (this
3913 // conversion is selected by enumerating the applicable
3914 // conversion functions (13.3.1.6) and choosing the best
3915 // one through overload resolution (13.3)),
3916 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003918 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003919 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3920 Init, T2, /*AllowRvalues=*/false,
3921 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003922 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003923 }
3924 }
3925
Sebastian Redld92badf2010-06-30 18:13:39 +00003926 // -- Otherwise, the reference shall be an lvalue reference to a
3927 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003928 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003930 // We actually handle one oddity of C++ [over.ics.ref] at this
3931 // point, which is that, due to p2 (which short-circuits reference
3932 // binding by only attempting a simple conversion for non-direct
3933 // bindings) and p3's strange wording, we allow a const volatile
3934 // reference to bind to an rvalue. Hence the check for the presence
3935 // of "const" rather than checking for "const" being the only
3936 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003937 // This is also the point where rvalue references and lvalue inits no longer
3938 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003939 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003940 return ICS;
3941
Douglas Gregorf143cd52011-01-24 16:14:37 +00003942 // -- If the initializer expression
3943 //
3944 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003945 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003946 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3947 (InitCategory.isXValue() ||
3948 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3949 (InitCategory.isLValue() && T2->isFunctionType()))) {
3950 ICS.setStandard();
3951 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003953 : ObjCConversion? ICK_Compatible_Conversion
3954 : ICK_Identity;
3955 ICS.Standard.Third = ICK_Identity;
3956 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3957 ICS.Standard.setToType(0, T2);
3958 ICS.Standard.setToType(1, T1);
3959 ICS.Standard.setToType(2, T1);
3960 ICS.Standard.ReferenceBinding = true;
3961 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3962 // binding unless we're binding to a class prvalue.
3963 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3964 // allow the use of rvalue references in C++98/03 for the benefit of
3965 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966 ICS.Standard.DirectBinding =
3967 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003968 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003969 ICS.Standard.IsLvalueReference = !isRValRef;
3970 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003972 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003973 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003974 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003975 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977
Douglas Gregorf143cd52011-01-24 16:14:37 +00003978 // -- has a class type (i.e., T2 is a class type), where T1 is not
3979 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980 // an xvalue, class prvalue, or function lvalue of type
3981 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003982 // "cv3 T3",
3983 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003985 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003987 // class subobject).
3988 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003990 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3991 Init, T2, /*AllowRvalues=*/true,
3992 AllowExplicit)) {
3993 // In the second case, if the reference is an rvalue reference
3994 // and the second standard conversion sequence of the
3995 // user-defined conversion sequence includes an lvalue-to-rvalue
3996 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003998 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3999 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4000
Douglas Gregor95273c32011-01-21 16:36:05 +00004001 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004004 // -- Otherwise, a temporary of type "cv1 T1" is created and
4005 // initialized from the initializer expression using the
4006 // rules for a non-reference copy initialization (8.5). The
4007 // reference is then bound to the temporary. If T1 is
4008 // reference-related to T2, cv1 must be the same
4009 // cv-qualification as, or greater cv-qualification than,
4010 // cv2; otherwise, the program is ill-formed.
4011 if (RefRelationship == Sema::Ref_Related) {
4012 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4013 // we would be reference-compatible or reference-compatible with
4014 // added qualification. But that wasn't the case, so the reference
4015 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004016 //
4017 // Note that we only want to check address spaces and cvr-qualifiers here.
4018 // ObjC GC and lifetime qualifiers aren't important.
4019 Qualifiers T1Quals = T1.getQualifiers();
4020 Qualifiers T2Quals = T2.getQualifiers();
4021 T1Quals.removeObjCGCAttr();
4022 T1Quals.removeObjCLifetime();
4023 T2Quals.removeObjCGCAttr();
4024 T2Quals.removeObjCLifetime();
4025 if (!T1Quals.compatiblyIncludes(T2Quals))
4026 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004027 }
4028
4029 // If at least one of the types is a class type, the types are not
4030 // related, and we aren't allowed any user conversions, the
4031 // reference binding fails. This case is important for breaking
4032 // recursion, since TryImplicitConversion below will attempt to
4033 // create a temporary through the use of a copy constructor.
4034 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4035 (T1->isRecordType() || T2->isRecordType()))
4036 return ICS;
4037
Douglas Gregorcba72b12011-01-21 05:18:22 +00004038 // If T1 is reference-related to T2 and the reference is an rvalue
4039 // reference, the initializer expression shall not be an lvalue.
4040 if (RefRelationship >= Sema::Ref_Related &&
4041 isRValRef && Init->Classify(S.Context).isLValue())
4042 return ICS;
4043
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004044 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004045 // When a parameter of reference type is not bound directly to
4046 // an argument expression, the conversion sequence is the one
4047 // required to convert the argument expression to the
4048 // underlying type of the reference according to
4049 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4050 // to copy-initializing a temporary of the underlying type with
4051 // the argument expression. Any difference in top-level
4052 // cv-qualification is subsumed by the initialization itself
4053 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004054 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4055 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004056 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004057 /*CStyle=*/false,
4058 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004059
4060 // Of course, that's still a reference binding.
4061 if (ICS.isStandard()) {
4062 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004063 ICS.Standard.IsLvalueReference = !isRValRef;
4064 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4065 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004066 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004067 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004068 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004069 // Don't allow rvalue references to bind to lvalues.
4070 if (DeclType->isRValueReferenceType()) {
4071 if (const ReferenceType *RefType
4072 = ICS.UserDefined.ConversionFunction->getResultType()
4073 ->getAs<LValueReferenceType>()) {
4074 if (!RefType->getPointeeType()->isFunctionType()) {
4075 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4076 DeclType);
4077 return ICS;
4078 }
4079 }
4080 }
4081
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004082 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004083 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4084 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4085 ICS.UserDefined.After.BindsToRvalue = true;
4086 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4087 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004088 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004089
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004090 return ICS;
4091}
4092
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004093static ImplicitConversionSequence
4094TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4095 bool SuppressUserConversions,
4096 bool InOverloadResolution,
4097 bool AllowObjCWritebackConversion);
4098
4099/// TryListConversion - Try to copy-initialize a value of type ToType from the
4100/// initializer list From.
4101static ImplicitConversionSequence
4102TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4103 bool SuppressUserConversions,
4104 bool InOverloadResolution,
4105 bool AllowObjCWritebackConversion) {
4106 // C++11 [over.ics.list]p1:
4107 // When an argument is an initializer list, it is not an expression and
4108 // special rules apply for converting it to a parameter type.
4109
4110 ImplicitConversionSequence Result;
4111 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004112 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004113
Sebastian Redl09edce02012-01-23 22:09:39 +00004114 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004115 // initialized from init lists.
4116 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4117 return Result;
4118
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004119 // C++11 [over.ics.list]p2:
4120 // If the parameter type is std::initializer_list<X> or "array of X" and
4121 // all the elements can be implicitly converted to X, the implicit
4122 // conversion sequence is the worst conversion necessary to convert an
4123 // element of the list to X.
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004124 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004125 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004126 X = S.Context.getBaseElementType(ToType);
4127 else
4128 (void)S.isStdInitializerList(ToType, &X);
4129 if (!X.isNull()) {
4130 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4131 Expr *Init = From->getInit(i);
4132 ImplicitConversionSequence ICS =
4133 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4134 InOverloadResolution,
4135 AllowObjCWritebackConversion);
4136 // If a single element isn't convertible, fail.
4137 if (ICS.isBad()) {
4138 Result = ICS;
4139 break;
4140 }
4141 // Otherwise, look for the worst conversion.
4142 if (Result.isBad() ||
4143 CompareImplicitConversionSequences(S, ICS, Result) ==
4144 ImplicitConversionSequence::Worse)
4145 Result = ICS;
4146 }
4147 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004148 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004149 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004150
4151 // C++11 [over.ics.list]p3:
4152 // Otherwise, if the parameter is a non-aggregate class X and overload
4153 // resolution chooses a single best constructor [...] the implicit
4154 // conversion sequence is a user-defined conversion sequence. If multiple
4155 // constructors are viable but none is better than the others, the
4156 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004157 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4158 // This function can deal with initializer lists.
4159 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4160 /*AllowExplicit=*/false,
4161 InOverloadResolution, /*CStyle=*/false,
4162 AllowObjCWritebackConversion);
4163 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004164 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004165 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004166
4167 // C++11 [over.ics.list]p4:
4168 // Otherwise, if the parameter has an aggregate type which can be
4169 // initialized from the initializer list [...] the implicit conversion
4170 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004171 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004172 // Type is an aggregate, argument is an init list. At this point it comes
4173 // down to checking whether the initialization works.
4174 // FIXME: Find out whether this parameter is consumed or not.
4175 InitializedEntity Entity =
4176 InitializedEntity::InitializeParameter(S.Context, ToType,
4177 /*Consumed=*/false);
4178 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4179 Result.setUserDefined();
4180 Result.UserDefined.Before.setAsIdentityConversion();
4181 // Initializer lists don't have a type.
4182 Result.UserDefined.Before.setFromType(QualType());
4183 Result.UserDefined.Before.setAllToTypes(QualType());
4184
4185 Result.UserDefined.After.setAsIdentityConversion();
4186 Result.UserDefined.After.setFromType(ToType);
4187 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004188 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004189 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004190 return Result;
4191 }
4192
4193 // C++11 [over.ics.list]p5:
4194 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004195 if (ToType->isReferenceType()) {
4196 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4197 // mention initializer lists in any way. So we go by what list-
4198 // initialization would do and try to extrapolate from that.
4199
4200 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4201
4202 // If the initializer list has a single element that is reference-related
4203 // to the parameter type, we initialize the reference from that.
4204 if (From->getNumInits() == 1) {
4205 Expr *Init = From->getInit(0);
4206
4207 QualType T2 = Init->getType();
4208
4209 // If the initializer is the address of an overloaded function, try
4210 // to resolve the overloaded function. If all goes well, T2 is the
4211 // type of the resulting function.
4212 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4213 DeclAccessPair Found;
4214 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4215 Init, ToType, false, Found))
4216 T2 = Fn->getType();
4217 }
4218
4219 // Compute some basic properties of the types and the initializer.
4220 bool dummy1 = false;
4221 bool dummy2 = false;
4222 bool dummy3 = false;
4223 Sema::ReferenceCompareResult RefRelationship
4224 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4225 dummy2, dummy3);
4226
4227 if (RefRelationship >= Sema::Ref_Related)
4228 return TryReferenceInit(S, Init, ToType,
4229 /*FIXME:*/From->getLocStart(),
4230 SuppressUserConversions,
4231 /*AllowExplicit=*/false);
4232 }
4233
4234 // Otherwise, we bind the reference to a temporary created from the
4235 // initializer list.
4236 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4237 InOverloadResolution,
4238 AllowObjCWritebackConversion);
4239 if (Result.isFailure())
4240 return Result;
4241 assert(!Result.isEllipsis() &&
4242 "Sub-initialization cannot result in ellipsis conversion.");
4243
4244 // Can we even bind to a temporary?
4245 if (ToType->isRValueReferenceType() ||
4246 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4247 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4248 Result.UserDefined.After;
4249 SCS.ReferenceBinding = true;
4250 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4251 SCS.BindsToRvalue = true;
4252 SCS.BindsToFunctionLvalue = false;
4253 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4254 SCS.ObjCLifetimeConversionBinding = false;
4255 } else
4256 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4257 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004258 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004259 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004260
4261 // C++11 [over.ics.list]p6:
4262 // Otherwise, if the parameter type is not a class:
4263 if (!ToType->isRecordType()) {
4264 // - if the initializer list has one element, the implicit conversion
4265 // sequence is the one required to convert the element to the
4266 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004267 unsigned NumInits = From->getNumInits();
4268 if (NumInits == 1)
4269 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4270 SuppressUserConversions,
4271 InOverloadResolution,
4272 AllowObjCWritebackConversion);
4273 // - if the initializer list has no elements, the implicit conversion
4274 // sequence is the identity conversion.
4275 else if (NumInits == 0) {
4276 Result.setStandard();
4277 Result.Standard.setAsIdentityConversion();
4278 }
4279 return Result;
4280 }
4281
4282 // C++11 [over.ics.list]p7:
4283 // In all cases other than those enumerated above, no conversion is possible
4284 return Result;
4285}
4286
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004287/// TryCopyInitialization - Try to copy-initialize a value of type
4288/// ToType from the expression From. Return the implicit conversion
4289/// sequence required to pass this argument, which may be a bad
4290/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004291/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004292/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004293static ImplicitConversionSequence
4294TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004296 bool InOverloadResolution,
4297 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004298 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4299 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4300 InOverloadResolution,AllowObjCWritebackConversion);
4301
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004302 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004303 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004304 /*FIXME:*/From->getLocStart(),
4305 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004306 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004307
John McCall5c32be02010-08-24 20:38:10 +00004308 return TryImplicitConversion(S, From, ToType,
4309 SuppressUserConversions,
4310 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004311 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004312 /*CStyle=*/false,
4313 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004314}
4315
Anna Zaks1b068122011-07-28 19:46:48 +00004316static bool TryCopyInitialization(const CanQualType FromQTy,
4317 const CanQualType ToQTy,
4318 Sema &S,
4319 SourceLocation Loc,
4320 ExprValueKind FromVK) {
4321 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4322 ImplicitConversionSequence ICS =
4323 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4324
4325 return !ICS.isBad();
4326}
4327
Douglas Gregor436424c2008-11-18 23:14:02 +00004328/// TryObjectArgumentInitialization - Try to initialize the object
4329/// parameter of the given member function (@c Method) from the
4330/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004331static ImplicitConversionSequence
4332TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004333 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004334 CXXMethodDecl *Method,
4335 CXXRecordDecl *ActingContext) {
4336 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004337 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4338 // const volatile object.
4339 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4340 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004341 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004342
4343 // Set up the conversion sequence as a "bad" conversion, to allow us
4344 // to exit early.
4345 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004346
4347 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004348 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004349 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004350 FromType = PT->getPointeeType();
4351
Douglas Gregor02824322011-01-26 19:30:28 +00004352 // When we had a pointer, it's implicitly dereferenced, so we
4353 // better have an lvalue.
4354 assert(FromClassification.isLValue());
4355 }
4356
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004357 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004358
Douglas Gregor02824322011-01-26 19:30:28 +00004359 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004361 // parameter is
4362 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004363 // - "lvalue reference to cv X" for functions declared without a
4364 // ref-qualifier or with the & ref-qualifier
4365 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004366 // ref-qualifier
4367 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004369 // cv-qualification on the member function declaration.
4370 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004372 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004373 // (C++ [over.match.funcs]p5). We perform a simplified version of
4374 // reference binding here, that allows class rvalues to bind to
4375 // non-constant references.
4376
Douglas Gregor02824322011-01-26 19:30:28 +00004377 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004378 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004380 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004381 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004382 ICS.setBad(BadConversionSequence::bad_qualifiers,
4383 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004384 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004385 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004386
4387 // Check that we have either the same type or a derived type. It
4388 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004389 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004390 ImplicitConversionKind SecondKind;
4391 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4392 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004393 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004394 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004395 else {
John McCall65eb8792010-02-25 01:37:24 +00004396 ICS.setBad(BadConversionSequence::unrelated_class,
4397 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004398 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004399 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004400
Douglas Gregor02824322011-01-26 19:30:28 +00004401 // Check the ref-qualifier.
4402 switch (Method->getRefQualifier()) {
4403 case RQ_None:
4404 // Do nothing; we don't care about lvalueness or rvalueness.
4405 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
Douglas Gregor02824322011-01-26 19:30:28 +00004407 case RQ_LValue:
4408 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4409 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004411 ImplicitParamType);
4412 return ICS;
4413 }
4414 break;
4415
4416 case RQ_RValue:
4417 if (!FromClassification.isRValue()) {
4418 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004420 ImplicitParamType);
4421 return ICS;
4422 }
4423 break;
4424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Douglas Gregor436424c2008-11-18 23:14:02 +00004426 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004427 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004428 ICS.Standard.setAsIdentityConversion();
4429 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004430 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004431 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004432 ICS.Standard.ReferenceBinding = true;
4433 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004435 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004436 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4437 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4438 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004439 return ICS;
4440}
4441
4442/// PerformObjectArgumentInitialization - Perform initialization of
4443/// the implicit object parameter for the given Method with the given
4444/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004445ExprResult
4446Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004448 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004449 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004450 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004451 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004452 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004453
Douglas Gregor02824322011-01-26 19:30:28 +00004454 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004455 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004456 FromRecordType = PT->getPointeeType();
4457 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004458 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004459 } else {
4460 FromRecordType = From->getType();
4461 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004462 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004463 }
4464
John McCall6e9f8f62009-12-03 04:06:58 +00004465 // Note that we always use the true parent context when performing
4466 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004467 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004468 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4469 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004470 if (ICS.isBad()) {
4471 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4472 Qualifiers FromQs = FromRecordType.getQualifiers();
4473 Qualifiers ToQs = DestType.getQualifiers();
4474 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4475 if (CVR) {
4476 Diag(From->getSourceRange().getBegin(),
4477 diag::err_member_function_call_bad_cvr)
4478 << Method->getDeclName() << FromRecordType << (CVR - 1)
4479 << From->getSourceRange();
4480 Diag(Method->getLocation(), diag::note_previous_decl)
4481 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004482 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004483 }
4484 }
4485
Douglas Gregor436424c2008-11-18 23:14:02 +00004486 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004487 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004488 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004489 }
Mike Stump11289f42009-09-09 15:08:12 +00004490
John Wiegley01296292011-04-08 18:41:53 +00004491 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4492 ExprResult FromRes =
4493 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4494 if (FromRes.isInvalid())
4495 return ExprError();
4496 From = FromRes.take();
4497 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004498
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004499 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004500 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004501 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004502 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004503}
4504
Douglas Gregor5fb53972009-01-14 15:45:31 +00004505/// TryContextuallyConvertToBool - Attempt to contextually convert the
4506/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004507static ImplicitConversionSequence
4508TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004509 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004510 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004511 // FIXME: Are these flags correct?
4512 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004513 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004514 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004515 /*CStyle=*/false,
4516 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004517}
4518
4519/// PerformContextuallyConvertToBool - Perform a contextual conversion
4520/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004521ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004522 if (checkPlaceholderForOverload(*this, From))
4523 return ExprError();
4524
John McCall5c32be02010-08-24 20:38:10 +00004525 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004526 if (!ICS.isBad())
4527 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528
Fariborz Jahanian76197412009-11-18 18:26:29 +00004529 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004530 return Diag(From->getSourceRange().getBegin(),
4531 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004532 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004533 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004534}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535
Richard Smithf8379a02012-01-18 23:55:52 +00004536/// Check that the specified conversion is permitted in a converted constant
4537/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4538/// is acceptable.
4539static bool CheckConvertedConstantConversions(Sema &S,
4540 StandardConversionSequence &SCS) {
4541 // Since we know that the target type is an integral or unscoped enumeration
4542 // type, most conversion kinds are impossible. All possible First and Third
4543 // conversions are fine.
4544 switch (SCS.Second) {
4545 case ICK_Identity:
4546 case ICK_Integral_Promotion:
4547 case ICK_Integral_Conversion:
4548 return true;
4549
4550 case ICK_Boolean_Conversion:
4551 // Conversion from an integral or unscoped enumeration type to bool is
4552 // classified as ICK_Boolean_Conversion, but it's also an integral
4553 // conversion, so it's permitted in a converted constant expression.
4554 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4555 SCS.getToType(2)->isBooleanType();
4556
4557 case ICK_Floating_Integral:
4558 case ICK_Complex_Real:
4559 return false;
4560
4561 case ICK_Lvalue_To_Rvalue:
4562 case ICK_Array_To_Pointer:
4563 case ICK_Function_To_Pointer:
4564 case ICK_NoReturn_Adjustment:
4565 case ICK_Qualification:
4566 case ICK_Compatible_Conversion:
4567 case ICK_Vector_Conversion:
4568 case ICK_Vector_Splat:
4569 case ICK_Derived_To_Base:
4570 case ICK_Pointer_Conversion:
4571 case ICK_Pointer_Member:
4572 case ICK_Block_Pointer_Conversion:
4573 case ICK_Writeback_Conversion:
4574 case ICK_Floating_Promotion:
4575 case ICK_Complex_Promotion:
4576 case ICK_Complex_Conversion:
4577 case ICK_Floating_Conversion:
4578 case ICK_TransparentUnionConversion:
4579 llvm_unreachable("unexpected second conversion kind");
4580
4581 case ICK_Num_Conversion_Kinds:
4582 break;
4583 }
4584
4585 llvm_unreachable("unknown conversion kind");
4586}
4587
4588/// CheckConvertedConstantExpression - Check that the expression From is a
4589/// converted constant expression of type T, perform the conversion and produce
4590/// the converted expression, per C++11 [expr.const]p3.
4591ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4592 llvm::APSInt &Value,
4593 CCEKind CCE) {
4594 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4595 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4596
4597 if (checkPlaceholderForOverload(*this, From))
4598 return ExprError();
4599
4600 // C++11 [expr.const]p3 with proposed wording fixes:
4601 // A converted constant expression of type T is a core constant expression,
4602 // implicitly converted to a prvalue of type T, where the converted
4603 // expression is a literal constant expression and the implicit conversion
4604 // sequence contains only user-defined conversions, lvalue-to-rvalue
4605 // conversions, integral promotions, and integral conversions other than
4606 // narrowing conversions.
4607 ImplicitConversionSequence ICS =
4608 TryImplicitConversion(From, T,
4609 /*SuppressUserConversions=*/false,
4610 /*AllowExplicit=*/false,
4611 /*InOverloadResolution=*/false,
4612 /*CStyle=*/false,
4613 /*AllowObjcWritebackConversion=*/false);
4614 StandardConversionSequence *SCS = 0;
4615 switch (ICS.getKind()) {
4616 case ImplicitConversionSequence::StandardConversion:
4617 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4618 return Diag(From->getSourceRange().getBegin(),
4619 diag::err_typecheck_converted_constant_expression_disallowed)
4620 << From->getType() << From->getSourceRange() << T;
4621 SCS = &ICS.Standard;
4622 break;
4623 case ImplicitConversionSequence::UserDefinedConversion:
4624 // We are converting from class type to an integral or enumeration type, so
4625 // the Before sequence must be trivial.
4626 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4627 return Diag(From->getSourceRange().getBegin(),
4628 diag::err_typecheck_converted_constant_expression_disallowed)
4629 << From->getType() << From->getSourceRange() << T;
4630 SCS = &ICS.UserDefined.After;
4631 break;
4632 case ImplicitConversionSequence::AmbiguousConversion:
4633 case ImplicitConversionSequence::BadConversion:
4634 if (!DiagnoseMultipleUserDefinedConversion(From, T))
4635 return Diag(From->getSourceRange().getBegin(),
4636 diag::err_typecheck_converted_constant_expression)
4637 << From->getType() << From->getSourceRange() << T;
4638 return ExprError();
4639
4640 case ImplicitConversionSequence::EllipsisConversion:
4641 llvm_unreachable("ellipsis conversion in converted constant expression");
4642 }
4643
4644 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4645 if (Result.isInvalid())
4646 return Result;
4647
4648 // Check for a narrowing implicit conversion.
4649 APValue PreNarrowingValue;
Richard Smith911e1422012-01-30 22:27:01 +00004650 bool Diagnosed = false;
Richard Smithf8379a02012-01-18 23:55:52 +00004651 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue)) {
4652 case NK_Variable_Narrowing:
4653 // Implicit conversion to a narrower type, and the value is not a constant
4654 // expression. We'll diagnose this in a moment.
4655 case NK_Not_Narrowing:
4656 break;
4657
4658 case NK_Constant_Narrowing:
4659 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4660 << CCE << /*Constant*/1
4661 << PreNarrowingValue.getAsString(Context, QualType()) << T;
Richard Smith911e1422012-01-30 22:27:01 +00004662 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004663 break;
4664
4665 case NK_Type_Narrowing:
4666 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4667 << CCE << /*Constant*/0 << From->getType() << T;
Richard Smith911e1422012-01-30 22:27:01 +00004668 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004669 break;
4670 }
4671
4672 // Check the expression is a constant expression.
4673 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4674 Expr::EvalResult Eval;
4675 Eval.Diag = &Notes;
4676
4677 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4678 // The expression can't be folded, so we can't keep it at this position in
4679 // the AST.
4680 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004681 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004682 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004683
4684 if (Notes.empty()) {
4685 // It's a constant expression.
4686 return Result;
4687 }
Richard Smithf8379a02012-01-18 23:55:52 +00004688 }
4689
Richard Smith911e1422012-01-30 22:27:01 +00004690 // Only issue one narrowing diagnostic.
4691 if (Diagnosed)
4692 return Result;
4693
Richard Smithf8379a02012-01-18 23:55:52 +00004694 // It's not a constant expression. Produce an appropriate diagnostic.
4695 if (Notes.size() == 1 &&
4696 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4697 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4698 else {
4699 Diag(From->getSourceRange().getBegin(), diag::err_expr_not_cce)
4700 << CCE << From->getSourceRange();
4701 for (unsigned I = 0; I < Notes.size(); ++I)
4702 Diag(Notes[I].first, Notes[I].second);
4703 }
Richard Smith911e1422012-01-30 22:27:01 +00004704 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004705}
4706
John McCallfec112d2011-09-09 06:11:02 +00004707/// dropPointerConversions - If the given standard conversion sequence
4708/// involves any pointer conversions, remove them. This may change
4709/// the result type of the conversion sequence.
4710static void dropPointerConversion(StandardConversionSequence &SCS) {
4711 if (SCS.Second == ICK_Pointer_Conversion) {
4712 SCS.Second = ICK_Identity;
4713 SCS.Third = ICK_Identity;
4714 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4715 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004716}
John McCall5c32be02010-08-24 20:38:10 +00004717
John McCallfec112d2011-09-09 06:11:02 +00004718/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4719/// convert the expression From to an Objective-C pointer type.
4720static ImplicitConversionSequence
4721TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4722 // Do an implicit conversion to 'id'.
4723 QualType Ty = S.Context.getObjCIdType();
4724 ImplicitConversionSequence ICS
4725 = TryImplicitConversion(S, From, Ty,
4726 // FIXME: Are these flags correct?
4727 /*SuppressUserConversions=*/false,
4728 /*AllowExplicit=*/true,
4729 /*InOverloadResolution=*/false,
4730 /*CStyle=*/false,
4731 /*AllowObjCWritebackConversion=*/false);
4732
4733 // Strip off any final conversions to 'id'.
4734 switch (ICS.getKind()) {
4735 case ImplicitConversionSequence::BadConversion:
4736 case ImplicitConversionSequence::AmbiguousConversion:
4737 case ImplicitConversionSequence::EllipsisConversion:
4738 break;
4739
4740 case ImplicitConversionSequence::UserDefinedConversion:
4741 dropPointerConversion(ICS.UserDefined.After);
4742 break;
4743
4744 case ImplicitConversionSequence::StandardConversion:
4745 dropPointerConversion(ICS.Standard);
4746 break;
4747 }
4748
4749 return ICS;
4750}
4751
4752/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4753/// conversion of the expression From to an Objective-C pointer type.
4754ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004755 if (checkPlaceholderForOverload(*this, From))
4756 return ExprError();
4757
John McCall8b07ec22010-05-15 11:32:37 +00004758 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004759 ImplicitConversionSequence ICS =
4760 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004761 if (!ICS.isBad())
4762 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004763 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004764}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004765
Richard Smith8dd34252012-02-04 07:07:42 +00004766/// Determine whether the provided type is an integral type, or an enumeration
4767/// type of a permitted flavor.
4768static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4769 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4770 : T->isIntegralOrUnscopedEnumerationType();
4771}
4772
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004774/// enumeration type.
4775///
4776/// This routine will attempt to convert an expression of class type to an
4777/// integral or enumeration type, if that class type only has a single
4778/// conversion to an integral or enumeration type.
4779///
Douglas Gregor4799d032010-06-30 00:20:43 +00004780/// \param Loc The source location of the construct that requires the
4781/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004782///
Douglas Gregor4799d032010-06-30 00:20:43 +00004783/// \param FromE The expression we're converting from.
4784///
4785/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4786/// have integral or enumeration type.
4787///
4788/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4789/// incomplete class type.
4790///
4791/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4792/// explicit conversion function (because no implicit conversion functions
4793/// were available). This is a recovery mode.
4794///
4795/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4796/// showing which conversion was picked.
4797///
4798/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4799/// conversion function that could convert to integral or enumeration type.
4800///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004802/// usable conversion function.
4803///
4804/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4805/// function, which may be an extension in this case.
4806///
Richard Smith8dd34252012-02-04 07:07:42 +00004807/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4808/// enumerations should be considered.
4809///
Douglas Gregor4799d032010-06-30 00:20:43 +00004810/// \returns The expression, converted to an integral or enumeration type if
4811/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812ExprResult
John McCallb268a282010-08-23 23:25:46 +00004813Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004814 const PartialDiagnostic &NotIntDiag,
4815 const PartialDiagnostic &IncompleteDiag,
4816 const PartialDiagnostic &ExplicitConvDiag,
4817 const PartialDiagnostic &ExplicitConvNote,
4818 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004819 const PartialDiagnostic &AmbigNote,
Richard Smith8dd34252012-02-04 07:07:42 +00004820 const PartialDiagnostic &ConvDiag,
4821 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004822 // We can't perform any more checking for type-dependent expressions.
4823 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004824 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825
Eli Friedman1da70392012-01-26 00:26:18 +00004826 // Process placeholders immediately.
4827 if (From->hasPlaceholderType()) {
4828 ExprResult result = CheckPlaceholderExpr(From);
4829 if (result.isInvalid()) return result;
4830 From = result.take();
4831 }
4832
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004833 // If the expression already has integral or enumeration type, we're golden.
4834 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00004835 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00004836 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004837
4838 // FIXME: Check for missing '()' if T is a function type?
4839
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840 // 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 +00004841 // expression of integral or enumeration type.
4842 const RecordType *RecordTy = T->getAs<RecordType>();
4843 if (!RecordTy || !getLangOptions().CPlusPlus) {
4844 Diag(Loc, NotIntDiag)
4845 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004846 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004849 // We must have a complete class type.
4850 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004851 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004853 // Look for a conversion to an integral or enumeration type.
4854 UnresolvedSet<4> ViableConversions;
4855 UnresolvedSet<4> ExplicitConversions;
4856 const UnresolvedSetImpl *Conversions
4857 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004859 bool HadMultipleCandidates = (Conversions->size() > 1);
4860
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004861 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862 E = Conversions->end();
4863 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004864 ++I) {
4865 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00004866 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
4867 if (isIntegralOrEnumerationType(
4868 Conversion->getConversionType().getNonReferenceType(),
4869 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004870 if (Conversion->isExplicit())
4871 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4872 else
4873 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4874 }
Richard Smith8dd34252012-02-04 07:07:42 +00004875 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004878 switch (ViableConversions.size()) {
4879 case 0:
4880 if (ExplicitConversions.size() == 1) {
4881 DeclAccessPair Found = ExplicitConversions[0];
4882 CXXConversionDecl *Conversion
4883 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004885 // The user probably meant to invoke the given explicit
4886 // conversion; use it.
4887 QualType ConvTy
4888 = Conversion->getConversionType().getNonReferenceType();
4889 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004890 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004892 Diag(Loc, ExplicitConvDiag)
4893 << T << ConvTy
4894 << FixItHint::CreateInsertion(From->getLocStart(),
4895 "static_cast<" + TypeStr + ">(")
4896 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4897 ")");
4898 Diag(Conversion->getLocation(), ExplicitConvNote)
4899 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004900
4901 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004902 // explicit conversion function.
4903 if (isSFINAEContext())
4904 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004905
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004906 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004907 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4908 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004909 if (Result.isInvalid())
4910 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004911 // Record usage of conversion in an implicit cast.
4912 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4913 CK_UserDefinedConversion,
4914 Result.get(), 0,
4915 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004916 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004918 // We'll complain below about a non-integral condition type.
4919 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004921 case 1: {
4922 // Apply this conversion.
4923 DeclAccessPair Found = ViableConversions[0];
4924 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Douglas Gregor4799d032010-06-30 00:20:43 +00004926 CXXConversionDecl *Conversion
4927 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4928 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004929 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004930 if (ConvDiag.getDiagID()) {
4931 if (isSFINAEContext())
4932 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933
Douglas Gregor4799d032010-06-30 00:20:43 +00004934 Diag(Loc, ConvDiag)
4935 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004937
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004938 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4939 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004940 if (Result.isInvalid())
4941 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004942 // Record usage of conversion in an implicit cast.
4943 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4944 CK_UserDefinedConversion,
4945 Result.get(), 0,
4946 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004947 break;
4948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004949
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004950 default:
4951 Diag(Loc, AmbigDiag)
4952 << T << From->getSourceRange();
4953 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4954 CXXConversionDecl *Conv
4955 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4956 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4957 Diag(Conv->getLocation(), AmbigNote)
4958 << ConvTy->isEnumeralType() << ConvTy;
4959 }
John McCallb268a282010-08-23 23:25:46 +00004960 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004962
Richard Smith8dd34252012-02-04 07:07:42 +00004963 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004964 Diag(Loc, NotIntDiag)
4965 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004966
Eli Friedman1da70392012-01-26 00:26:18 +00004967 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004968}
4969
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004970/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004971/// candidate functions, using the given function call arguments. If
4972/// @p SuppressUserConversions, then don't allow user-defined
4973/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004974///
4975/// \para PartialOverloading true if we are performing "partial" overloading
4976/// based on an incomplete set of function arguments. This feature is used by
4977/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004978void
4979Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004980 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004981 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004982 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004983 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004984 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004985 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004986 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004987 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004988 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004989 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004990
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004991 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004992 if (!isa<CXXConstructorDecl>(Method)) {
4993 // If we get here, it's because we're calling a member function
4994 // that is named without a member access expression (e.g.,
4995 // "this->f") that was either written explicitly or created
4996 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004997 // function, e.g., X::f(). We use an empty type for the implied
4998 // object argument (C++ [over.call.func]p3), and the acting context
4999 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005000 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00005002 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005003 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005004 return;
5005 }
5006 // We treat a constructor like a non-member function, since its object
5007 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005008 }
5009
Douglas Gregorff7028a2009-11-13 23:59:09 +00005010 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005011 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005012
Douglas Gregor27381f32009-11-23 12:27:39 +00005013 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005014 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005015
Douglas Gregorffe14e32009-11-14 01:20:54 +00005016 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5017 // C++ [class.copy]p3:
5018 // A member function template is never instantiated to perform the copy
5019 // of a class object to an object of its class type.
5020 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005021 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005022 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005023 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5024 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005025 return;
5026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005028 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005029 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005030 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005031 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005032 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005033 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005034 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005035 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005037 unsigned NumArgsInProto = Proto->getNumArgs();
5038
5039 // (C++ 13.3.2p2): A candidate function having fewer than m
5040 // parameters is viable only if it has an ellipsis in its parameter
5041 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005043 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005044 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005045 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005046 return;
5047 }
5048
5049 // (C++ 13.3.2p2): A candidate function having more than m parameters
5050 // is viable only if the (m+1)st parameter has a default argument
5051 // (8.3.6). For the purposes of overload resolution, the
5052 // parameter list is truncated on the right, so that there are
5053 // exactly m parameters.
5054 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00005055 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005056 // Not enough arguments.
5057 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005058 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005059 return;
5060 }
5061
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005062 // (CUDA B.1): Check for invalid calls between targets.
5063 if (getLangOptions().CUDA)
5064 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5065 if (CheckCUDATarget(Caller, Function)) {
5066 Candidate.Viable = false;
5067 Candidate.FailureKind = ovl_fail_bad_target;
5068 return;
5069 }
5070
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005071 // Determine the implicit conversion sequences for each of the
5072 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005073 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5074 if (ArgIdx < NumArgsInProto) {
5075 // (C++ 13.3.2p3): for F to be a viable function, there shall
5076 // exist for each argument an implicit conversion sequence
5077 // (13.3.3.1) that converts that argument to the corresponding
5078 // parameter of F.
5079 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005080 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005081 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005082 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005083 /*InOverloadResolution=*/true,
5084 /*AllowObjCWritebackConversion=*/
5085 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005086 if (Candidate.Conversions[ArgIdx].isBad()) {
5087 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005088 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005089 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005090 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005091 } else {
5092 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5093 // argument for which there is no corresponding parameter is
5094 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005095 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005096 }
5097 }
5098}
5099
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005100/// \brief Add all of the function declarations in the given function set to
5101/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005102void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005103 Expr **Args, unsigned NumArgs,
5104 OverloadCandidateSet& CandidateSet,
5105 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00005106 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005107 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5108 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005109 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005110 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005111 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005112 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005114 CandidateSet, SuppressUserConversions);
5115 else
John McCalla0296f72010-03-19 07:35:19 +00005116 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005117 SuppressUserConversions);
5118 } else {
John McCalla0296f72010-03-19 07:35:19 +00005119 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005120 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5121 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005122 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005123 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00005124 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005126 Args[0]->Classify(Context),
5127 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005128 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00005129 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005130 else
John McCalla0296f72010-03-19 07:35:19 +00005131 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00005132 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005133 Args, NumArgs, CandidateSet,
5134 SuppressUserConversions);
5135 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005136 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005137}
5138
John McCallf0f1cf02009-11-17 07:50:12 +00005139/// AddMethodCandidate - Adds a named decl (which is some kind of
5140/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005141void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005142 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005143 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005144 Expr **Args, unsigned NumArgs,
5145 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005146 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005147 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005148 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005149
5150 if (isa<UsingShadowDecl>(Decl))
5151 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
John McCallf0f1cf02009-11-17 07:50:12 +00005153 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5154 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5155 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005156 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5157 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00005158 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00005159 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005160 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005161 } else {
John McCalla0296f72010-03-19 07:35:19 +00005162 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00005163 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005164 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005165 }
5166}
5167
Douglas Gregor436424c2008-11-18 23:14:02 +00005168/// AddMethodCandidate - Adds the given C++ member function to the set
5169/// of candidate functions, using the given function call arguments
5170/// and the object argument (@c Object). For example, in a call
5171/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5172/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5173/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005174/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005175void
John McCalla0296f72010-03-19 07:35:19 +00005176Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005177 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005178 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00005179 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00005180 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005181 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005182 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005183 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005184 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005185 assert(!isa<CXXConstructorDecl>(Method) &&
5186 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005187
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005188 if (!CandidateSet.isNewCandidate(Method))
5189 return;
5190
Douglas Gregor27381f32009-11-23 12:27:39 +00005191 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005192 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005193
Douglas Gregor436424c2008-11-18 23:14:02 +00005194 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005195 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005196 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005197 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005198 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005199 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005200 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00005201
5202 unsigned NumArgsInProto = Proto->getNumArgs();
5203
5204 // (C++ 13.3.2p2): A candidate function having fewer than m
5205 // parameters is viable only if it has an ellipsis in its parameter
5206 // list (8.3.5).
5207 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5208 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005209 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005210 return;
5211 }
5212
5213 // (C++ 13.3.2p2): A candidate function having more than m parameters
5214 // is viable only if the (m+1)st parameter has a default argument
5215 // (8.3.6). For the purposes of overload resolution, the
5216 // parameter list is truncated on the right, so that there are
5217 // exactly m parameters.
5218 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5219 if (NumArgs < MinRequiredArgs) {
5220 // Not enough arguments.
5221 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005222 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005223 return;
5224 }
5225
5226 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005227
John McCall6e9f8f62009-12-03 04:06:58 +00005228 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005229 // The implicit object argument is ignored.
5230 Candidate.IgnoreObjectArgument = true;
5231 else {
5232 // Determine the implicit conversion sequence for the object
5233 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005234 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005235 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5236 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005237 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005238 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005239 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005240 return;
5241 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005242 }
5243
5244 // Determine the implicit conversion sequences for each of the
5245 // arguments.
5246 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5247 if (ArgIdx < NumArgsInProto) {
5248 // (C++ 13.3.2p3): for F to be a viable function, there shall
5249 // exist for each argument an implicit conversion sequence
5250 // (13.3.3.1) that converts that argument to the corresponding
5251 // parameter of F.
5252 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005253 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005254 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005256 /*InOverloadResolution=*/true,
5257 /*AllowObjCWritebackConversion=*/
5258 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005259 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005260 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005261 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005262 break;
5263 }
5264 } else {
5265 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5266 // argument for which there is no corresponding parameter is
5267 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005268 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005269 }
5270 }
5271}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Douglas Gregor97628d62009-08-21 00:16:32 +00005273/// \brief Add a C++ member function template as a candidate to the candidate
5274/// set, using template argument deduction to produce an appropriate member
5275/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005276void
Douglas Gregor97628d62009-08-21 00:16:32 +00005277Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005278 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005279 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005280 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005281 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005282 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00005283 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00005284 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005285 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005286 if (!CandidateSet.isNewCandidate(MethodTmpl))
5287 return;
5288
Douglas Gregor97628d62009-08-21 00:16:32 +00005289 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005290 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005291 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005292 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005293 // candidate functions in the usual way.113) A given name can refer to one
5294 // or more function templates and also to a set of overloaded non-template
5295 // functions. In such a case, the candidate functions generated from each
5296 // function template are combined with the set of non-template candidate
5297 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005298 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005299 FunctionDecl *Specialization = 0;
5300 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00005301 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00005302 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005303 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005304 Candidate.FoundDecl = FoundDecl;
5305 Candidate.Function = MethodTmpl->getTemplatedDecl();
5306 Candidate.Viable = false;
5307 Candidate.FailureKind = ovl_fail_bad_deduction;
5308 Candidate.IsSurrogate = false;
5309 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005310 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005312 Info);
5313 return;
5314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
Douglas Gregor97628d62009-08-21 00:16:32 +00005316 // Add the function template specialization produced by template argument
5317 // deduction as a candidate.
5318 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005319 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005320 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005321 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00005322 ActingContext, ObjectType, ObjectClassification,
5323 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005324}
5325
Douglas Gregor05155d82009-08-21 23:19:43 +00005326/// \brief Add a C++ function template specialization as a candidate
5327/// in the candidate set, using template argument deduction to produce
5328/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005329void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005330Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005331 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005332 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005333 Expr **Args, unsigned NumArgs,
5334 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005335 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005336 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5337 return;
5338
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005339 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005340 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005341 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005342 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005343 // candidate functions in the usual way.113) A given name can refer to one
5344 // or more function templates and also to a set of overloaded non-template
5345 // functions. In such a case, the candidate functions generated from each
5346 // function template are combined with the set of non-template candidate
5347 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005348 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005349 FunctionDecl *Specialization = 0;
5350 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00005351 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005352 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005353 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005354 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005355 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5356 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005357 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005358 Candidate.IsSurrogate = false;
5359 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005360 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005361 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005362 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005363 return;
5364 }
Mike Stump11289f42009-09-09 15:08:12 +00005365
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005366 // Add the function template specialization produced by template argument
5367 // deduction as a candidate.
5368 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005369 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005370 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005371}
Mike Stump11289f42009-09-09 15:08:12 +00005372
Douglas Gregora1f013e2008-11-07 22:36:19 +00005373/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005374/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005375/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005376/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005377/// (which may or may not be the same type as the type that the
5378/// conversion function produces).
5379void
5380Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005381 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005382 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005383 Expr *From, QualType ToType,
5384 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005385 assert(!Conversion->getDescribedFunctionTemplate() &&
5386 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005387 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005388 if (!CandidateSet.isNewCandidate(Conversion))
5389 return;
5390
Douglas Gregor27381f32009-11-23 12:27:39 +00005391 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005392 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005393
Douglas Gregora1f013e2008-11-07 22:36:19 +00005394 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005395 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005396 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005397 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005398 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005399 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005400 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005401 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005402 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005403 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005404 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005405
Douglas Gregor6affc782010-08-19 15:37:02 +00005406 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005407 // For conversion functions, the function is considered to be a member of
5408 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005409 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005410 //
5411 // Determine the implicit conversion sequence for the implicit
5412 // object parameter.
5413 QualType ImplicitParamType = From->getType();
5414 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5415 ImplicitParamType = FromPtrType->getPointeeType();
5416 CXXRecordDecl *ConversionContext
5417 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005418
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005419 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005420 = TryObjectArgumentInitialization(*this, From->getType(),
5421 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005422 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
John McCall0d1da222010-01-12 00:44:57 +00005424 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005425 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005426 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005427 return;
5428 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005429
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005430 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005431 // derived to base as such conversions are given Conversion Rank. They only
5432 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5433 QualType FromCanon
5434 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5435 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5436 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5437 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005438 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005439 return;
5440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005441
Douglas Gregora1f013e2008-11-07 22:36:19 +00005442 // To determine what the conversion from the result of calling the
5443 // conversion function to the type we're eventually trying to
5444 // convert to (ToType), we need to synthesize a call to the
5445 // conversion function and attempt copy initialization from it. This
5446 // makes sure that we get the right semantics with respect to
5447 // lvalues/rvalues and the type. Fortunately, we can allocate this
5448 // call on the stack and we don't need its arguments to be
5449 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005450 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005451 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005452 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5453 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005454 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005455 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005456
Richard Smith48d24642011-07-13 22:53:21 +00005457 QualType ConversionType = Conversion->getConversionType();
5458 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005459 Candidate.Viable = false;
5460 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5461 return;
5462 }
5463
Richard Smith48d24642011-07-13 22:53:21 +00005464 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005465
Mike Stump11289f42009-09-09 15:08:12 +00005466 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005467 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5468 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005469 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005470 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005471 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005472 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005473 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005474 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005475 /*InOverloadResolution=*/false,
5476 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005477
John McCall0d1da222010-01-12 00:44:57 +00005478 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005479 case ImplicitConversionSequence::StandardConversion:
5480 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005482 // C++ [over.ics.user]p3:
5483 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005485 // shall have exact match rank.
5486 if (Conversion->getPrimaryTemplate() &&
5487 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5488 Candidate.Viable = false;
5489 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491
Douglas Gregorcba72b12011-01-21 05:18:22 +00005492 // C++0x [dcl.init.ref]p5:
5493 // In the second case, if the reference is an rvalue reference and
5494 // the second standard conversion sequence of the user-defined
5495 // conversion sequence includes an lvalue-to-rvalue conversion, the
5496 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005497 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005498 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5499 Candidate.Viable = false;
5500 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5501 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005502 break;
5503
5504 case ImplicitConversionSequence::BadConversion:
5505 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005506 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005507 break;
5508
5509 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005510 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005511 "Can only end up with a standard conversion sequence or failure");
5512 }
5513}
5514
Douglas Gregor05155d82009-08-21 23:19:43 +00005515/// \brief Adds a conversion function template specialization
5516/// candidate to the overload set, using template argument deduction
5517/// to deduce the template arguments of the conversion function
5518/// template from the type that we are converting to (C++
5519/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005520void
Douglas Gregor05155d82009-08-21 23:19:43 +00005521Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005522 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005523 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005524 Expr *From, QualType ToType,
5525 OverloadCandidateSet &CandidateSet) {
5526 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5527 "Only conversion function templates permitted here");
5528
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005529 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5530 return;
5531
John McCallbc077cf2010-02-08 23:07:23 +00005532 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005533 CXXConversionDecl *Specialization = 0;
5534 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005535 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005536 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005537 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005538 Candidate.FoundDecl = FoundDecl;
5539 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5540 Candidate.Viable = false;
5541 Candidate.FailureKind = ovl_fail_bad_deduction;
5542 Candidate.IsSurrogate = false;
5543 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005544 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005546 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005547 return;
5548 }
Mike Stump11289f42009-09-09 15:08:12 +00005549
Douglas Gregor05155d82009-08-21 23:19:43 +00005550 // Add the conversion function template specialization produced by
5551 // template argument deduction as a candidate.
5552 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005553 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005554 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005555}
5556
Douglas Gregorab7897a2008-11-19 22:57:39 +00005557/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5558/// converts the given @c Object to a function pointer via the
5559/// conversion function @c Conversion, and then attempts to call it
5560/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5561/// the type of function that we'll eventually be calling.
5562void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005563 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005564 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005565 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005566 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005567 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005568 OverloadCandidateSet& CandidateSet) {
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
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005575 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005576 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005577 Candidate.Function = 0;
5578 Candidate.Surrogate = Conversion;
5579 Candidate.Viable = true;
5580 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005581 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005582 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005583
5584 // Determine the implicit conversion sequence for the implicit
5585 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005586 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005588 Object->Classify(Context),
5589 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005590 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005591 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005592 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005593 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005594 return;
5595 }
5596
5597 // The first conversion is actually a user-defined conversion whose
5598 // first conversion is ObjectInit's standard conversion (which is
5599 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005600 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005601 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005602 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005603 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005604 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005605 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005606 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005607 = Candidate.Conversions[0].UserDefined.Before;
5608 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5609
Mike Stump11289f42009-09-09 15:08:12 +00005610 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005611 unsigned NumArgsInProto = Proto->getNumArgs();
5612
5613 // (C++ 13.3.2p2): A candidate function having fewer than m
5614 // parameters is viable only if it has an ellipsis in its parameter
5615 // list (8.3.5).
5616 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5617 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005618 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005619 return;
5620 }
5621
5622 // Function types don't have any default arguments, so just check if
5623 // we have enough arguments.
5624 if (NumArgs < NumArgsInProto) {
5625 // Not enough arguments.
5626 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005627 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005628 return;
5629 }
5630
5631 // Determine the implicit conversion sequences for each of the
5632 // arguments.
5633 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5634 if (ArgIdx < NumArgsInProto) {
5635 // (C++ 13.3.2p3): for F to be a viable function, there shall
5636 // exist for each argument an implicit conversion sequence
5637 // (13.3.3.1) that converts that argument to the corresponding
5638 // parameter of F.
5639 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005640 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005641 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005642 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005643 /*InOverloadResolution=*/false,
5644 /*AllowObjCWritebackConversion=*/
5645 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005646 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005647 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005648 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005649 break;
5650 }
5651 } else {
5652 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5653 // argument for which there is no corresponding parameter is
5654 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005655 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005656 }
5657 }
5658}
5659
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005660/// \brief Add overload candidates for overloaded operators that are
5661/// member functions.
5662///
5663/// Add the overloaded operator candidates that are member functions
5664/// for the operator Op that was used in an operator expression such
5665/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5666/// CandidateSet will store the added overload candidates. (C++
5667/// [over.match.oper]).
5668void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5669 SourceLocation OpLoc,
5670 Expr **Args, unsigned NumArgs,
5671 OverloadCandidateSet& CandidateSet,
5672 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5674
5675 // C++ [over.match.oper]p3:
5676 // For a unary operator @ with an operand of a type whose
5677 // cv-unqualified version is T1, and for a binary operator @ with
5678 // a left operand of a type whose cv-unqualified version is T1 and
5679 // a right operand of a type whose cv-unqualified version is T2,
5680 // three sets of candidate functions, designated member
5681 // candidates, non-member candidates and built-in candidates, are
5682 // constructed as follows:
5683 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005684
5685 // -- If T1 is a class type, the set of member candidates is the
5686 // result of the qualified lookup of T1::operator@
5687 // (13.3.1.1.1); otherwise, the set of member candidates is
5688 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005689 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005690 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005691 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005692 return;
Mike Stump11289f42009-09-09 15:08:12 +00005693
John McCall27b18f82009-11-17 02:14:36 +00005694 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5695 LookupQualifiedName(Operators, T1Rec->getDecl());
5696 Operators.suppressDiagnostics();
5697
Mike Stump11289f42009-09-09 15:08:12 +00005698 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005699 OperEnd = Operators.end();
5700 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005701 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005702 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005704 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005705 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005706 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005707}
5708
Douglas Gregora11693b2008-11-12 17:17:38 +00005709/// AddBuiltinCandidate - Add a candidate for a built-in
5710/// operator. ResultTy and ParamTys are the result and parameter types
5711/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005712/// arguments being passed to the candidate. IsAssignmentOperator
5713/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005714/// operator. NumContextualBoolArguments is the number of arguments
5715/// (at the beginning of the argument list) that will be contextually
5716/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005717void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005718 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005719 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005720 bool IsAssignmentOperator,
5721 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005722 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005723 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005724
Douglas Gregora11693b2008-11-12 17:17:38 +00005725 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005726 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005727 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005728 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005729 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005730 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005731 Candidate.BuiltinTypes.ResultTy = ResultTy;
5732 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5733 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5734
5735 // Determine the implicit conversion sequences for each of the
5736 // arguments.
5737 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005738 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005739 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005740 // C++ [over.match.oper]p4:
5741 // For the built-in assignment operators, conversions of the
5742 // left operand are restricted as follows:
5743 // -- no temporaries are introduced to hold the left operand, and
5744 // -- no user-defined conversions are applied to the left
5745 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005746 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005747 //
5748 // We block these conversions by turning off user-defined
5749 // conversions, since that is the only way that initialization of
5750 // a reference to a non-class type can occur from something that
5751 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005752 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005753 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005754 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005755 Candidate.Conversions[ArgIdx]
5756 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005757 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005758 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005759 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005760 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005761 /*InOverloadResolution=*/false,
5762 /*AllowObjCWritebackConversion=*/
5763 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005764 }
John McCall0d1da222010-01-12 00:44:57 +00005765 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005766 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005767 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005768 break;
5769 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005770 }
5771}
5772
5773/// BuiltinCandidateTypeSet - A set of types that will be used for the
5774/// candidate operator functions for built-in operators (C++
5775/// [over.built]). The types are separated into pointer types and
5776/// enumeration types.
5777class BuiltinCandidateTypeSet {
5778 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005779 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005780
5781 /// PointerTypes - The set of pointer types that will be used in the
5782 /// built-in candidates.
5783 TypeSet PointerTypes;
5784
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005785 /// MemberPointerTypes - The set of member pointer types that will be
5786 /// used in the built-in candidates.
5787 TypeSet MemberPointerTypes;
5788
Douglas Gregora11693b2008-11-12 17:17:38 +00005789 /// EnumerationTypes - The set of enumeration types that will be
5790 /// used in the built-in candidates.
5791 TypeSet EnumerationTypes;
5792
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005793 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005794 /// candidates.
5795 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005796
5797 /// \brief A flag indicating non-record types are viable candidates
5798 bool HasNonRecordTypes;
5799
5800 /// \brief A flag indicating whether either arithmetic or enumeration types
5801 /// were present in the candidate set.
5802 bool HasArithmeticOrEnumeralTypes;
5803
Douglas Gregor80af3132011-05-21 23:15:46 +00005804 /// \brief A flag indicating whether the nullptr type was present in the
5805 /// candidate set.
5806 bool HasNullPtrType;
5807
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005808 /// Sema - The semantic analysis instance where we are building the
5809 /// candidate type set.
5810 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005811
Douglas Gregora11693b2008-11-12 17:17:38 +00005812 /// Context - The AST context in which we will build the type sets.
5813 ASTContext &Context;
5814
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005815 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5816 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005817 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005818
5819public:
5820 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005821 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005822
Mike Stump11289f42009-09-09 15:08:12 +00005823 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005824 : HasNonRecordTypes(false),
5825 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005826 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005827 SemaRef(SemaRef),
5828 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005829
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005830 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005831 SourceLocation Loc,
5832 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005833 bool AllowExplicitConversions,
5834 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005835
5836 /// pointer_begin - First pointer type found;
5837 iterator pointer_begin() { return PointerTypes.begin(); }
5838
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005839 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005840 iterator pointer_end() { return PointerTypes.end(); }
5841
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005842 /// member_pointer_begin - First member pointer type found;
5843 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5844
5845 /// member_pointer_end - Past the last member pointer type found;
5846 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5847
Douglas Gregora11693b2008-11-12 17:17:38 +00005848 /// enumeration_begin - First enumeration type found;
5849 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5850
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005851 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005852 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005854 iterator vector_begin() { return VectorTypes.begin(); }
5855 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005856
5857 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5858 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005859 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005860};
5861
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005862/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005863/// the set of pointer types along with any more-qualified variants of
5864/// that type. For example, if @p Ty is "int const *", this routine
5865/// will add "int const *", "int const volatile *", "int const
5866/// restrict *", and "int const volatile restrict *" to the set of
5867/// pointer types. Returns true if the add of @p Ty itself succeeded,
5868/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005869///
5870/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005871bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005872BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5873 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005874
Douglas Gregora11693b2008-11-12 17:17:38 +00005875 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005876 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005877 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005878
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005879 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005880 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005881 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005882 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005883 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005884 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005885 buildObjCPtr = true;
5886 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005887 else
David Blaikie83d382b2011-09-23 05:06:16 +00005888 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005889 }
5890 else
5891 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005892
Sebastian Redl4990a632009-11-18 20:39:26 +00005893 // Don't add qualified variants of arrays. For one, they're not allowed
5894 // (the qualifier would sink to the element type), and for another, the
5895 // only overload situation where it matters is subscript or pointer +- int,
5896 // and those shouldn't have qualifier variants anyway.
5897 if (PointeeTy->isArrayType())
5898 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005899 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005900 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005901 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005902 bool hasVolatile = VisibleQuals.hasVolatile();
5903 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005904
John McCall8ccfcb52009-09-24 19:53:00 +00005905 // Iterate through all strict supersets of BaseCVR.
5906 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5907 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005908 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5909 // in the types.
5910 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5911 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005912 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005913 if (!buildObjCPtr)
5914 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5915 else
5916 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005917 }
5918
5919 return true;
5920}
5921
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005922/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5923/// to the set of pointer types along with any more-qualified variants of
5924/// that type. For example, if @p Ty is "int const *", this routine
5925/// will add "int const *", "int const volatile *", "int const
5926/// restrict *", and "int const volatile restrict *" to the set of
5927/// pointer types. Returns true if the add of @p Ty itself succeeded,
5928/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005929///
5930/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005931bool
5932BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5933 QualType Ty) {
5934 // Insert this type.
5935 if (!MemberPointerTypes.insert(Ty))
5936 return false;
5937
John McCall8ccfcb52009-09-24 19:53:00 +00005938 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5939 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005940
John McCall8ccfcb52009-09-24 19:53:00 +00005941 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005942 // Don't add qualified variants of arrays. For one, they're not allowed
5943 // (the qualifier would sink to the element type), and for another, the
5944 // only overload situation where it matters is subscript or pointer +- int,
5945 // and those shouldn't have qualifier variants anyway.
5946 if (PointeeTy->isArrayType())
5947 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005948 const Type *ClassTy = PointerTy->getClass();
5949
5950 // Iterate through all strict supersets of the pointee type's CVR
5951 // qualifiers.
5952 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5953 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5954 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005955
John McCall8ccfcb52009-09-24 19:53:00 +00005956 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005957 MemberPointerTypes.insert(
5958 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005959 }
5960
5961 return true;
5962}
5963
Douglas Gregora11693b2008-11-12 17:17:38 +00005964/// AddTypesConvertedFrom - Add each of the types to which the type @p
5965/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005966/// primarily interested in pointer types and enumeration types. We also
5967/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005968/// AllowUserConversions is true if we should look at the conversion
5969/// functions of a class type, and AllowExplicitConversions if we
5970/// should also include the explicit conversion functions of a class
5971/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005972void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005973BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005974 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005975 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005976 bool AllowExplicitConversions,
5977 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005978 // Only deal with canonical types.
5979 Ty = Context.getCanonicalType(Ty);
5980
5981 // Look through reference types; they aren't part of the type of an
5982 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005983 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005984 Ty = RefTy->getPointeeType();
5985
John McCall33ddac02011-01-19 10:06:00 +00005986 // If we're dealing with an array type, decay to the pointer.
5987 if (Ty->isArrayType())
5988 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5989
5990 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005991 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005992
Chandler Carruth00a38332010-12-13 01:44:01 +00005993 // Flag if we ever add a non-record type.
5994 const RecordType *TyRec = Ty->getAs<RecordType>();
5995 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5996
Chandler Carruth00a38332010-12-13 01:44:01 +00005997 // Flag if we encounter an arithmetic type.
5998 HasArithmeticOrEnumeralTypes =
5999 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6000
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006001 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6002 PointerTypes.insert(Ty);
6003 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006004 // Insert our type, and its more-qualified variants, into the set
6005 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006006 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006007 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006008 } else if (Ty->isMemberPointerType()) {
6009 // Member pointers are far easier, since the pointee can't be converted.
6010 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6011 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006012 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006013 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006014 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006015 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006016 // We treat vector types as arithmetic types in many contexts as an
6017 // extension.
6018 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006019 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006020 } else if (Ty->isNullPtrType()) {
6021 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006022 } else if (AllowUserConversions && TyRec) {
6023 // No conversion functions in incomplete types.
6024 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6025 return;
Mike Stump11289f42009-09-09 15:08:12 +00006026
Chandler Carruth00a38332010-12-13 01:44:01 +00006027 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6028 const UnresolvedSetImpl *Conversions
6029 = ClassDecl->getVisibleConversionFunctions();
6030 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6031 E = Conversions->end(); I != E; ++I) {
6032 NamedDecl *D = I.getDecl();
6033 if (isa<UsingShadowDecl>(D))
6034 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006035
Chandler Carruth00a38332010-12-13 01:44:01 +00006036 // Skip conversion function templates; they don't tell us anything
6037 // about which builtin types we can convert to.
6038 if (isa<FunctionTemplateDecl>(D))
6039 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006040
Chandler Carruth00a38332010-12-13 01:44:01 +00006041 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6042 if (AllowExplicitConversions || !Conv->isExplicit()) {
6043 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6044 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006045 }
6046 }
6047 }
6048}
6049
Douglas Gregor84605ae2009-08-24 13:43:27 +00006050/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6051/// the volatile- and non-volatile-qualified assignment operators for the
6052/// given type to the candidate set.
6053static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6054 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006055 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006056 unsigned NumArgs,
6057 OverloadCandidateSet &CandidateSet) {
6058 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006059
Douglas Gregor84605ae2009-08-24 13:43:27 +00006060 // T& operator=(T&, T)
6061 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6062 ParamTypes[1] = T;
6063 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6064 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006065
Douglas Gregor84605ae2009-08-24 13:43:27 +00006066 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6067 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006068 ParamTypes[0]
6069 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006070 ParamTypes[1] = T;
6071 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006072 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006073 }
6074}
Mike Stump11289f42009-09-09 15:08:12 +00006075
Sebastian Redl1054fae2009-10-25 17:03:50 +00006076/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6077/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006078static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6079 Qualifiers VRQuals;
6080 const RecordType *TyRec;
6081 if (const MemberPointerType *RHSMPType =
6082 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006083 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006084 else
6085 TyRec = ArgExpr->getType()->getAs<RecordType>();
6086 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006087 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006088 VRQuals.addVolatile();
6089 VRQuals.addRestrict();
6090 return VRQuals;
6091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006092
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006093 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006094 if (!ClassDecl->hasDefinition())
6095 return VRQuals;
6096
John McCallad371252010-01-20 00:46:10 +00006097 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006098 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006099
John McCallad371252010-01-20 00:46:10 +00006100 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006101 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006102 NamedDecl *D = I.getDecl();
6103 if (isa<UsingShadowDecl>(D))
6104 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6105 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006106 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6107 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6108 CanTy = ResTypeRef->getPointeeType();
6109 // Need to go down the pointer/mempointer chain and add qualifiers
6110 // as see them.
6111 bool done = false;
6112 while (!done) {
6113 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6114 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006115 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006116 CanTy->getAs<MemberPointerType>())
6117 CanTy = ResTypeMPtr->getPointeeType();
6118 else
6119 done = true;
6120 if (CanTy.isVolatileQualified())
6121 VRQuals.addVolatile();
6122 if (CanTy.isRestrictQualified())
6123 VRQuals.addRestrict();
6124 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6125 return VRQuals;
6126 }
6127 }
6128 }
6129 return VRQuals;
6130}
John McCall52872982010-11-13 05:51:15 +00006131
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006132namespace {
John McCall52872982010-11-13 05:51:15 +00006133
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006134/// \brief Helper class to manage the addition of builtin operator overload
6135/// candidates. It provides shared state and utility methods used throughout
6136/// the process, as well as a helper method to add each group of builtin
6137/// operator overloads from the standard to a candidate set.
6138class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006139 // Common instance state available to all overload candidate addition methods.
6140 Sema &S;
6141 Expr **Args;
6142 unsigned NumArgs;
6143 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006144 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006145 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006146 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006147
Chandler Carruthc6586e52010-12-12 10:35:00 +00006148 // Define some constants used to index and iterate over the arithemetic types
6149 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006150 // The "promoted arithmetic types" are the arithmetic
6151 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006152 static const unsigned FirstIntegralType = 3;
6153 static const unsigned LastIntegralType = 18;
6154 static const unsigned FirstPromotedIntegralType = 3,
6155 LastPromotedIntegralType = 9;
6156 static const unsigned FirstPromotedArithmeticType = 0,
6157 LastPromotedArithmeticType = 9;
6158 static const unsigned NumArithmeticTypes = 18;
6159
Chandler Carruthc6586e52010-12-12 10:35:00 +00006160 /// \brief Get the canonical type for a given arithmetic type index.
6161 CanQualType getArithmeticType(unsigned index) {
6162 assert(index < NumArithmeticTypes);
6163 static CanQualType ASTContext::* const
6164 ArithmeticTypes[NumArithmeticTypes] = {
6165 // Start of promoted types.
6166 &ASTContext::FloatTy,
6167 &ASTContext::DoubleTy,
6168 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006169
Chandler Carruthc6586e52010-12-12 10:35:00 +00006170 // Start of integral types.
6171 &ASTContext::IntTy,
6172 &ASTContext::LongTy,
6173 &ASTContext::LongLongTy,
6174 &ASTContext::UnsignedIntTy,
6175 &ASTContext::UnsignedLongTy,
6176 &ASTContext::UnsignedLongLongTy,
6177 // End of promoted types.
6178
6179 &ASTContext::BoolTy,
6180 &ASTContext::CharTy,
6181 &ASTContext::WCharTy,
6182 &ASTContext::Char16Ty,
6183 &ASTContext::Char32Ty,
6184 &ASTContext::SignedCharTy,
6185 &ASTContext::ShortTy,
6186 &ASTContext::UnsignedCharTy,
6187 &ASTContext::UnsignedShortTy,
6188 // End of integral types.
6189 // FIXME: What about complex?
6190 };
6191 return S.Context.*ArithmeticTypes[index];
6192 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006193
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006194 /// \brief Gets the canonical type resulting from the usual arithemetic
6195 /// converions for the given arithmetic types.
6196 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6197 // Accelerator table for performing the usual arithmetic conversions.
6198 // The rules are basically:
6199 // - if either is floating-point, use the wider floating-point
6200 // - if same signedness, use the higher rank
6201 // - if same size, use unsigned of the higher rank
6202 // - use the larger type
6203 // These rules, together with the axiom that higher ranks are
6204 // never smaller, are sufficient to precompute all of these results
6205 // *except* when dealing with signed types of higher rank.
6206 // (we could precompute SLL x UI for all known platforms, but it's
6207 // better not to make any assumptions).
6208 enum PromotedType {
6209 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6210 };
6211 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6212 [LastPromotedArithmeticType] = {
6213 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6214 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6215 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6216 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6217 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6218 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6219 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6220 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6221 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6222 };
6223
6224 assert(L < LastPromotedArithmeticType);
6225 assert(R < LastPromotedArithmeticType);
6226 int Idx = ConversionsTable[L][R];
6227
6228 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006229 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006230
6231 // Slow path: we need to compare widths.
6232 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006233 CanQualType LT = getArithmeticType(L),
6234 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006235 unsigned LW = S.Context.getIntWidth(LT),
6236 RW = S.Context.getIntWidth(RT);
6237
6238 // If they're different widths, use the signed type.
6239 if (LW > RW) return LT;
6240 else if (LW < RW) return RT;
6241
6242 // Otherwise, use the unsigned type of the signed type's rank.
6243 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6244 assert(L == SLL || R == SLL);
6245 return S.Context.UnsignedLongLongTy;
6246 }
6247
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006248 /// \brief Helper method to factor out the common pattern of adding overloads
6249 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006250 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6251 bool HasVolatile) {
6252 QualType ParamTypes[2] = {
6253 S.Context.getLValueReferenceType(CandidateTy),
6254 S.Context.IntTy
6255 };
6256
6257 // Non-volatile version.
6258 if (NumArgs == 1)
6259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6260 else
6261 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6262
6263 // Use a heuristic to reduce number of builtin candidates in the set:
6264 // add volatile version only if there are conversions to a volatile type.
6265 if (HasVolatile) {
6266 ParamTypes[0] =
6267 S.Context.getLValueReferenceType(
6268 S.Context.getVolatileType(CandidateTy));
6269 if (NumArgs == 1)
6270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6271 else
6272 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6273 }
6274 }
6275
6276public:
6277 BuiltinOperatorOverloadBuilder(
6278 Sema &S, Expr **Args, unsigned NumArgs,
6279 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006280 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006281 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006282 OverloadCandidateSet &CandidateSet)
6283 : S(S), Args(Args), NumArgs(NumArgs),
6284 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006285 HasArithmeticOrEnumeralCandidateType(
6286 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006287 CandidateTypes(CandidateTypes),
6288 CandidateSet(CandidateSet) {
6289 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006290 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006291 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006292 assert(getArithmeticType(LastPromotedIntegralType - 1)
6293 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006294 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006295 assert(getArithmeticType(FirstPromotedArithmeticType)
6296 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006297 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006298 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6299 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006300 "Invalid last promoted arithmetic type");
6301 }
6302
6303 // C++ [over.built]p3:
6304 //
6305 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6306 // is either volatile or empty, there exist candidate operator
6307 // functions of the form
6308 //
6309 // VQ T& operator++(VQ T&);
6310 // T operator++(VQ T&, int);
6311 //
6312 // C++ [over.built]p4:
6313 //
6314 // For every pair (T, VQ), where T is an arithmetic type other
6315 // than bool, and VQ is either volatile or empty, there exist
6316 // candidate operator functions of the form
6317 //
6318 // VQ T& operator--(VQ T&);
6319 // T operator--(VQ T&, int);
6320 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006321 if (!HasArithmeticOrEnumeralCandidateType)
6322 return;
6323
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006324 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6325 Arith < NumArithmeticTypes; ++Arith) {
6326 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006327 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006328 VisibleTypeConversionsQuals.hasVolatile());
6329 }
6330 }
6331
6332 // C++ [over.built]p5:
6333 //
6334 // For every pair (T, VQ), where T is a cv-qualified or
6335 // cv-unqualified object type, and VQ is either volatile or
6336 // empty, there exist candidate operator functions of the form
6337 //
6338 // T*VQ& operator++(T*VQ&);
6339 // T*VQ& operator--(T*VQ&);
6340 // T* operator++(T*VQ&, int);
6341 // T* operator--(T*VQ&, int);
6342 void addPlusPlusMinusMinusPointerOverloads() {
6343 for (BuiltinCandidateTypeSet::iterator
6344 Ptr = CandidateTypes[0].pointer_begin(),
6345 PtrEnd = CandidateTypes[0].pointer_end();
6346 Ptr != PtrEnd; ++Ptr) {
6347 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006348 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006349 continue;
6350
6351 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6352 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6353 VisibleTypeConversionsQuals.hasVolatile()));
6354 }
6355 }
6356
6357 // C++ [over.built]p6:
6358 // For every cv-qualified or cv-unqualified object type T, there
6359 // exist candidate operator functions of the form
6360 //
6361 // T& operator*(T*);
6362 //
6363 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006364 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006365 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006366 // T& operator*(T*);
6367 void addUnaryStarPointerOverloads() {
6368 for (BuiltinCandidateTypeSet::iterator
6369 Ptr = CandidateTypes[0].pointer_begin(),
6370 PtrEnd = CandidateTypes[0].pointer_end();
6371 Ptr != PtrEnd; ++Ptr) {
6372 QualType ParamTy = *Ptr;
6373 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006374 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6375 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006376
Douglas Gregor02824322011-01-26 19:30:28 +00006377 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6378 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6379 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006381 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6382 &ParamTy, Args, 1, CandidateSet);
6383 }
6384 }
6385
6386 // C++ [over.built]p9:
6387 // For every promoted arithmetic type T, there exist candidate
6388 // operator functions of the form
6389 //
6390 // T operator+(T);
6391 // T operator-(T);
6392 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006393 if (!HasArithmeticOrEnumeralCandidateType)
6394 return;
6395
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006396 for (unsigned Arith = FirstPromotedArithmeticType;
6397 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006398 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006399 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6400 }
6401
6402 // Extension: We also add these operators for vector types.
6403 for (BuiltinCandidateTypeSet::iterator
6404 Vec = CandidateTypes[0].vector_begin(),
6405 VecEnd = CandidateTypes[0].vector_end();
6406 Vec != VecEnd; ++Vec) {
6407 QualType VecTy = *Vec;
6408 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6409 }
6410 }
6411
6412 // C++ [over.built]p8:
6413 // For every type T, there exist candidate operator functions of
6414 // the form
6415 //
6416 // T* operator+(T*);
6417 void addUnaryPlusPointerOverloads() {
6418 for (BuiltinCandidateTypeSet::iterator
6419 Ptr = CandidateTypes[0].pointer_begin(),
6420 PtrEnd = CandidateTypes[0].pointer_end();
6421 Ptr != PtrEnd; ++Ptr) {
6422 QualType ParamTy = *Ptr;
6423 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6424 }
6425 }
6426
6427 // C++ [over.built]p10:
6428 // For every promoted integral type T, there exist candidate
6429 // operator functions of the form
6430 //
6431 // T operator~(T);
6432 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006433 if (!HasArithmeticOrEnumeralCandidateType)
6434 return;
6435
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006436 for (unsigned Int = FirstPromotedIntegralType;
6437 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006438 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006439 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6440 }
6441
6442 // Extension: We also add this operator for vector types.
6443 for (BuiltinCandidateTypeSet::iterator
6444 Vec = CandidateTypes[0].vector_begin(),
6445 VecEnd = CandidateTypes[0].vector_end();
6446 Vec != VecEnd; ++Vec) {
6447 QualType VecTy = *Vec;
6448 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6449 }
6450 }
6451
6452 // C++ [over.match.oper]p16:
6453 // For every pointer to member type T, there exist candidate operator
6454 // functions of the form
6455 //
6456 // bool operator==(T,T);
6457 // bool operator!=(T,T);
6458 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6459 /// Set of (canonical) types that we've already handled.
6460 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6461
6462 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6463 for (BuiltinCandidateTypeSet::iterator
6464 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6465 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6466 MemPtr != MemPtrEnd;
6467 ++MemPtr) {
6468 // Don't add the same builtin candidate twice.
6469 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6470 continue;
6471
6472 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6473 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6474 CandidateSet);
6475 }
6476 }
6477 }
6478
6479 // C++ [over.built]p15:
6480 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006481 // For every T, where T is an enumeration type, a pointer type, or
6482 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006483 //
6484 // bool operator<(T, T);
6485 // bool operator>(T, T);
6486 // bool operator<=(T, T);
6487 // bool operator>=(T, T);
6488 // bool operator==(T, T);
6489 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006490 void addRelationalPointerOrEnumeralOverloads() {
6491 // C++ [over.built]p1:
6492 // If there is a user-written candidate with the same name and parameter
6493 // types as a built-in candidate operator function, the built-in operator
6494 // function is hidden and is not included in the set of candidate
6495 // functions.
6496 //
6497 // The text is actually in a note, but if we don't implement it then we end
6498 // up with ambiguities when the user provides an overloaded operator for
6499 // an enumeration type. Note that only enumeration types have this problem,
6500 // so we track which enumeration types we've seen operators for. Also, the
6501 // only other overloaded operator with enumeration argumenst, operator=,
6502 // cannot be overloaded for enumeration types, so this is the only place
6503 // where we must suppress candidates like this.
6504 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6505 UserDefinedBinaryOperators;
6506
6507 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6508 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6509 CandidateTypes[ArgIdx].enumeration_end()) {
6510 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6511 CEnd = CandidateSet.end();
6512 C != CEnd; ++C) {
6513 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6514 continue;
6515
6516 QualType FirstParamType =
6517 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6518 QualType SecondParamType =
6519 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6520
6521 // Skip if either parameter isn't of enumeral type.
6522 if (!FirstParamType->isEnumeralType() ||
6523 !SecondParamType->isEnumeralType())
6524 continue;
6525
6526 // Add this operator to the set of known user-defined operators.
6527 UserDefinedBinaryOperators.insert(
6528 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6529 S.Context.getCanonicalType(SecondParamType)));
6530 }
6531 }
6532 }
6533
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006534 /// Set of (canonical) types that we've already handled.
6535 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6536
6537 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6538 for (BuiltinCandidateTypeSet::iterator
6539 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6540 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6541 Ptr != PtrEnd; ++Ptr) {
6542 // Don't add the same builtin candidate twice.
6543 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6544 continue;
6545
6546 QualType ParamTypes[2] = { *Ptr, *Ptr };
6547 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6548 CandidateSet);
6549 }
6550 for (BuiltinCandidateTypeSet::iterator
6551 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6552 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6553 Enum != EnumEnd; ++Enum) {
6554 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6555
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006556 // Don't add the same builtin candidate twice, or if a user defined
6557 // candidate exists.
6558 if (!AddedTypes.insert(CanonType) ||
6559 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6560 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006561 continue;
6562
6563 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006564 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6565 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006566 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006567
6568 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6569 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6570 if (AddedTypes.insert(NullPtrTy) &&
6571 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6572 NullPtrTy))) {
6573 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6574 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6575 CandidateSet);
6576 }
6577 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006578 }
6579 }
6580
6581 // C++ [over.built]p13:
6582 //
6583 // For every cv-qualified or cv-unqualified object type T
6584 // there exist candidate operator functions of the form
6585 //
6586 // T* operator+(T*, ptrdiff_t);
6587 // T& operator[](T*, ptrdiff_t); [BELOW]
6588 // T* operator-(T*, ptrdiff_t);
6589 // T* operator+(ptrdiff_t, T*);
6590 // T& operator[](ptrdiff_t, T*); [BELOW]
6591 //
6592 // C++ [over.built]p14:
6593 //
6594 // For every T, where T is a pointer to object type, there
6595 // exist candidate operator functions of the form
6596 //
6597 // ptrdiff_t operator-(T, T);
6598 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6599 /// Set of (canonical) types that we've already handled.
6600 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6601
6602 for (int Arg = 0; Arg < 2; ++Arg) {
6603 QualType AsymetricParamTypes[2] = {
6604 S.Context.getPointerDiffType(),
6605 S.Context.getPointerDiffType(),
6606 };
6607 for (BuiltinCandidateTypeSet::iterator
6608 Ptr = CandidateTypes[Arg].pointer_begin(),
6609 PtrEnd = CandidateTypes[Arg].pointer_end();
6610 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006611 QualType PointeeTy = (*Ptr)->getPointeeType();
6612 if (!PointeeTy->isObjectType())
6613 continue;
6614
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006615 AsymetricParamTypes[Arg] = *Ptr;
6616 if (Arg == 0 || Op == OO_Plus) {
6617 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6618 // T* operator+(ptrdiff_t, T*);
6619 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6620 CandidateSet);
6621 }
6622 if (Op == OO_Minus) {
6623 // ptrdiff_t operator-(T, T);
6624 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6625 continue;
6626
6627 QualType ParamTypes[2] = { *Ptr, *Ptr };
6628 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6629 Args, 2, CandidateSet);
6630 }
6631 }
6632 }
6633 }
6634
6635 // C++ [over.built]p12:
6636 //
6637 // For every pair of promoted arithmetic types L and R, there
6638 // exist candidate operator functions of the form
6639 //
6640 // LR operator*(L, R);
6641 // LR operator/(L, R);
6642 // LR operator+(L, R);
6643 // LR operator-(L, R);
6644 // bool operator<(L, R);
6645 // bool operator>(L, R);
6646 // bool operator<=(L, R);
6647 // bool operator>=(L, R);
6648 // bool operator==(L, R);
6649 // bool operator!=(L, R);
6650 //
6651 // where LR is the result of the usual arithmetic conversions
6652 // between types L and R.
6653 //
6654 // C++ [over.built]p24:
6655 //
6656 // For every pair of promoted arithmetic types L and R, there exist
6657 // candidate operator functions of the form
6658 //
6659 // LR operator?(bool, L, R);
6660 //
6661 // where LR is the result of the usual arithmetic conversions
6662 // between types L and R.
6663 // Our candidates ignore the first parameter.
6664 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006665 if (!HasArithmeticOrEnumeralCandidateType)
6666 return;
6667
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006668 for (unsigned Left = FirstPromotedArithmeticType;
6669 Left < LastPromotedArithmeticType; ++Left) {
6670 for (unsigned Right = FirstPromotedArithmeticType;
6671 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006672 QualType LandR[2] = { getArithmeticType(Left),
6673 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006674 QualType Result =
6675 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006676 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006677 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6678 }
6679 }
6680
6681 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6682 // conditional operator for vector types.
6683 for (BuiltinCandidateTypeSet::iterator
6684 Vec1 = CandidateTypes[0].vector_begin(),
6685 Vec1End = CandidateTypes[0].vector_end();
6686 Vec1 != Vec1End; ++Vec1) {
6687 for (BuiltinCandidateTypeSet::iterator
6688 Vec2 = CandidateTypes[1].vector_begin(),
6689 Vec2End = CandidateTypes[1].vector_end();
6690 Vec2 != Vec2End; ++Vec2) {
6691 QualType LandR[2] = { *Vec1, *Vec2 };
6692 QualType Result = S.Context.BoolTy;
6693 if (!isComparison) {
6694 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6695 Result = *Vec1;
6696 else
6697 Result = *Vec2;
6698 }
6699
6700 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6701 }
6702 }
6703 }
6704
6705 // C++ [over.built]p17:
6706 //
6707 // For every pair of promoted integral types L and R, there
6708 // exist candidate operator functions of the form
6709 //
6710 // LR operator%(L, R);
6711 // LR operator&(L, R);
6712 // LR operator^(L, R);
6713 // LR operator|(L, R);
6714 // L operator<<(L, R);
6715 // L operator>>(L, R);
6716 //
6717 // where LR is the result of the usual arithmetic conversions
6718 // between types L and R.
6719 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006720 if (!HasArithmeticOrEnumeralCandidateType)
6721 return;
6722
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006723 for (unsigned Left = FirstPromotedIntegralType;
6724 Left < LastPromotedIntegralType; ++Left) {
6725 for (unsigned Right = FirstPromotedIntegralType;
6726 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006727 QualType LandR[2] = { getArithmeticType(Left),
6728 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006729 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6730 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006731 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006732 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6733 }
6734 }
6735 }
6736
6737 // C++ [over.built]p20:
6738 //
6739 // For every pair (T, VQ), where T is an enumeration or
6740 // pointer to member type and VQ is either volatile or
6741 // empty, there exist candidate operator functions of the form
6742 //
6743 // VQ T& operator=(VQ T&, T);
6744 void addAssignmentMemberPointerOrEnumeralOverloads() {
6745 /// Set of (canonical) types that we've already handled.
6746 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6747
6748 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6749 for (BuiltinCandidateTypeSet::iterator
6750 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6751 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6752 Enum != EnumEnd; ++Enum) {
6753 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6754 continue;
6755
6756 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6757 CandidateSet);
6758 }
6759
6760 for (BuiltinCandidateTypeSet::iterator
6761 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6762 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6763 MemPtr != MemPtrEnd; ++MemPtr) {
6764 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6765 continue;
6766
6767 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6768 CandidateSet);
6769 }
6770 }
6771 }
6772
6773 // C++ [over.built]p19:
6774 //
6775 // For every pair (T, VQ), where T is any type and VQ is either
6776 // volatile or empty, there exist candidate operator functions
6777 // of the form
6778 //
6779 // T*VQ& operator=(T*VQ&, T*);
6780 //
6781 // C++ [over.built]p21:
6782 //
6783 // For every pair (T, VQ), where T is a cv-qualified or
6784 // cv-unqualified object type and VQ is either volatile or
6785 // empty, there exist candidate operator functions of the form
6786 //
6787 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6788 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6789 void addAssignmentPointerOverloads(bool isEqualOp) {
6790 /// Set of (canonical) types that we've already handled.
6791 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6792
6793 for (BuiltinCandidateTypeSet::iterator
6794 Ptr = CandidateTypes[0].pointer_begin(),
6795 PtrEnd = CandidateTypes[0].pointer_end();
6796 Ptr != PtrEnd; ++Ptr) {
6797 // If this is operator=, keep track of the builtin candidates we added.
6798 if (isEqualOp)
6799 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006800 else if (!(*Ptr)->getPointeeType()->isObjectType())
6801 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006802
6803 // non-volatile version
6804 QualType ParamTypes[2] = {
6805 S.Context.getLValueReferenceType(*Ptr),
6806 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6807 };
6808 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6809 /*IsAssigmentOperator=*/ isEqualOp);
6810
6811 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6812 VisibleTypeConversionsQuals.hasVolatile()) {
6813 // volatile version
6814 ParamTypes[0] =
6815 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6816 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6817 /*IsAssigmentOperator=*/isEqualOp);
6818 }
6819 }
6820
6821 if (isEqualOp) {
6822 for (BuiltinCandidateTypeSet::iterator
6823 Ptr = CandidateTypes[1].pointer_begin(),
6824 PtrEnd = CandidateTypes[1].pointer_end();
6825 Ptr != PtrEnd; ++Ptr) {
6826 // Make sure we don't add the same candidate twice.
6827 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6828 continue;
6829
Chandler Carruth8e543b32010-12-12 08:17:55 +00006830 QualType ParamTypes[2] = {
6831 S.Context.getLValueReferenceType(*Ptr),
6832 *Ptr,
6833 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006834
6835 // non-volatile version
6836 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6837 /*IsAssigmentOperator=*/true);
6838
6839 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6840 VisibleTypeConversionsQuals.hasVolatile()) {
6841 // volatile version
6842 ParamTypes[0] =
6843 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006844 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6845 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006846 }
6847 }
6848 }
6849 }
6850
6851 // C++ [over.built]p18:
6852 //
6853 // For every triple (L, VQ, R), where L is an arithmetic type,
6854 // VQ is either volatile or empty, and R is a promoted
6855 // arithmetic type, there exist candidate operator functions of
6856 // the form
6857 //
6858 // VQ L& operator=(VQ L&, R);
6859 // VQ L& operator*=(VQ L&, R);
6860 // VQ L& operator/=(VQ L&, R);
6861 // VQ L& operator+=(VQ L&, R);
6862 // VQ L& operator-=(VQ L&, R);
6863 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006864 if (!HasArithmeticOrEnumeralCandidateType)
6865 return;
6866
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006867 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6868 for (unsigned Right = FirstPromotedArithmeticType;
6869 Right < LastPromotedArithmeticType; ++Right) {
6870 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006871 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006872
6873 // Add this built-in operator as a candidate (VQ is empty).
6874 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006875 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006876 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6877 /*IsAssigmentOperator=*/isEqualOp);
6878
6879 // Add this built-in operator as a candidate (VQ is 'volatile').
6880 if (VisibleTypeConversionsQuals.hasVolatile()) {
6881 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006882 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006883 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006884 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6885 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006886 /*IsAssigmentOperator=*/isEqualOp);
6887 }
6888 }
6889 }
6890
6891 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6892 for (BuiltinCandidateTypeSet::iterator
6893 Vec1 = CandidateTypes[0].vector_begin(),
6894 Vec1End = CandidateTypes[0].vector_end();
6895 Vec1 != Vec1End; ++Vec1) {
6896 for (BuiltinCandidateTypeSet::iterator
6897 Vec2 = CandidateTypes[1].vector_begin(),
6898 Vec2End = CandidateTypes[1].vector_end();
6899 Vec2 != Vec2End; ++Vec2) {
6900 QualType ParamTypes[2];
6901 ParamTypes[1] = *Vec2;
6902 // Add this built-in operator as a candidate (VQ is empty).
6903 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6904 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6905 /*IsAssigmentOperator=*/isEqualOp);
6906
6907 // Add this built-in operator as a candidate (VQ is 'volatile').
6908 if (VisibleTypeConversionsQuals.hasVolatile()) {
6909 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6910 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006911 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6912 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006913 /*IsAssigmentOperator=*/isEqualOp);
6914 }
6915 }
6916 }
6917 }
6918
6919 // C++ [over.built]p22:
6920 //
6921 // For every triple (L, VQ, R), where L is an integral type, VQ
6922 // is either volatile or empty, and R is a promoted integral
6923 // type, there exist candidate operator functions of the form
6924 //
6925 // VQ L& operator%=(VQ L&, R);
6926 // VQ L& operator<<=(VQ L&, R);
6927 // VQ L& operator>>=(VQ L&, R);
6928 // VQ L& operator&=(VQ L&, R);
6929 // VQ L& operator^=(VQ L&, R);
6930 // VQ L& operator|=(VQ L&, R);
6931 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006932 if (!HasArithmeticOrEnumeralCandidateType)
6933 return;
6934
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006935 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6936 for (unsigned Right = FirstPromotedIntegralType;
6937 Right < LastPromotedIntegralType; ++Right) {
6938 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006939 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006940
6941 // Add this built-in operator as a candidate (VQ is empty).
6942 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006943 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006944 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6945 if (VisibleTypeConversionsQuals.hasVolatile()) {
6946 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006947 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006948 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6949 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6950 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6951 CandidateSet);
6952 }
6953 }
6954 }
6955 }
6956
6957 // C++ [over.operator]p23:
6958 //
6959 // There also exist candidate operator functions of the form
6960 //
6961 // bool operator!(bool);
6962 // bool operator&&(bool, bool);
6963 // bool operator||(bool, bool);
6964 void addExclaimOverload() {
6965 QualType ParamTy = S.Context.BoolTy;
6966 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6967 /*IsAssignmentOperator=*/false,
6968 /*NumContextualBoolArguments=*/1);
6969 }
6970 void addAmpAmpOrPipePipeOverload() {
6971 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6972 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6973 /*IsAssignmentOperator=*/false,
6974 /*NumContextualBoolArguments=*/2);
6975 }
6976
6977 // C++ [over.built]p13:
6978 //
6979 // For every cv-qualified or cv-unqualified object type T there
6980 // exist candidate operator functions of the form
6981 //
6982 // T* operator+(T*, ptrdiff_t); [ABOVE]
6983 // T& operator[](T*, ptrdiff_t);
6984 // T* operator-(T*, ptrdiff_t); [ABOVE]
6985 // T* operator+(ptrdiff_t, T*); [ABOVE]
6986 // T& operator[](ptrdiff_t, T*);
6987 void addSubscriptOverloads() {
6988 for (BuiltinCandidateTypeSet::iterator
6989 Ptr = CandidateTypes[0].pointer_begin(),
6990 PtrEnd = CandidateTypes[0].pointer_end();
6991 Ptr != PtrEnd; ++Ptr) {
6992 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6993 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006994 if (!PointeeType->isObjectType())
6995 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006996
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006997 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6998
6999 // T& operator[](T*, ptrdiff_t)
7000 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7001 }
7002
7003 for (BuiltinCandidateTypeSet::iterator
7004 Ptr = CandidateTypes[1].pointer_begin(),
7005 PtrEnd = CandidateTypes[1].pointer_end();
7006 Ptr != PtrEnd; ++Ptr) {
7007 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7008 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007009 if (!PointeeType->isObjectType())
7010 continue;
7011
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007012 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7013
7014 // T& operator[](ptrdiff_t, T*)
7015 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7016 }
7017 }
7018
7019 // C++ [over.built]p11:
7020 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7021 // C1 is the same type as C2 or is a derived class of C2, T is an object
7022 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7023 // there exist candidate operator functions of the form
7024 //
7025 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7026 //
7027 // where CV12 is the union of CV1 and CV2.
7028 void addArrowStarOverloads() {
7029 for (BuiltinCandidateTypeSet::iterator
7030 Ptr = CandidateTypes[0].pointer_begin(),
7031 PtrEnd = CandidateTypes[0].pointer_end();
7032 Ptr != PtrEnd; ++Ptr) {
7033 QualType C1Ty = (*Ptr);
7034 QualType C1;
7035 QualifierCollector Q1;
7036 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7037 if (!isa<RecordType>(C1))
7038 continue;
7039 // heuristic to reduce number of builtin candidates in the set.
7040 // Add volatile/restrict version only if there are conversions to a
7041 // volatile/restrict type.
7042 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7043 continue;
7044 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7045 continue;
7046 for (BuiltinCandidateTypeSet::iterator
7047 MemPtr = CandidateTypes[1].member_pointer_begin(),
7048 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7049 MemPtr != MemPtrEnd; ++MemPtr) {
7050 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7051 QualType C2 = QualType(mptr->getClass(), 0);
7052 C2 = C2.getUnqualifiedType();
7053 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7054 break;
7055 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7056 // build CV12 T&
7057 QualType T = mptr->getPointeeType();
7058 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7059 T.isVolatileQualified())
7060 continue;
7061 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7062 T.isRestrictQualified())
7063 continue;
7064 T = Q1.apply(S.Context, T);
7065 QualType ResultTy = S.Context.getLValueReferenceType(T);
7066 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7067 }
7068 }
7069 }
7070
7071 // Note that we don't consider the first argument, since it has been
7072 // contextually converted to bool long ago. The candidates below are
7073 // therefore added as binary.
7074 //
7075 // C++ [over.built]p25:
7076 // For every type T, where T is a pointer, pointer-to-member, or scoped
7077 // enumeration type, there exist candidate operator functions of the form
7078 //
7079 // T operator?(bool, T, T);
7080 //
7081 void addConditionalOperatorOverloads() {
7082 /// Set of (canonical) types that we've already handled.
7083 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7084
7085 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7086 for (BuiltinCandidateTypeSet::iterator
7087 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7088 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7089 Ptr != PtrEnd; ++Ptr) {
7090 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7091 continue;
7092
7093 QualType ParamTypes[2] = { *Ptr, *Ptr };
7094 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7095 }
7096
7097 for (BuiltinCandidateTypeSet::iterator
7098 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7099 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7100 MemPtr != MemPtrEnd; ++MemPtr) {
7101 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7102 continue;
7103
7104 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7105 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7106 }
7107
7108 if (S.getLangOptions().CPlusPlus0x) {
7109 for (BuiltinCandidateTypeSet::iterator
7110 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7111 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7112 Enum != EnumEnd; ++Enum) {
7113 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7114 continue;
7115
7116 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7117 continue;
7118
7119 QualType ParamTypes[2] = { *Enum, *Enum };
7120 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7121 }
7122 }
7123 }
7124 }
7125};
7126
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007127} // end anonymous namespace
7128
7129/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7130/// operator overloads to the candidate set (C++ [over.built]), based
7131/// on the operator @p Op and the arguments given. For example, if the
7132/// operator is a binary '+', this routine might add "int
7133/// operator+(int, int)" to cover integer addition.
7134void
7135Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7136 SourceLocation OpLoc,
7137 Expr **Args, unsigned NumArgs,
7138 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007139 // Find all of the types that the arguments can convert to, but only
7140 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007141 // that make use of these types. Also record whether we encounter non-record
7142 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007143 Qualifiers VisibleTypeConversionsQuals;
7144 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007145 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7146 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007147
7148 bool HasNonRecordCandidateType = false;
7149 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007150 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007151 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7152 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7153 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7154 OpLoc,
7155 true,
7156 (Op == OO_Exclaim ||
7157 Op == OO_AmpAmp ||
7158 Op == OO_PipePipe),
7159 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007160 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7161 CandidateTypes[ArgIdx].hasNonRecordTypes();
7162 HasArithmeticOrEnumeralCandidateType =
7163 HasArithmeticOrEnumeralCandidateType ||
7164 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007165 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007166
Chandler Carruth00a38332010-12-13 01:44:01 +00007167 // Exit early when no non-record types have been added to the candidate set
7168 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007169 //
7170 // We can't exit early for !, ||, or &&, since there we have always have
7171 // 'bool' overloads.
7172 if (!HasNonRecordCandidateType &&
7173 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007174 return;
7175
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007176 // Setup an object to manage the common state for building overloads.
7177 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7178 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007179 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007180 CandidateTypes, CandidateSet);
7181
7182 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007183 switch (Op) {
7184 case OO_None:
7185 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007186 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007187
Chandler Carruth5184de02010-12-12 08:51:33 +00007188 case OO_New:
7189 case OO_Delete:
7190 case OO_Array_New:
7191 case OO_Array_Delete:
7192 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007193 llvm_unreachable(
7194 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007195
7196 case OO_Comma:
7197 case OO_Arrow:
7198 // C++ [over.match.oper]p3:
7199 // -- For the operator ',', the unary operator '&', or the
7200 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007201 break;
7202
7203 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007204 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007205 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007206 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007207
7208 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007209 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007210 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007211 } else {
7212 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7213 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7214 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007215 break;
7216
Chandler Carruth5184de02010-12-12 08:51:33 +00007217 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007218 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007219 OpBuilder.addUnaryStarPointerOverloads();
7220 else
7221 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7222 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007223
Chandler Carruth5184de02010-12-12 08:51:33 +00007224 case OO_Slash:
7225 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007226 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007227
7228 case OO_PlusPlus:
7229 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007230 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7231 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007232 break;
7233
Douglas Gregor84605ae2009-08-24 13:43:27 +00007234 case OO_EqualEqual:
7235 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007236 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007237 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007238
Douglas Gregora11693b2008-11-12 17:17:38 +00007239 case OO_Less:
7240 case OO_Greater:
7241 case OO_LessEqual:
7242 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007243 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007244 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7245 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007246
Douglas Gregora11693b2008-11-12 17:17:38 +00007247 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007248 case OO_Caret:
7249 case OO_Pipe:
7250 case OO_LessLess:
7251 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007252 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007253 break;
7254
Chandler Carruth5184de02010-12-12 08:51:33 +00007255 case OO_Amp: // '&' is either unary or binary
7256 if (NumArgs == 1)
7257 // C++ [over.match.oper]p3:
7258 // -- For the operator ',', the unary operator '&', or the
7259 // operator '->', the built-in candidates set is empty.
7260 break;
7261
7262 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7263 break;
7264
7265 case OO_Tilde:
7266 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7267 break;
7268
Douglas Gregora11693b2008-11-12 17:17:38 +00007269 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007270 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007271 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007272
7273 case OO_PlusEqual:
7274 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007275 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007276 // Fall through.
7277
7278 case OO_StarEqual:
7279 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007280 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007281 break;
7282
7283 case OO_PercentEqual:
7284 case OO_LessLessEqual:
7285 case OO_GreaterGreaterEqual:
7286 case OO_AmpEqual:
7287 case OO_CaretEqual:
7288 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007289 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007290 break;
7291
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007292 case OO_Exclaim:
7293 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007294 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007295
Douglas Gregora11693b2008-11-12 17:17:38 +00007296 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007297 case OO_PipePipe:
7298 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007299 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007300
7301 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007302 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007303 break;
7304
7305 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007306 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007307 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007308
7309 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007310 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007311 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7312 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007313 }
7314}
7315
Douglas Gregore254f902009-02-04 00:32:51 +00007316/// \brief Add function candidates found via argument-dependent lookup
7317/// to the set of overloading candidates.
7318///
7319/// This routine performs argument-dependent name lookup based on the
7320/// given function name (which may also be an operator name) and adds
7321/// all of the overload candidates found by ADL to the overload
7322/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007323void
Douglas Gregore254f902009-02-04 00:32:51 +00007324Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00007325 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00007326 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007327 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007328 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007329 bool PartialOverloading,
7330 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007331 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007332
John McCall91f61fc2010-01-26 06:04:06 +00007333 // FIXME: This approach for uniquing ADL results (and removing
7334 // redundant candidates from the set) relies on pointer-equality,
7335 // which means we need to key off the canonical decl. However,
7336 // always going back to the canonical decl might not get us the
7337 // right set of default arguments. What default arguments are
7338 // we supposed to consider on ADL candidates, anyway?
7339
Douglas Gregorcabea402009-09-22 15:41:20 +00007340 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00007341 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
7342 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007343
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007344 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007345 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7346 CandEnd = CandidateSet.end();
7347 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007348 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007349 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007350 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007351 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007352 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007353
7354 // For each of the ADL candidates we found, add it to the overload
7355 // set.
John McCall8fe68082010-01-26 07:16:45 +00007356 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007357 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007359 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007360 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007361
John McCalla0296f72010-03-19 07:35:19 +00007362 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007363 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007364 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007365 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007366 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00007367 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007368 }
Douglas Gregore254f902009-02-04 00:32:51 +00007369}
7370
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007371/// isBetterOverloadCandidate - Determines whether the first overload
7372/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007373bool
John McCall5c32be02010-08-24 20:38:10 +00007374isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007375 const OverloadCandidate &Cand1,
7376 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007377 SourceLocation Loc,
7378 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007379 // Define viable functions to be better candidates than non-viable
7380 // functions.
7381 if (!Cand2.Viable)
7382 return Cand1.Viable;
7383 else if (!Cand1.Viable)
7384 return false;
7385
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007386 // C++ [over.match.best]p1:
7387 //
7388 // -- if F is a static member function, ICS1(F) is defined such
7389 // that ICS1(F) is neither better nor worse than ICS1(G) for
7390 // any function G, and, symmetrically, ICS1(G) is neither
7391 // better nor worse than ICS1(F).
7392 unsigned StartArg = 0;
7393 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7394 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007395
Douglas Gregord3cb3562009-07-07 23:38:56 +00007396 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007397 // A viable function F1 is defined to be a better function than another
7398 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007399 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007400 unsigned NumArgs = Cand1.NumConversions;
7401 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007402 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007403 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007404 switch (CompareImplicitConversionSequences(S,
7405 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007406 Cand2.Conversions[ArgIdx])) {
7407 case ImplicitConversionSequence::Better:
7408 // Cand1 has a better conversion sequence.
7409 HasBetterConversion = true;
7410 break;
7411
7412 case ImplicitConversionSequence::Worse:
7413 // Cand1 can't be better than Cand2.
7414 return false;
7415
7416 case ImplicitConversionSequence::Indistinguishable:
7417 // Do nothing.
7418 break;
7419 }
7420 }
7421
Mike Stump11289f42009-09-09 15:08:12 +00007422 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007423 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007424 if (HasBetterConversion)
7425 return true;
7426
Mike Stump11289f42009-09-09 15:08:12 +00007427 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007428 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007429 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007430 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7431 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007432
7433 // -- F1 and F2 are function template specializations, and the function
7434 // template for F1 is more specialized than the template for F2
7435 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007436 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007437 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007438 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007439 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007440 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7441 Cand2.Function->getPrimaryTemplate(),
7442 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007443 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007444 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007445 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007446 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007448
Douglas Gregora1f013e2008-11-07 22:36:19 +00007449 // -- the context is an initialization by user-defined conversion
7450 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7451 // from the return type of F1 to the destination type (i.e.,
7452 // the type of the entity being initialized) is a better
7453 // conversion sequence than the standard conversion sequence
7454 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007455 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007456 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007457 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007458 switch (CompareStandardConversionSequences(S,
7459 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007460 Cand2.FinalConversion)) {
7461 case ImplicitConversionSequence::Better:
7462 // Cand1 has a better conversion sequence.
7463 return true;
7464
7465 case ImplicitConversionSequence::Worse:
7466 // Cand1 can't be better than Cand2.
7467 return false;
7468
7469 case ImplicitConversionSequence::Indistinguishable:
7470 // Do nothing
7471 break;
7472 }
7473 }
7474
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007475 return false;
7476}
7477
Mike Stump11289f42009-09-09 15:08:12 +00007478/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007479/// within an overload candidate set.
7480///
7481/// \param CandidateSet the set of candidate functions.
7482///
7483/// \param Loc the location of the function name (or operator symbol) for
7484/// which overload resolution occurs.
7485///
Mike Stump11289f42009-09-09 15:08:12 +00007486/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007487/// function, Best points to the candidate function found.
7488///
7489/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007490OverloadingResult
7491OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007492 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007493 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007494 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007495 Best = end();
7496 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7497 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007498 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007499 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007500 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007501 }
7502
7503 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007504 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007505 return OR_No_Viable_Function;
7506
7507 // Make sure that this function is better than every other viable
7508 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007509 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007510 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007511 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007512 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007513 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007514 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007515 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007516 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007517 }
Mike Stump11289f42009-09-09 15:08:12 +00007518
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007519 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007520 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007521 (Best->Function->isDeleted() ||
7522 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007523 return OR_Deleted;
7524
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007525 return OR_Success;
7526}
7527
John McCall53262c92010-01-12 02:15:36 +00007528namespace {
7529
7530enum OverloadCandidateKind {
7531 oc_function,
7532 oc_method,
7533 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007534 oc_function_template,
7535 oc_method_template,
7536 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007537 oc_implicit_default_constructor,
7538 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007539 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007540 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007541 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007542 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007543};
7544
John McCalle1ac8d12010-01-13 00:25:19 +00007545OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7546 FunctionDecl *Fn,
7547 std::string &Description) {
7548 bool isTemplate = false;
7549
7550 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7551 isTemplate = true;
7552 Description = S.getTemplateArgumentBindingsText(
7553 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7554 }
John McCallfd0b2f82010-01-06 09:43:14 +00007555
7556 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007557 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007558 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007559
Sebastian Redl08905022011-02-05 19:23:19 +00007560 if (Ctor->getInheritedConstructor())
7561 return oc_implicit_inherited_constructor;
7562
Alexis Hunt119c10e2011-05-25 23:16:36 +00007563 if (Ctor->isDefaultConstructor())
7564 return oc_implicit_default_constructor;
7565
7566 if (Ctor->isMoveConstructor())
7567 return oc_implicit_move_constructor;
7568
7569 assert(Ctor->isCopyConstructor() &&
7570 "unexpected sort of implicit constructor");
7571 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007572 }
7573
7574 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7575 // This actually gets spelled 'candidate function' for now, but
7576 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007577 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007578 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007579
Alexis Hunt119c10e2011-05-25 23:16:36 +00007580 if (Meth->isMoveAssignmentOperator())
7581 return oc_implicit_move_assignment;
7582
Douglas Gregorec3bec02010-09-27 22:37:28 +00007583 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007584 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007585 return oc_implicit_copy_assignment;
7586 }
7587
John McCalle1ac8d12010-01-13 00:25:19 +00007588 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007589}
7590
Sebastian Redl08905022011-02-05 19:23:19 +00007591void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7592 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7593 if (!Ctor) return;
7594
7595 Ctor = Ctor->getInheritedConstructor();
7596 if (!Ctor) return;
7597
7598 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7599}
7600
John McCall53262c92010-01-12 02:15:36 +00007601} // end anonymous namespace
7602
7603// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007604void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007605 std::string FnDesc;
7606 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007607 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7608 << (unsigned) K << FnDesc;
7609 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7610 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007611 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007612}
7613
Douglas Gregorb491ed32011-02-19 21:32:49 +00007614//Notes the location of all overload candidates designated through
7615// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007616void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007617 assert(OverloadedExpr->getType() == Context.OverloadTy);
7618
7619 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7620 OverloadExpr *OvlExpr = Ovl.Expression;
7621
7622 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7623 IEnd = OvlExpr->decls_end();
7624 I != IEnd; ++I) {
7625 if (FunctionTemplateDecl *FunTmpl =
7626 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007627 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007628 } else if (FunctionDecl *Fun
7629 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007630 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007631 }
7632 }
7633}
7634
John McCall0d1da222010-01-12 00:44:57 +00007635/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7636/// "lead" diagnostic; it will be given two arguments, the source and
7637/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007638void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7639 Sema &S,
7640 SourceLocation CaretLoc,
7641 const PartialDiagnostic &PDiag) const {
7642 S.Diag(CaretLoc, PDiag)
7643 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007644 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007645 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7646 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007647 }
John McCall12f97bc2010-01-08 04:41:39 +00007648}
7649
John McCall0d1da222010-01-12 00:44:57 +00007650namespace {
7651
John McCall6a61b522010-01-13 09:16:55 +00007652void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7653 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7654 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007655 assert(Cand->Function && "for now, candidate must be a function");
7656 FunctionDecl *Fn = Cand->Function;
7657
7658 // There's a conversion slot for the object argument if this is a
7659 // non-constructor method. Note that 'I' corresponds the
7660 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007661 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007662 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007663 if (I == 0)
7664 isObjectArgument = true;
7665 else
7666 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007667 }
7668
John McCalle1ac8d12010-01-13 00:25:19 +00007669 std::string FnDesc;
7670 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7671
John McCall6a61b522010-01-13 09:16:55 +00007672 Expr *FromExpr = Conv.Bad.FromExpr;
7673 QualType FromTy = Conv.Bad.getFromType();
7674 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007675
John McCallfb7ad0f2010-02-02 02:42:52 +00007676 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007677 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007678 Expr *E = FromExpr->IgnoreParens();
7679 if (isa<UnaryOperator>(E))
7680 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007681 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007682
7683 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7684 << (unsigned) FnKind << FnDesc
7685 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7686 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007687 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007688 return;
7689 }
7690
John McCall6d174642010-01-23 08:10:49 +00007691 // Do some hand-waving analysis to see if the non-viability is due
7692 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007693 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7694 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7695 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7696 CToTy = RT->getPointeeType();
7697 else {
7698 // TODO: detect and diagnose the full richness of const mismatches.
7699 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7700 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7701 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7702 }
7703
7704 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7705 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7706 // It is dumb that we have to do this here.
7707 while (isa<ArrayType>(CFromTy))
7708 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7709 while (isa<ArrayType>(CToTy))
7710 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7711
7712 Qualifiers FromQs = CFromTy.getQualifiers();
7713 Qualifiers ToQs = CToTy.getQualifiers();
7714
7715 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7716 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7717 << (unsigned) FnKind << FnDesc
7718 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7719 << FromTy
7720 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7721 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007722 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007723 return;
7724 }
7725
John McCall31168b02011-06-15 23:02:42 +00007726 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007727 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007728 << (unsigned) FnKind << FnDesc
7729 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7730 << FromTy
7731 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7732 << (unsigned) isObjectArgument << I+1;
7733 MaybeEmitInheritedConstructorNote(S, Fn);
7734 return;
7735 }
7736
Douglas Gregoraec25842011-04-26 23:16:46 +00007737 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7738 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7739 << (unsigned) FnKind << FnDesc
7740 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7741 << FromTy
7742 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7743 << (unsigned) isObjectArgument << I+1;
7744 MaybeEmitInheritedConstructorNote(S, Fn);
7745 return;
7746 }
7747
John McCall47000992010-01-14 03:28:57 +00007748 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7749 assert(CVR && "unexpected qualifiers mismatch");
7750
7751 if (isObjectArgument) {
7752 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7753 << (unsigned) FnKind << FnDesc
7754 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7755 << FromTy << (CVR - 1);
7756 } else {
7757 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7758 << (unsigned) FnKind << FnDesc
7759 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7760 << FromTy << (CVR - 1) << I+1;
7761 }
Sebastian Redl08905022011-02-05 19:23:19 +00007762 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007763 return;
7764 }
7765
Sebastian Redla72462c2011-09-24 17:48:32 +00007766 // Special diagnostic for failure to convert an initializer list, since
7767 // telling the user that it has type void is not useful.
7768 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7769 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7770 << (unsigned) FnKind << FnDesc
7771 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7772 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7773 MaybeEmitInheritedConstructorNote(S, Fn);
7774 return;
7775 }
7776
John McCall6d174642010-01-23 08:10:49 +00007777 // Diagnose references or pointers to incomplete types differently,
7778 // since it's far from impossible that the incompleteness triggered
7779 // the failure.
7780 QualType TempFromTy = FromTy.getNonReferenceType();
7781 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7782 TempFromTy = PTy->getPointeeType();
7783 if (TempFromTy->isIncompleteType()) {
7784 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7785 << (unsigned) FnKind << FnDesc
7786 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7787 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007788 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007789 return;
7790 }
7791
Douglas Gregor56f2e342010-06-30 23:01:39 +00007792 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007793 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007794 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7795 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7796 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7797 FromPtrTy->getPointeeType()) &&
7798 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7799 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007800 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007801 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007802 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007803 }
7804 } else if (const ObjCObjectPointerType *FromPtrTy
7805 = FromTy->getAs<ObjCObjectPointerType>()) {
7806 if (const ObjCObjectPointerType *ToPtrTy
7807 = ToTy->getAs<ObjCObjectPointerType>())
7808 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7809 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7810 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7811 FromPtrTy->getPointeeType()) &&
7812 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007813 BaseToDerivedConversion = 2;
7814 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7815 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7816 !FromTy->isIncompleteType() &&
7817 !ToRefTy->getPointeeType()->isIncompleteType() &&
7818 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7819 BaseToDerivedConversion = 3;
7820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007821
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007822 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007823 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007824 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007825 << (unsigned) FnKind << FnDesc
7826 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007827 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007828 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007829 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007830 return;
7831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007832
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007833 if (isa<ObjCObjectPointerType>(CFromTy) &&
7834 isa<PointerType>(CToTy)) {
7835 Qualifiers FromQs = CFromTy.getQualifiers();
7836 Qualifiers ToQs = CToTy.getQualifiers();
7837 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7838 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7839 << (unsigned) FnKind << FnDesc
7840 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7841 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7842 MaybeEmitInheritedConstructorNote(S, Fn);
7843 return;
7844 }
7845 }
7846
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007847 // Emit the generic diagnostic and, optionally, add the hints to it.
7848 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7849 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007850 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007851 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7852 << (unsigned) (Cand->Fix.Kind);
7853
7854 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00007855 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7856 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007857 FDiag << *HI;
7858 S.Diag(Fn->getLocation(), FDiag);
7859
Sebastian Redl08905022011-02-05 19:23:19 +00007860 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007861}
7862
7863void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7864 unsigned NumFormalArgs) {
7865 // TODO: treat calls to a missing default constructor as a special case
7866
7867 FunctionDecl *Fn = Cand->Function;
7868 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7869
7870 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007871
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007872 // With invalid overloaded operators, it's possible that we think we
7873 // have an arity mismatch when it fact it looks like we have the
7874 // right number of arguments, because only overloaded operators have
7875 // the weird behavior of overloading member and non-member functions.
7876 // Just don't report anything.
7877 if (Fn->isInvalidDecl() &&
7878 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7879 return;
7880
John McCall6a61b522010-01-13 09:16:55 +00007881 // at least / at most / exactly
7882 unsigned mode, modeCount;
7883 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007884 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7885 (Cand->FailureKind == ovl_fail_bad_deduction &&
7886 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007887 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007888 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007889 mode = 0; // "at least"
7890 else
7891 mode = 2; // "exactly"
7892 modeCount = MinParams;
7893 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007894 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7895 (Cand->FailureKind == ovl_fail_bad_deduction &&
7896 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007897 if (MinParams != FnTy->getNumArgs())
7898 mode = 1; // "at most"
7899 else
7900 mode = 2; // "exactly"
7901 modeCount = FnTy->getNumArgs();
7902 }
7903
7904 std::string Description;
7905 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7906
7907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007908 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007909 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007910 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007911}
7912
John McCall8b9ed552010-02-01 18:53:26 +00007913/// Diagnose a failed template-argument deduction.
7914void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7915 Expr **Args, unsigned NumArgs) {
7916 FunctionDecl *Fn = Cand->Function; // pattern
7917
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007918 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007919 NamedDecl *ParamD;
7920 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7921 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7922 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007923 switch (Cand->DeductionFailure.Result) {
7924 case Sema::TDK_Success:
7925 llvm_unreachable("TDK_success while diagnosing bad deduction");
7926
7927 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007928 assert(ParamD && "no parameter found for incomplete deduction result");
7929 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7930 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007931 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007932 return;
7933 }
7934
John McCall42d7d192010-08-05 09:05:08 +00007935 case Sema::TDK_Underqualified: {
7936 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7937 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7938
7939 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7940
7941 // Param will have been canonicalized, but it should just be a
7942 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007943 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007944 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007945 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007946 assert(S.Context.hasSameType(Param, NonCanonParam));
7947
7948 // Arg has also been canonicalized, but there's nothing we can do
7949 // about that. It also doesn't matter as much, because it won't
7950 // have any template parameters in it (because deduction isn't
7951 // done on dependent types).
7952 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7953
7954 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7955 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007956 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007957 return;
7958 }
7959
7960 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007961 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007962 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007963 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007964 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007965 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007966 which = 1;
7967 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007968 which = 2;
7969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007970
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007972 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007973 << *Cand->DeductionFailure.getFirstArg()
7974 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007975 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007976 return;
7977 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007978
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007979 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007980 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007981 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007983 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7984 << ParamD->getDeclName();
7985 else {
7986 int index = 0;
7987 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7988 index = TTP->getIndex();
7989 else if (NonTypeTemplateParmDecl *NTTP
7990 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7991 index = NTTP->getIndex();
7992 else
7993 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007994 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007995 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7996 << (index + 1);
7997 }
Sebastian Redl08905022011-02-05 19:23:19 +00007998 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007999 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008000
Douglas Gregor02eb4832010-05-08 18:13:28 +00008001 case Sema::TDK_TooManyArguments:
8002 case Sema::TDK_TooFewArguments:
8003 DiagnoseArityMismatch(S, Cand, NumArgs);
8004 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008005
8006 case Sema::TDK_InstantiationDepth:
8007 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008008 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008009 return;
8010
8011 case Sema::TDK_SubstitutionFailure: {
8012 std::string ArgString;
8013 if (TemplateArgumentList *Args
8014 = Cand->DeductionFailure.getTemplateArgumentList())
8015 ArgString = S.getTemplateArgumentBindingsText(
8016 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8017 *Args);
8018 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8019 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00008020 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008021 return;
8022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008023
John McCall8b9ed552010-02-01 18:53:26 +00008024 // TODO: diagnose these individually, then kill off
8025 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008026 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008027 case Sema::TDK_FailedOverloadResolution:
8028 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008029 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008030 return;
8031 }
8032}
8033
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008034/// CUDA: diagnose an invalid call across targets.
8035void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8036 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8037 FunctionDecl *Callee = Cand->Function;
8038
8039 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8040 CalleeTarget = S.IdentifyCUDATarget(Callee);
8041
8042 std::string FnDesc;
8043 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8044
8045 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8046 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8047}
8048
John McCall8b9ed552010-02-01 18:53:26 +00008049/// Generates a 'note' diagnostic for an overload candidate. We've
8050/// already generated a primary error at the call site.
8051///
8052/// It really does need to be a single diagnostic with its caret
8053/// pointed at the candidate declaration. Yes, this creates some
8054/// major challenges of technical writing. Yes, this makes pointing
8055/// out problems with specific arguments quite awkward. It's still
8056/// better than generating twenty screens of text for every failed
8057/// overload.
8058///
8059/// It would be great to be able to express per-candidate problems
8060/// more richly for those diagnostic clients that cared, but we'd
8061/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008062void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8063 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008064 FunctionDecl *Fn = Cand->Function;
8065
John McCall12f97bc2010-01-08 04:41:39 +00008066 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008067 if (Cand->Viable && (Fn->isDeleted() ||
8068 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008069 std::string FnDesc;
8070 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008071
8072 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00008073 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00008074 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008075 return;
John McCall12f97bc2010-01-08 04:41:39 +00008076 }
8077
John McCalle1ac8d12010-01-13 00:25:19 +00008078 // We don't really have anything else to say about viable candidates.
8079 if (Cand->Viable) {
8080 S.NoteOverloadCandidate(Fn);
8081 return;
8082 }
John McCall0d1da222010-01-12 00:44:57 +00008083
John McCall6a61b522010-01-13 09:16:55 +00008084 switch (Cand->FailureKind) {
8085 case ovl_fail_too_many_arguments:
8086 case ovl_fail_too_few_arguments:
8087 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008088
John McCall6a61b522010-01-13 09:16:55 +00008089 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00008090 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
8091
John McCallfe796dd2010-01-23 05:17:32 +00008092 case ovl_fail_trivial_conversion:
8093 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008094 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008095 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008096
John McCall65eb8792010-02-25 01:37:24 +00008097 case ovl_fail_bad_conversion: {
8098 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008099 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008100 if (Cand->Conversions[I].isBad())
8101 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008102
John McCall6a61b522010-01-13 09:16:55 +00008103 // FIXME: this currently happens when we're called from SemaInit
8104 // when user-conversion overload fails. Figure out how to handle
8105 // those conditions and diagnose them well.
8106 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008107 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008108
8109 case ovl_fail_bad_target:
8110 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008111 }
John McCalld3224162010-01-08 00:58:21 +00008112}
8113
8114void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8115 // Desugar the type of the surrogate down to a function type,
8116 // retaining as many typedefs as possible while still showing
8117 // the function type (and, therefore, its parameter types).
8118 QualType FnType = Cand->Surrogate->getConversionType();
8119 bool isLValueReference = false;
8120 bool isRValueReference = false;
8121 bool isPointer = false;
8122 if (const LValueReferenceType *FnTypeRef =
8123 FnType->getAs<LValueReferenceType>()) {
8124 FnType = FnTypeRef->getPointeeType();
8125 isLValueReference = true;
8126 } else if (const RValueReferenceType *FnTypeRef =
8127 FnType->getAs<RValueReferenceType>()) {
8128 FnType = FnTypeRef->getPointeeType();
8129 isRValueReference = true;
8130 }
8131 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8132 FnType = FnTypePtr->getPointeeType();
8133 isPointer = true;
8134 }
8135 // Desugar down to a function type.
8136 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8137 // Reconstruct the pointer/reference as appropriate.
8138 if (isPointer) FnType = S.Context.getPointerType(FnType);
8139 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8140 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8141
8142 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8143 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008144 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008145}
8146
8147void NoteBuiltinOperatorCandidate(Sema &S,
8148 const char *Opc,
8149 SourceLocation OpLoc,
8150 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008151 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008152 std::string TypeStr("operator");
8153 TypeStr += Opc;
8154 TypeStr += "(";
8155 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008156 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008157 TypeStr += ")";
8158 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8159 } else {
8160 TypeStr += ", ";
8161 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8162 TypeStr += ")";
8163 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8164 }
8165}
8166
8167void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8168 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008169 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008170 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8171 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008172 if (ICS.isBad()) break; // all meaningless after first invalid
8173 if (!ICS.isAmbiguous()) continue;
8174
John McCall5c32be02010-08-24 20:38:10 +00008175 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008176 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008177 }
8178}
8179
John McCall3712d9e2010-01-15 23:32:50 +00008180SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8181 if (Cand->Function)
8182 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008183 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008184 return Cand->Surrogate->getLocation();
8185 return SourceLocation();
8186}
8187
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008188static unsigned
8189RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008190 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008191 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008192 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008193
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008194 case Sema::TDK_Incomplete:
8195 return 1;
8196
8197 case Sema::TDK_Underqualified:
8198 case Sema::TDK_Inconsistent:
8199 return 2;
8200
8201 case Sema::TDK_SubstitutionFailure:
8202 case Sema::TDK_NonDeducedMismatch:
8203 return 3;
8204
8205 case Sema::TDK_InstantiationDepth:
8206 case Sema::TDK_FailedOverloadResolution:
8207 return 4;
8208
8209 case Sema::TDK_InvalidExplicitArguments:
8210 return 5;
8211
8212 case Sema::TDK_TooManyArguments:
8213 case Sema::TDK_TooFewArguments:
8214 return 6;
8215 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008216 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008217}
8218
John McCallad2587a2010-01-12 00:48:53 +00008219struct CompareOverloadCandidatesForDisplay {
8220 Sema &S;
8221 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008222
8223 bool operator()(const OverloadCandidate *L,
8224 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008225 // Fast-path this check.
8226 if (L == R) return false;
8227
John McCall12f97bc2010-01-08 04:41:39 +00008228 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008229 if (L->Viable) {
8230 if (!R->Viable) return true;
8231
8232 // TODO: introduce a tri-valued comparison for overload
8233 // candidates. Would be more worthwhile if we had a sort
8234 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008235 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8236 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008237 } else if (R->Viable)
8238 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008239
John McCall3712d9e2010-01-15 23:32:50 +00008240 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008241
John McCall3712d9e2010-01-15 23:32:50 +00008242 // Criteria by which we can sort non-viable candidates:
8243 if (!L->Viable) {
8244 // 1. Arity mismatches come after other candidates.
8245 if (L->FailureKind == ovl_fail_too_many_arguments ||
8246 L->FailureKind == ovl_fail_too_few_arguments)
8247 return false;
8248 if (R->FailureKind == ovl_fail_too_many_arguments ||
8249 R->FailureKind == ovl_fail_too_few_arguments)
8250 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008251
John McCallfe796dd2010-01-23 05:17:32 +00008252 // 2. Bad conversions come first and are ordered by the number
8253 // of bad conversions and quality of good conversions.
8254 if (L->FailureKind == ovl_fail_bad_conversion) {
8255 if (R->FailureKind != ovl_fail_bad_conversion)
8256 return true;
8257
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008258 // The conversion that can be fixed with a smaller number of changes,
8259 // comes first.
8260 unsigned numLFixes = L->Fix.NumConversionsFixed;
8261 unsigned numRFixes = R->Fix.NumConversionsFixed;
8262 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8263 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008264 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008265 if (numLFixes < numRFixes)
8266 return true;
8267 else
8268 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008269 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008270
John McCallfe796dd2010-01-23 05:17:32 +00008271 // If there's any ordering between the defined conversions...
8272 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008273 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008274
8275 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008276 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008277 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008278 switch (CompareImplicitConversionSequences(S,
8279 L->Conversions[I],
8280 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008281 case ImplicitConversionSequence::Better:
8282 leftBetter++;
8283 break;
8284
8285 case ImplicitConversionSequence::Worse:
8286 leftBetter--;
8287 break;
8288
8289 case ImplicitConversionSequence::Indistinguishable:
8290 break;
8291 }
8292 }
8293 if (leftBetter > 0) return true;
8294 if (leftBetter < 0) return false;
8295
8296 } else if (R->FailureKind == ovl_fail_bad_conversion)
8297 return false;
8298
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008299 if (L->FailureKind == ovl_fail_bad_deduction) {
8300 if (R->FailureKind != ovl_fail_bad_deduction)
8301 return true;
8302
8303 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8304 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008305 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008306 } else if (R->FailureKind == ovl_fail_bad_deduction)
8307 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008308
John McCall3712d9e2010-01-15 23:32:50 +00008309 // TODO: others?
8310 }
8311
8312 // Sort everything else by location.
8313 SourceLocation LLoc = GetLocationForCandidate(L);
8314 SourceLocation RLoc = GetLocationForCandidate(R);
8315
8316 // Put candidates without locations (e.g. builtins) at the end.
8317 if (LLoc.isInvalid()) return false;
8318 if (RLoc.isInvalid()) return true;
8319
8320 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008321 }
8322};
8323
John McCallfe796dd2010-01-23 05:17:32 +00008324/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008325/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008326void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8327 Expr **Args, unsigned NumArgs) {
8328 assert(!Cand->Viable);
8329
8330 // Don't do anything on failures other than bad conversion.
8331 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8332
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008333 // We only want the FixIts if all the arguments can be corrected.
8334 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008335 // Use a implicit copy initialization to check conversion fixes.
8336 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008337
John McCallfe796dd2010-01-23 05:17:32 +00008338 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008339 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008340 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008341 while (true) {
8342 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8343 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008344 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008345 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008346 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008347 }
John McCallfe796dd2010-01-23 05:17:32 +00008348 }
8349
8350 if (ConvIdx == ConvCount)
8351 return;
8352
John McCall65eb8792010-02-25 01:37:24 +00008353 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8354 "remaining conversion is initialized?");
8355
Douglas Gregoradc7a702010-04-16 17:45:54 +00008356 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008357 // operation somehow.
8358 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008359
8360 const FunctionProtoType* Proto;
8361 unsigned ArgIdx = ConvIdx;
8362
8363 if (Cand->IsSurrogate) {
8364 QualType ConvType
8365 = Cand->Surrogate->getConversionType().getNonReferenceType();
8366 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8367 ConvType = ConvPtrType->getPointeeType();
8368 Proto = ConvType->getAs<FunctionProtoType>();
8369 ArgIdx--;
8370 } else if (Cand->Function) {
8371 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8372 if (isa<CXXMethodDecl>(Cand->Function) &&
8373 !isa<CXXConstructorDecl>(Cand->Function))
8374 ArgIdx--;
8375 } else {
8376 // Builtin binary operator with a bad first conversion.
8377 assert(ConvCount <= 3);
8378 for (; ConvIdx != ConvCount; ++ConvIdx)
8379 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008380 = TryCopyInitialization(S, Args[ConvIdx],
8381 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008382 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008383 /*InOverloadResolution*/ true,
8384 /*AllowObjCWritebackConversion=*/
8385 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008386 return;
8387 }
8388
8389 // Fill in the rest of the conversions.
8390 unsigned NumArgsInProto = Proto->getNumArgs();
8391 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008392 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008393 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008394 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008395 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008396 /*InOverloadResolution=*/true,
8397 /*AllowObjCWritebackConversion=*/
8398 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008399 // Store the FixIt in the candidate if it exists.
8400 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008401 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008402 }
John McCallfe796dd2010-01-23 05:17:32 +00008403 else
8404 Cand->Conversions[ConvIdx].setEllipsis();
8405 }
8406}
8407
John McCalld3224162010-01-08 00:58:21 +00008408} // end anonymous namespace
8409
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008410/// PrintOverloadCandidates - When overload resolution fails, prints
8411/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008412/// set.
John McCall5c32be02010-08-24 20:38:10 +00008413void OverloadCandidateSet::NoteCandidates(Sema &S,
8414 OverloadCandidateDisplayKind OCD,
8415 Expr **Args, unsigned NumArgs,
8416 const char *Opc,
8417 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008418 // Sort the candidates by viability and position. Sorting directly would
8419 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008420 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008421 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8422 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008423 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008424 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008425 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008426 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008427 if (Cand->Function || Cand->IsSurrogate)
8428 Cands.push_back(Cand);
8429 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8430 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008431 }
8432 }
8433
John McCallad2587a2010-01-12 00:48:53 +00008434 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008435 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008436
John McCall0d1da222010-01-12 00:44:57 +00008437 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008438
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008439 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008440 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8441 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008442 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008443 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8444 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008445
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008446 // Set an arbitrary limit on the number of candidate functions we'll spam
8447 // the user with. FIXME: This limit should depend on details of the
8448 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008449 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008450 break;
8451 }
8452 ++CandsShown;
8453
John McCalld3224162010-01-08 00:58:21 +00008454 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008455 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008456 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008457 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008458 else {
8459 assert(Cand->Viable &&
8460 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008461 // Generally we only see ambiguities including viable builtin
8462 // operators if overload resolution got screwed up by an
8463 // ambiguous user-defined conversion.
8464 //
8465 // FIXME: It's quite possible for different conversions to see
8466 // different ambiguities, though.
8467 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008468 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008469 ReportedAmbiguousConversions = true;
8470 }
John McCalld3224162010-01-08 00:58:21 +00008471
John McCall0d1da222010-01-12 00:44:57 +00008472 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008473 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008474 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008475 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008476
8477 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008478 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008479}
8480
Douglas Gregorb491ed32011-02-19 21:32:49 +00008481// [PossiblyAFunctionType] --> [Return]
8482// NonFunctionType --> NonFunctionType
8483// R (A) --> R(A)
8484// R (*)(A) --> R (A)
8485// R (&)(A) --> R (A)
8486// R (S::*)(A) --> R (A)
8487QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8488 QualType Ret = PossiblyAFunctionType;
8489 if (const PointerType *ToTypePtr =
8490 PossiblyAFunctionType->getAs<PointerType>())
8491 Ret = ToTypePtr->getPointeeType();
8492 else if (const ReferenceType *ToTypeRef =
8493 PossiblyAFunctionType->getAs<ReferenceType>())
8494 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008495 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008496 PossiblyAFunctionType->getAs<MemberPointerType>())
8497 Ret = MemTypePtr->getPointeeType();
8498 Ret =
8499 Context.getCanonicalType(Ret).getUnqualifiedType();
8500 return Ret;
8501}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008502
Douglas Gregorb491ed32011-02-19 21:32:49 +00008503// A helper class to help with address of function resolution
8504// - allows us to avoid passing around all those ugly parameters
8505class AddressOfFunctionResolver
8506{
8507 Sema& S;
8508 Expr* SourceExpr;
8509 const QualType& TargetType;
8510 QualType TargetFunctionType; // Extracted function type from target type
8511
8512 bool Complain;
8513 //DeclAccessPair& ResultFunctionAccessPair;
8514 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008515
Douglas Gregorb491ed32011-02-19 21:32:49 +00008516 bool TargetTypeIsNonStaticMemberFunction;
8517 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008518
Douglas Gregorb491ed32011-02-19 21:32:49 +00008519 OverloadExpr::FindResult OvlExprInfo;
8520 OverloadExpr *OvlExpr;
8521 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008522 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008523
Douglas Gregorb491ed32011-02-19 21:32:49 +00008524public:
8525 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8526 const QualType& TargetType, bool Complain)
8527 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8528 Complain(Complain), Context(S.getASTContext()),
8529 TargetTypeIsNonStaticMemberFunction(
8530 !!TargetType->getAs<MemberPointerType>()),
8531 FoundNonTemplateFunction(false),
8532 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8533 OvlExpr(OvlExprInfo.Expression)
8534 {
8535 ExtractUnqualifiedFunctionTypeFromTargetType();
8536
8537 if (!TargetFunctionType->isFunctionType()) {
8538 if (OvlExpr->hasExplicitTemplateArgs()) {
8539 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008540 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008541 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008542
8543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8544 if (!Method->isStatic()) {
8545 // If the target type is a non-function type and the function
8546 // found is a non-static member function, pretend as if that was
8547 // the target, it's the only possible type to end up with.
8548 TargetTypeIsNonStaticMemberFunction = true;
8549
8550 // And skip adding the function if its not in the proper form.
8551 // We'll diagnose this due to an empty set of functions.
8552 if (!OvlExprInfo.HasFormOfMemberPointer)
8553 return;
8554 }
8555 }
8556
Douglas Gregorb491ed32011-02-19 21:32:49 +00008557 Matches.push_back(std::make_pair(dap,Fn));
8558 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008559 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008560 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008561 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008562
8563 if (OvlExpr->hasExplicitTemplateArgs())
8564 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008565
Douglas Gregorb491ed32011-02-19 21:32:49 +00008566 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8567 // C++ [over.over]p4:
8568 // If more than one function is selected, [...]
8569 if (Matches.size() > 1) {
8570 if (FoundNonTemplateFunction)
8571 EliminateAllTemplateMatches();
8572 else
8573 EliminateAllExceptMostSpecializedTemplate();
8574 }
8575 }
8576 }
8577
8578private:
8579 bool isTargetTypeAFunction() const {
8580 return TargetFunctionType->isFunctionType();
8581 }
8582
8583 // [ToType] [Return]
8584
8585 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8586 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8587 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8588 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8589 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8590 }
8591
8592 // return true if any matching specializations were found
8593 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8594 const DeclAccessPair& CurAccessFunPair) {
8595 if (CXXMethodDecl *Method
8596 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8597 // Skip non-static function templates when converting to pointer, and
8598 // static when converting to member pointer.
8599 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8600 return false;
8601 }
8602 else if (TargetTypeIsNonStaticMemberFunction)
8603 return false;
8604
8605 // C++ [over.over]p2:
8606 // If the name is a function template, template argument deduction is
8607 // done (14.8.2.2), and if the argument deduction succeeds, the
8608 // resulting template argument list is used to generate a single
8609 // function template specialization, which is added to the set of
8610 // overloaded functions considered.
8611 FunctionDecl *Specialization = 0;
8612 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8613 if (Sema::TemplateDeductionResult Result
8614 = S.DeduceTemplateArguments(FunctionTemplate,
8615 &OvlExplicitTemplateArgs,
8616 TargetFunctionType, Specialization,
8617 Info)) {
8618 // FIXME: make a note of the failed deduction for diagnostics.
8619 (void)Result;
8620 return false;
8621 }
8622
8623 // Template argument deduction ensures that we have an exact match.
8624 // This function template specicalization works.
8625 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8626 assert(TargetFunctionType
8627 == Context.getCanonicalType(Specialization->getType()));
8628 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8629 return true;
8630 }
8631
8632 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8633 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008634 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008635 // Skip non-static functions when converting to pointer, and static
8636 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008637 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8638 return false;
8639 }
8640 else if (TargetTypeIsNonStaticMemberFunction)
8641 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008642
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008643 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008644 if (S.getLangOptions().CUDA)
8645 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8646 if (S.CheckCUDATarget(Caller, FunDecl))
8647 return false;
8648
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008649 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008650 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8651 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008652 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8653 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008654 Matches.push_back(std::make_pair(CurAccessFunPair,
8655 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008656 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008657 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008658 }
Mike Stump11289f42009-09-09 15:08:12 +00008659 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008660
8661 return false;
8662 }
8663
8664 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8665 bool Ret = false;
8666
8667 // If the overload expression doesn't have the form of a pointer to
8668 // member, don't try to convert it to a pointer-to-member type.
8669 if (IsInvalidFormOfPointerToMemberFunction())
8670 return false;
8671
8672 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8673 E = OvlExpr->decls_end();
8674 I != E; ++I) {
8675 // Look through any using declarations to find the underlying function.
8676 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8677
8678 // C++ [over.over]p3:
8679 // Non-member functions and static member functions match
8680 // targets of type "pointer-to-function" or "reference-to-function."
8681 // Nonstatic member functions match targets of
8682 // type "pointer-to-member-function."
8683 // Note that according to DR 247, the containing class does not matter.
8684 if (FunctionTemplateDecl *FunctionTemplate
8685 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8686 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8687 Ret = true;
8688 }
8689 // If we have explicit template arguments supplied, skip non-templates.
8690 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8691 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8692 Ret = true;
8693 }
8694 assert(Ret || Matches.empty());
8695 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008696 }
8697
Douglas Gregorb491ed32011-02-19 21:32:49 +00008698 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008699 // [...] and any given function template specialization F1 is
8700 // eliminated if the set contains a second function template
8701 // specialization whose function template is more specialized
8702 // than the function template of F1 according to the partial
8703 // ordering rules of 14.5.5.2.
8704
8705 // The algorithm specified above is quadratic. We instead use a
8706 // two-pass algorithm (similar to the one used to identify the
8707 // best viable function in an overload set) that identifies the
8708 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008709
8710 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8711 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8712 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008713
John McCall58cc69d2010-01-27 01:50:18 +00008714 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008715 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8716 TPOC_Other, 0, SourceExpr->getLocStart(),
8717 S.PDiag(),
8718 S.PDiag(diag::err_addr_ovl_ambiguous)
8719 << Matches[0].second->getDeclName(),
8720 S.PDiag(diag::note_ovl_candidate)
8721 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008722 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008723
Douglas Gregorb491ed32011-02-19 21:32:49 +00008724 if (Result != MatchesCopy.end()) {
8725 // Make it the first and only element
8726 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8727 Matches[0].second = cast<FunctionDecl>(*Result);
8728 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008729 }
8730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008731
Douglas Gregorb491ed32011-02-19 21:32:49 +00008732 void EliminateAllTemplateMatches() {
8733 // [...] any function template specializations in the set are
8734 // eliminated if the set also contains a non-template function, [...]
8735 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8736 if (Matches[I].second->getPrimaryTemplate() == 0)
8737 ++I;
8738 else {
8739 Matches[I] = Matches[--N];
8740 Matches.set_size(N);
8741 }
8742 }
8743 }
8744
8745public:
8746 void ComplainNoMatchesFound() const {
8747 assert(Matches.empty());
8748 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8749 << OvlExpr->getName() << TargetFunctionType
8750 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008751 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008752 }
8753
8754 bool IsInvalidFormOfPointerToMemberFunction() const {
8755 return TargetTypeIsNonStaticMemberFunction &&
8756 !OvlExprInfo.HasFormOfMemberPointer;
8757 }
8758
8759 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8760 // TODO: Should we condition this on whether any functions might
8761 // have matched, or is it more appropriate to do that in callers?
8762 // TODO: a fixit wouldn't hurt.
8763 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8764 << TargetType << OvlExpr->getSourceRange();
8765 }
8766
8767 void ComplainOfInvalidConversion() const {
8768 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8769 << OvlExpr->getName() << TargetType;
8770 }
8771
8772 void ComplainMultipleMatchesFound() const {
8773 assert(Matches.size() > 1);
8774 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8775 << OvlExpr->getName()
8776 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008777 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008778 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008779
8780 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8781
Douglas Gregorb491ed32011-02-19 21:32:49 +00008782 int getNumMatches() const { return Matches.size(); }
8783
8784 FunctionDecl* getMatchingFunctionDecl() const {
8785 if (Matches.size() != 1) return 0;
8786 return Matches[0].second;
8787 }
8788
8789 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8790 if (Matches.size() != 1) return 0;
8791 return &Matches[0].first;
8792 }
8793};
8794
8795/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8796/// an overloaded function (C++ [over.over]), where @p From is an
8797/// expression with overloaded function type and @p ToType is the type
8798/// we're trying to resolve to. For example:
8799///
8800/// @code
8801/// int f(double);
8802/// int f(int);
8803///
8804/// int (*pfd)(double) = f; // selects f(double)
8805/// @endcode
8806///
8807/// This routine returns the resulting FunctionDecl if it could be
8808/// resolved, and NULL otherwise. When @p Complain is true, this
8809/// routine will emit diagnostics if there is an error.
8810FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008811Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8812 QualType TargetType,
8813 bool Complain,
8814 DeclAccessPair &FoundResult,
8815 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008816 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008817
8818 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8819 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008820 int NumMatches = Resolver.getNumMatches();
8821 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008822 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008823 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8824 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8825 else
8826 Resolver.ComplainNoMatchesFound();
8827 }
8828 else if (NumMatches > 1 && Complain)
8829 Resolver.ComplainMultipleMatchesFound();
8830 else if (NumMatches == 1) {
8831 Fn = Resolver.getMatchingFunctionDecl();
8832 assert(Fn);
8833 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00008834 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008835 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008836 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008837 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008838
8839 if (pHadMultipleCandidates)
8840 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008841 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008842}
8843
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008844/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008845/// resolve that overloaded function expression down to a single function.
8846///
8847/// This routine can only resolve template-ids that refer to a single function
8848/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008849/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008850/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008851FunctionDecl *
8852Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8853 bool Complain,
8854 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008855 // C++ [over.over]p1:
8856 // [...] [Note: any redundant set of parentheses surrounding the
8857 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008858 // C++ [over.over]p1:
8859 // [...] The overloaded function name can be preceded by the &
8860 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008861
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008862 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008863 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008864 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008865
8866 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008867 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008868
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008869 // Look through all of the overloaded functions, searching for one
8870 // whose type matches exactly.
8871 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008872 for (UnresolvedSetIterator I = ovl->decls_begin(),
8873 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008874 // C++0x [temp.arg.explicit]p3:
8875 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008876 // where deduction is not done, if a template argument list is
8877 // specified and it, along with any default template arguments,
8878 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008879 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008880 FunctionTemplateDecl *FunctionTemplate
8881 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008882
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008883 // C++ [over.over]p2:
8884 // If the name is a function template, template argument deduction is
8885 // done (14.8.2.2), and if the argument deduction succeeds, the
8886 // resulting template argument list is used to generate a single
8887 // function template specialization, which is added to the set of
8888 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008889 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008890 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008891 if (TemplateDeductionResult Result
8892 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8893 Specialization, Info)) {
8894 // FIXME: make a note of the failed deduction for diagnostics.
8895 (void)Result;
8896 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008897 }
8898
John McCall0009fcc2011-04-26 20:42:42 +00008899 assert(Specialization && "no specialization and no error?");
8900
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008901 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008902 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008903 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008904 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8905 << ovl->getName();
8906 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008907 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008908 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008909 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008910
John McCall0009fcc2011-04-26 20:42:42 +00008911 Matched = Specialization;
8912 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008913 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008914
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008915 return Matched;
8916}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008917
Douglas Gregor1beec452011-03-12 01:48:56 +00008918
8919
8920
John McCall50a2c2c2011-10-11 23:14:30 +00008921// Resolve and fix an overloaded expression that can be resolved
8922// because it identifies a single function template specialization.
8923//
Douglas Gregor1beec452011-03-12 01:48:56 +00008924// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008925//
8926// Return true if it was logically possible to so resolve the
8927// expression, regardless of whether or not it succeeded. Always
8928// returns true if 'complain' is set.
8929bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8930 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8931 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008932 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008933 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008934 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008935
John McCall50a2c2c2011-10-11 23:14:30 +00008936 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008937
John McCall0009fcc2011-04-26 20:42:42 +00008938 DeclAccessPair found;
8939 ExprResult SingleFunctionExpression;
8940 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8941 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008942 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8943 SrcExpr = ExprError();
8944 return true;
8945 }
John McCall0009fcc2011-04-26 20:42:42 +00008946
8947 // It is only correct to resolve to an instance method if we're
8948 // resolving a form that's permitted to be a pointer to member.
8949 // Otherwise we'll end up making a bound member expression, which
8950 // is illegal in all the contexts we resolve like this.
8951 if (!ovl.HasFormOfMemberPointer &&
8952 isa<CXXMethodDecl>(fn) &&
8953 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008954 if (!complain) return false;
8955
8956 Diag(ovl.Expression->getExprLoc(),
8957 diag::err_bound_member_function)
8958 << 0 << ovl.Expression->getSourceRange();
8959
8960 // TODO: I believe we only end up here if there's a mix of
8961 // static and non-static candidates (otherwise the expression
8962 // would have 'bound member' type, not 'overload' type).
8963 // Ideally we would note which candidate was chosen and why
8964 // the static candidates were rejected.
8965 SrcExpr = ExprError();
8966 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008967 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008968
John McCall0009fcc2011-04-26 20:42:42 +00008969 // Fix the expresion to refer to 'fn'.
8970 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008971 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008972
8973 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008974 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008975 SingleFunctionExpression =
8976 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008977 if (SingleFunctionExpression.isInvalid()) {
8978 SrcExpr = ExprError();
8979 return true;
8980 }
8981 }
John McCall0009fcc2011-04-26 20:42:42 +00008982 }
8983
8984 if (!SingleFunctionExpression.isUsable()) {
8985 if (complain) {
8986 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8987 << ovl.Expression->getName()
8988 << DestTypeForComplaining
8989 << OpRangeForComplaining
8990 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008991 NoteAllOverloadCandidates(SrcExpr.get());
8992
8993 SrcExpr = ExprError();
8994 return true;
8995 }
8996
8997 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008998 }
8999
John McCall50a2c2c2011-10-11 23:14:30 +00009000 SrcExpr = SingleFunctionExpression;
9001 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009002}
9003
Douglas Gregorcabea402009-09-22 15:41:20 +00009004/// \brief Add a single candidate to the overload set.
9005static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009006 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009007 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00009008 Expr **Args, unsigned NumArgs,
9009 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009010 bool PartialOverloading,
9011 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009012 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009013 if (isa<UsingShadowDecl>(Callee))
9014 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9015
Douglas Gregorcabea402009-09-22 15:41:20 +00009016 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009017 if (ExplicitTemplateArgs) {
9018 assert(!KnownValid && "Explicit template arguments?");
9019 return;
9020 }
John McCalla0296f72010-03-19 07:35:19 +00009021 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00009022 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009023 return;
John McCalld14a8642009-11-21 08:51:07 +00009024 }
9025
9026 if (FunctionTemplateDecl *FuncTemplate
9027 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009028 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9029 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00009030 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009031 return;
9032 }
9033
Richard Smith95ce4f62011-06-26 22:19:54 +00009034 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009035}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009036
Douglas Gregorcabea402009-09-22 15:41:20 +00009037/// \brief Add the overload candidates named by callee and/or found by argument
9038/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009039void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00009040 Expr **Args, unsigned NumArgs,
9041 OverloadCandidateSet &CandidateSet,
9042 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009043
9044#ifndef NDEBUG
9045 // Verify that ArgumentDependentLookup is consistent with the rules
9046 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009047 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009048 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9049 // and let Y be the lookup set produced by argument dependent
9050 // lookup (defined as follows). If X contains
9051 //
9052 // -- a declaration of a class member, or
9053 //
9054 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009055 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009056 //
9057 // -- a declaration that is neither a function or a function
9058 // template
9059 //
9060 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009061
John McCall57500772009-12-16 12:17:52 +00009062 if (ULE->requiresADL()) {
9063 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9064 E = ULE->decls_end(); I != E; ++I) {
9065 assert(!(*I)->getDeclContext()->isRecord());
9066 assert(isa<UsingShadowDecl>(*I) ||
9067 !(*I)->getDeclContext()->isFunctionOrMethod());
9068 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009069 }
9070 }
9071#endif
9072
John McCall57500772009-12-16 12:17:52 +00009073 // It would be nice to avoid this copy.
9074 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009075 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009076 if (ULE->hasExplicitTemplateArgs()) {
9077 ULE->copyTemplateArgumentsInto(TABuffer);
9078 ExplicitTemplateArgs = &TABuffer;
9079 }
9080
9081 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9082 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00009083 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009084 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009085 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009086
John McCall57500772009-12-16 12:17:52 +00009087 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009088 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9089 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00009090 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00009091 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00009092 PartialOverloading,
9093 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009094}
John McCalld681c392009-12-16 08:11:27 +00009095
Richard Smith998a5912011-06-05 22:42:48 +00009096/// Attempt to recover from an ill-formed use of a non-dependent name in a
9097/// template, where the non-dependent name was declared after the template
9098/// was defined. This is common in code written for a compilers which do not
9099/// correctly implement two-stage name lookup.
9100///
9101/// Returns true if a viable candidate was found and a diagnostic was issued.
9102static bool
9103DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9104 const CXXScopeSpec &SS, LookupResult &R,
9105 TemplateArgumentListInfo *ExplicitTemplateArgs,
9106 Expr **Args, unsigned NumArgs) {
9107 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9108 return false;
9109
9110 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9111 SemaRef.LookupQualifiedName(R, DC);
9112
9113 if (!R.empty()) {
9114 R.suppressDiagnostics();
9115
9116 if (isa<CXXRecordDecl>(DC)) {
9117 // Don't diagnose names we find in classes; we get much better
9118 // diagnostics for these from DiagnoseEmptyLookup.
9119 R.clear();
9120 return false;
9121 }
9122
9123 OverloadCandidateSet Candidates(FnLoc);
9124 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9125 AddOverloadedCallCandidate(SemaRef, I.getPair(),
9126 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00009127 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009128
9129 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009130 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009131 // No viable functions. Don't bother the user with notes for functions
9132 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009133 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009134 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009135 }
Richard Smith998a5912011-06-05 22:42:48 +00009136
9137 // Find the namespaces where ADL would have looked, and suggest
9138 // declaring the function there instead.
9139 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9140 Sema::AssociatedClassSet AssociatedClasses;
9141 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
9142 AssociatedNamespaces,
9143 AssociatedClasses);
9144 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009145 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009146 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009147 for (Sema::AssociatedNamespaceSet::iterator
9148 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009149 end = AssociatedNamespaces.end(); it != end; ++it) {
9150 if (!Std->Encloses(*it))
9151 SuggestedNamespaces.insert(*it);
9152 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009153 } else {
9154 // Lacking the 'std::' namespace, use all of the associated namespaces.
9155 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009156 }
9157
9158 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9159 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009160 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009161 SemaRef.Diag(Best->Function->getLocation(),
9162 diag::note_not_found_by_two_phase_lookup)
9163 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009164 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009165 SemaRef.Diag(Best->Function->getLocation(),
9166 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009167 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009168 } else {
9169 // FIXME: It would be useful to list the associated namespaces here,
9170 // but the diagnostics infrastructure doesn't provide a way to produce
9171 // a localized representation of a list of items.
9172 SemaRef.Diag(Best->Function->getLocation(),
9173 diag::note_not_found_by_two_phase_lookup)
9174 << R.getLookupName() << 2;
9175 }
9176
9177 // Try to recover by calling this function.
9178 return true;
9179 }
9180
9181 R.clear();
9182 }
9183
9184 return false;
9185}
9186
9187/// Attempt to recover from ill-formed use of a non-dependent operator in a
9188/// template, where the non-dependent operator was declared after the template
9189/// was defined.
9190///
9191/// Returns true if a viable candidate was found and a diagnostic was issued.
9192static bool
9193DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9194 SourceLocation OpLoc,
9195 Expr **Args, unsigned NumArgs) {
9196 DeclarationName OpName =
9197 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9198 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9199 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9200 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
9201}
9202
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009203namespace {
9204// Callback to limit the allowed keywords and to only accept typo corrections
9205// that are keywords or whose decls refer to functions (or template functions)
9206// that accept the given number of arguments.
9207class RecoveryCallCCC : public CorrectionCandidateCallback {
9208 public:
9209 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9210 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9211 WantTypeSpecifiers = SemaRef.getLangOptions().CPlusPlus;
9212 WantRemainingKeywords = false;
9213 }
9214
9215 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9216 if (!candidate.getCorrectionDecl())
9217 return candidate.isKeyword();
9218
9219 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9220 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9221 FunctionDecl *FD = 0;
9222 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9223 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9224 FD = FTD->getTemplatedDecl();
9225 if (!HasExplicitTemplateArgs && !FD) {
9226 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9227 // If the Decl is neither a function nor a template function,
9228 // determine if it is a pointer or reference to a function. If so,
9229 // check against the number of arguments expected for the pointee.
9230 QualType ValType = cast<ValueDecl>(ND)->getType();
9231 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9232 ValType = ValType->getPointeeType();
9233 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9234 if (FPT->getNumArgs() == NumArgs)
9235 return true;
9236 }
9237 }
9238 if (FD && FD->getNumParams() >= NumArgs &&
9239 FD->getMinRequiredArguments() <= NumArgs)
9240 return true;
9241 }
9242 return false;
9243 }
9244
9245 private:
9246 unsigned NumArgs;
9247 bool HasExplicitTemplateArgs;
9248};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009249
9250// Callback that effectively disabled typo correction
9251class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9252 public:
9253 NoTypoCorrectionCCC() {
9254 WantTypeSpecifiers = false;
9255 WantExpressionKeywords = false;
9256 WantCXXNamedCasts = false;
9257 WantRemainingKeywords = false;
9258 }
9259
9260 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9261 return false;
9262 }
9263};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009264}
9265
John McCalld681c392009-12-16 08:11:27 +00009266/// Attempts to recover from a call where no functions were found.
9267///
9268/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009269static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009270BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009271 UnresolvedLookupExpr *ULE,
9272 SourceLocation LParenLoc,
9273 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00009274 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009275 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009276
9277 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009278 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009279 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009280
John McCall57500772009-12-16 12:17:52 +00009281 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009282 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009283 if (ULE->hasExplicitTemplateArgs()) {
9284 ULE->copyTemplateArgumentsInto(TABuffer);
9285 ExplicitTemplateArgs = &TABuffer;
9286 }
9287
John McCalld681c392009-12-16 08:11:27 +00009288 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9289 Sema::LookupOrdinaryName);
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009290 RecoveryCallCCC Validator(SemaRef, NumArgs, ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009291 NoTypoCorrectionCCC RejectAll;
9292 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9293 (CorrectionCandidateCallback*)&Validator :
9294 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009295 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9296 ExplicitTemplateArgs, Args, NumArgs) &&
9297 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009298 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00009299 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00009300 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009301
John McCall57500772009-12-16 12:17:52 +00009302 assert(!R.empty() && "lookup results empty despite recovery");
9303
9304 // Build an implicit member call if appropriate. Just drop the
9305 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009306 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009307 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009308 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9309 R, ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009310 else if (ExplicitTemplateArgs)
Abramo Bagnara7945c982012-01-27 09:46:47 +00009311 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9312 *ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009313 else
9314 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9315
9316 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009317 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009318
9319 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009320 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009321 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009322 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009323 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009324}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009325
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009326/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009327/// (which eventually refers to the declaration Func) and the call
9328/// arguments Args/NumArgs, attempt to resolve the function call down
9329/// to a specific function. If overload resolution succeeds, returns
9330/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009331/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009332/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009333ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009334Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009335 SourceLocation LParenLoc,
9336 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009337 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009338 Expr *ExecConfig,
9339 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009340#ifndef NDEBUG
9341 if (ULE->requiresADL()) {
9342 // To do ADL, we must have found an unqualified name.
9343 assert(!ULE->getQualifier() && "qualified name with ADL");
9344
9345 // We don't perform ADL for implicit declarations of builtins.
9346 // Verify that this was correctly set up.
9347 FunctionDecl *F;
9348 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9349 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9350 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009351 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009352
John McCall57500772009-12-16 12:17:52 +00009353 // We don't perform ADL in C.
9354 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009355 } else
9356 assert(!ULE->isStdAssociatedNamespace() &&
9357 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009358#endif
9359
John McCall4124c492011-10-17 18:40:02 +00009360 UnbridgedCastsSet UnbridgedCasts;
9361 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9362 return ExprError();
9363
John McCallbc077cf2010-02-08 23:07:23 +00009364 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009365
John McCall57500772009-12-16 12:17:52 +00009366 // Add the functions denoted by the callee to the set of candidate
9367 // functions, including those from argument-dependent lookup.
9368 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009369
9370 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009371 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9372 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009373 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009374 // In Microsoft mode, if we are inside a template class member function then
9375 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009376 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009377 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00009378 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009379 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009380 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9381 Context.DependentTy, VK_RValue,
9382 RParenLoc);
9383 CE->setTypeDependent(true);
9384 return Owned(CE);
9385 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009386 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009387 RParenLoc, /*EmptyLookup=*/true,
9388 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009389 }
John McCalld681c392009-12-16 08:11:27 +00009390
John McCall4124c492011-10-17 18:40:02 +00009391 UnbridgedCasts.restore();
9392
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009393 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009394 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009395 case OR_Success: {
9396 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009397 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009398 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009399 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009400 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009401 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9402 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009403 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009404
Richard Smith998a5912011-06-05 22:42:48 +00009405 case OR_No_Viable_Function: {
9406 // Try to recover by looking for viable functions which the user might
9407 // have meant to call.
9408 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9409 Args, NumArgs, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009410 /*EmptyLookup=*/false,
9411 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009412 if (!Recovery.isInvalid())
9413 return Recovery;
9414
Chris Lattner45d9d602009-02-17 07:29:20 +00009415 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009416 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009417 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009418 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009419 break;
Richard Smith998a5912011-06-05 22:42:48 +00009420 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009421
9422 case OR_Ambiguous:
9423 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009424 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009425 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009426 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009427
9428 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009429 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009430 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
9431 << Best->Function->isDeleted()
9432 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009433 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009434 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009435 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009436
9437 // We emitted an error for the unvailable/deleted function call but keep
9438 // the call in the AST.
9439 FunctionDecl *FDecl = Best->Function;
9440 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9441 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9442 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009443 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009444 }
9445
Douglas Gregorb412e172010-07-25 18:17:45 +00009446 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009447 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009448}
9449
John McCall4c4c1df2010-01-26 03:27:55 +00009450static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009451 return Functions.size() > 1 ||
9452 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9453}
9454
Douglas Gregor084d8552009-03-13 23:49:33 +00009455/// \brief Create a unary operation that may resolve to an overloaded
9456/// operator.
9457///
9458/// \param OpLoc The location of the operator itself (e.g., '*').
9459///
9460/// \param OpcIn The UnaryOperator::Opcode that describes this
9461/// operator.
9462///
9463/// \param Functions The set of non-member functions that will be
9464/// considered by overload resolution. The caller needs to build this
9465/// set based on the context using, e.g.,
9466/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9467/// set should not contain any member functions; those will be added
9468/// by CreateOverloadedUnaryOp().
9469///
9470/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009471ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009472Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9473 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009474 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009475 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009476
9477 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9478 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9479 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009480 // TODO: provide better source location info.
9481 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009482
John McCall4124c492011-10-17 18:40:02 +00009483 if (checkPlaceholderForOverload(*this, Input))
9484 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009485
Douglas Gregor084d8552009-03-13 23:49:33 +00009486 Expr *Args[2] = { Input, 0 };
9487 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009488
Douglas Gregor084d8552009-03-13 23:49:33 +00009489 // For post-increment and post-decrement, add the implicit '0' as
9490 // the second argument, so that we know this is a post-increment or
9491 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009492 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009493 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009494 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9495 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009496 NumArgs = 2;
9497 }
9498
9499 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009500 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009501 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009502 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009503 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009504 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009505 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009506
John McCall58cc69d2010-01-27 01:50:18 +00009507 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009508 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009509 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009510 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009511 /*ADL*/ true, IsOverloaded(Fns),
9512 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009513 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009514 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009515 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009516 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009517 OpLoc));
9518 }
9519
9520 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009521 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009522
9523 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009524 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009525
9526 // Add operator candidates that are member functions.
9527 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9528
John McCall4c4c1df2010-01-26 03:27:55 +00009529 // Add candidates from ADL.
9530 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009531 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009532 /*ExplicitTemplateArgs*/ 0,
9533 CandidateSet);
9534
Douglas Gregor084d8552009-03-13 23:49:33 +00009535 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009536 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009537
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009538 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9539
Douglas Gregor084d8552009-03-13 23:49:33 +00009540 // Perform overload resolution.
9541 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009542 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009543 case OR_Success: {
9544 // We found a built-in operator or an overloaded operator.
9545 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009546
Douglas Gregor084d8552009-03-13 23:49:33 +00009547 if (FnDecl) {
9548 // We matched an overloaded operator. Build a call to that
9549 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009550
Eli Friedmanfa0df832012-02-02 03:46:19 +00009551 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009552
Douglas Gregor084d8552009-03-13 23:49:33 +00009553 // Convert the arguments.
9554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009555 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009556
John Wiegley01296292011-04-08 18:41:53 +00009557 ExprResult InputRes =
9558 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9559 Best->FoundDecl, Method);
9560 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009561 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009562 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009563 } else {
9564 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009565 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009566 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009567 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009568 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009569 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009570 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009571 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009572 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009573 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009574 }
9575
John McCall4fa0d5f2010-05-06 18:15:07 +00009576 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9577
John McCall7decc9e2010-11-18 06:31:45 +00009578 // Determine the result type.
9579 QualType ResultTy = FnDecl->getResultType();
9580 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9581 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009582
Douglas Gregor084d8552009-03-13 23:49:33 +00009583 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009584 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9585 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009586 if (FnExpr.isInvalid())
9587 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009588
Eli Friedman030eee42009-11-18 03:58:17 +00009589 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009590 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009591 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009592 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009594 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009595 FnDecl))
9596 return ExprError();
9597
John McCallb268a282010-08-23 23:25:46 +00009598 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009599 } else {
9600 // We matched a built-in operator. Convert the arguments, then
9601 // break out so that we will build the appropriate built-in
9602 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009603 ExprResult InputRes =
9604 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9605 Best->Conversions[0], AA_Passing);
9606 if (InputRes.isInvalid())
9607 return ExprError();
9608 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009609 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009610 }
John Wiegley01296292011-04-08 18:41:53 +00009611 }
9612
9613 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009614 // This is an erroneous use of an operator which can be overloaded by
9615 // a non-member function. Check for non-member operators which were
9616 // defined too late to be candidates.
9617 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9618 // FIXME: Recover by calling the found function.
9619 return ExprError();
9620
John Wiegley01296292011-04-08 18:41:53 +00009621 // No viable function; fall through to handling this as a
9622 // built-in operator, which will produce an error message for us.
9623 break;
9624
9625 case OR_Ambiguous:
9626 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9627 << UnaryOperator::getOpcodeStr(Opc)
9628 << Input->getType()
9629 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009630 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009631 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9632 return ExprError();
9633
9634 case OR_Deleted:
9635 Diag(OpLoc, diag::err_ovl_deleted_oper)
9636 << Best->Function->isDeleted()
9637 << UnaryOperator::getOpcodeStr(Opc)
9638 << getDeletedOrUnavailableSuffix(Best->Function)
9639 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009640 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9641 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009642 return ExprError();
9643 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009644
9645 // Either we found no viable overloaded operator or we matched a
9646 // built-in operator. In either case, fall through to trying to
9647 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009648 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009649}
9650
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009651/// \brief Create a binary operation that may resolve to an overloaded
9652/// operator.
9653///
9654/// \param OpLoc The location of the operator itself (e.g., '+').
9655///
9656/// \param OpcIn The BinaryOperator::Opcode that describes this
9657/// operator.
9658///
9659/// \param Functions The set of non-member functions that will be
9660/// considered by overload resolution. The caller needs to build this
9661/// set based on the context using, e.g.,
9662/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9663/// set should not contain any member functions; those will be added
9664/// by CreateOverloadedBinOp().
9665///
9666/// \param LHS Left-hand argument.
9667/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009668ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009669Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009670 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009671 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009672 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009673 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009674 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009675
9676 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9677 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9678 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9679
9680 // If either side is type-dependent, create an appropriate dependent
9681 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009682 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009683 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009684 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009685 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009686 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009687 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009688 Context.DependentTy,
9689 VK_RValue, OK_Ordinary,
9690 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009691
Douglas Gregor5287f092009-11-05 00:51:44 +00009692 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9693 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009694 VK_LValue,
9695 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009696 Context.DependentTy,
9697 Context.DependentTy,
9698 OpLoc));
9699 }
John McCall4c4c1df2010-01-26 03:27:55 +00009700
9701 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009702 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009703 // TODO: provide better source location info in DNLoc component.
9704 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009705 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009706 = UnresolvedLookupExpr::Create(Context, NamingClass,
9707 NestedNameSpecifierLoc(), OpNameInfo,
9708 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009709 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009710 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009711 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009712 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009713 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009714 OpLoc));
9715 }
9716
John McCall4124c492011-10-17 18:40:02 +00009717 // Always do placeholder-like conversions on the RHS.
9718 if (checkPlaceholderForOverload(*this, Args[1]))
9719 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009720
John McCall526ab472011-10-25 17:37:35 +00009721 // Do placeholder-like conversion on the LHS; note that we should
9722 // not get here with a PseudoObject LHS.
9723 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009724 if (checkPlaceholderForOverload(*this, Args[0]))
9725 return ExprError();
9726
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009727 // If this is the assignment operator, we only perform overload resolution
9728 // if the left-hand side is a class or enumeration type. This is actually
9729 // a hack. The standard requires that we do overload resolution between the
9730 // various built-in candidates, but as DR507 points out, this can lead to
9731 // problems. So we do it this way, which pretty much follows what GCC does.
9732 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009733 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009734 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009735
John McCalle26a8722010-12-04 08:14:53 +00009736 // If this is the .* operator, which is not overloadable, just
9737 // create a built-in binary operator.
9738 if (Opc == BO_PtrMemD)
9739 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9740
Douglas Gregor084d8552009-03-13 23:49:33 +00009741 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009742 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009743
9744 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009745 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009746
9747 // Add operator candidates that are member functions.
9748 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9749
John McCall4c4c1df2010-01-26 03:27:55 +00009750 // Add candidates from ADL.
9751 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9752 Args, 2,
9753 /*ExplicitTemplateArgs*/ 0,
9754 CandidateSet);
9755
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009756 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009757 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009758
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009759 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9760
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009761 // Perform overload resolution.
9762 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009763 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009764 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009765 // We found a built-in operator or an overloaded operator.
9766 FunctionDecl *FnDecl = Best->Function;
9767
9768 if (FnDecl) {
9769 // We matched an overloaded operator. Build a call to that
9770 // operator.
9771
Eli Friedmanfa0df832012-02-02 03:46:19 +00009772 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009773
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009774 // Convert the arguments.
9775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009776 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009777 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009778
Chandler Carruth8e543b32010-12-12 08:17:55 +00009779 ExprResult Arg1 =
9780 PerformCopyInitialization(
9781 InitializedEntity::InitializeParameter(Context,
9782 FnDecl->getParamDecl(0)),
9783 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009784 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009785 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009786
John Wiegley01296292011-04-08 18:41:53 +00009787 ExprResult Arg0 =
9788 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9789 Best->FoundDecl, Method);
9790 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009791 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009792 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009793 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009794 } else {
9795 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009796 ExprResult Arg0 = PerformCopyInitialization(
9797 InitializedEntity::InitializeParameter(Context,
9798 FnDecl->getParamDecl(0)),
9799 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009800 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009801 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009802
Chandler Carruth8e543b32010-12-12 08:17:55 +00009803 ExprResult Arg1 =
9804 PerformCopyInitialization(
9805 InitializedEntity::InitializeParameter(Context,
9806 FnDecl->getParamDecl(1)),
9807 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009808 if (Arg1.isInvalid())
9809 return ExprError();
9810 Args[0] = LHS = Arg0.takeAs<Expr>();
9811 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009812 }
9813
John McCall4fa0d5f2010-05-06 18:15:07 +00009814 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9815
John McCall7decc9e2010-11-18 06:31:45 +00009816 // Determine the result type.
9817 QualType ResultTy = FnDecl->getResultType();
9818 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9819 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009820
9821 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009822 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9823 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009824 if (FnExpr.isInvalid())
9825 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009826
John McCallb268a282010-08-23 23:25:46 +00009827 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009828 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009829 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009830
9831 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009832 FnDecl))
9833 return ExprError();
9834
John McCallb268a282010-08-23 23:25:46 +00009835 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009836 } else {
9837 // We matched a built-in operator. Convert the arguments, then
9838 // break out so that we will build the appropriate built-in
9839 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009840 ExprResult ArgsRes0 =
9841 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9842 Best->Conversions[0], AA_Passing);
9843 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009844 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009845 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009846
John Wiegley01296292011-04-08 18:41:53 +00009847 ExprResult ArgsRes1 =
9848 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9849 Best->Conversions[1], AA_Passing);
9850 if (ArgsRes1.isInvalid())
9851 return ExprError();
9852 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009853 break;
9854 }
9855 }
9856
Douglas Gregor66950a32009-09-30 21:46:01 +00009857 case OR_No_Viable_Function: {
9858 // C++ [over.match.oper]p9:
9859 // If the operator is the operator , [...] and there are no
9860 // viable functions, then the operator is assumed to be the
9861 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009862 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009863 break;
9864
Chandler Carruth8e543b32010-12-12 08:17:55 +00009865 // For class as left operand for assignment or compound assigment
9866 // operator do not fall through to handling in built-in, but report that
9867 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009868 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009869 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009870 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009871 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9872 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009873 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009874 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009875 // This is an erroneous use of an operator which can be overloaded by
9876 // a non-member function. Check for non-member operators which were
9877 // defined too late to be candidates.
9878 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9879 // FIXME: Recover by calling the found function.
9880 return ExprError();
9881
Douglas Gregor66950a32009-09-30 21:46:01 +00009882 // No viable function; try to create a built-in operation, which will
9883 // produce an error. Then, show the non-viable candidates.
9884 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009886 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009887 "C++ binary operator overloading is missing candidates!");
9888 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009889 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9890 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009891 return move(Result);
9892 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009893
9894 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009895 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009896 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009897 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009898 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009899 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9900 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009901 return ExprError();
9902
9903 case OR_Deleted:
9904 Diag(OpLoc, diag::err_ovl_deleted_oper)
9905 << Best->Function->isDeleted()
9906 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009907 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009908 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009909 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9910 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009911 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009912 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009913
Douglas Gregor66950a32009-09-30 21:46:01 +00009914 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009915 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009916}
9917
John McCalldadc5752010-08-24 06:29:42 +00009918ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009919Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9920 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009921 Expr *Base, Expr *Idx) {
9922 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009923 DeclarationName OpName =
9924 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9925
9926 // If either side is type-dependent, create an appropriate dependent
9927 // expression.
9928 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9929
John McCall58cc69d2010-01-27 01:50:18 +00009930 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009931 // CHECKME: no 'operator' keyword?
9932 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9933 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009934 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009935 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009936 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009937 /*ADL*/ true, /*Overloaded*/ false,
9938 UnresolvedSetIterator(),
9939 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009940 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009941
Sebastian Redladba46e2009-10-29 20:17:01 +00009942 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9943 Args, 2,
9944 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009945 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009946 RLoc));
9947 }
9948
John McCall4124c492011-10-17 18:40:02 +00009949 // Handle placeholders on both operands.
9950 if (checkPlaceholderForOverload(*this, Args[0]))
9951 return ExprError();
9952 if (checkPlaceholderForOverload(*this, Args[1]))
9953 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009954
Sebastian Redladba46e2009-10-29 20:17:01 +00009955 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009956 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009957
9958 // Subscript can only be overloaded as a member function.
9959
9960 // Add operator candidates that are member functions.
9961 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9962
9963 // Add builtin operator candidates.
9964 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9965
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009966 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9967
Sebastian Redladba46e2009-10-29 20:17:01 +00009968 // Perform overload resolution.
9969 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009970 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009971 case OR_Success: {
9972 // We found a built-in operator or an overloaded operator.
9973 FunctionDecl *FnDecl = Best->Function;
9974
9975 if (FnDecl) {
9976 // We matched an overloaded operator. Build a call to that
9977 // operator.
9978
Eli Friedmanfa0df832012-02-02 03:46:19 +00009979 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009980
John McCalla0296f72010-03-19 07:35:19 +00009981 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009982 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009983
Sebastian Redladba46e2009-10-29 20:17:01 +00009984 // Convert the arguments.
9985 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009986 ExprResult Arg0 =
9987 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9988 Best->FoundDecl, Method);
9989 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009990 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009991 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009992
Anders Carlssona68e51e2010-01-29 18:37:50 +00009993 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009994 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009995 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009996 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009997 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009998 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009999 Owned(Args[1]));
10000 if (InputInit.isInvalid())
10001 return ExprError();
10002
10003 Args[1] = InputInit.takeAs<Expr>();
10004
Sebastian Redladba46e2009-10-29 20:17:01 +000010005 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010006 QualType ResultTy = FnDecl->getResultType();
10007 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10008 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010009
10010 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +000010011 DeclarationNameLoc LocInfo;
10012 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
10013 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010014 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10015 HadMultipleCandidates,
10016 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +000010017 if (FnExpr.isInvalid())
10018 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010019
John McCallb268a282010-08-23 23:25:46 +000010020 CXXOperatorCallExpr *TheCall =
10021 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010022 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010023 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010024
John McCallb268a282010-08-23 23:25:46 +000010025 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010026 FnDecl))
10027 return ExprError();
10028
John McCallb268a282010-08-23 23:25:46 +000010029 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010030 } else {
10031 // We matched a built-in operator. Convert the arguments, then
10032 // break out so that we will build the appropriate built-in
10033 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010034 ExprResult ArgsRes0 =
10035 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10036 Best->Conversions[0], AA_Passing);
10037 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010038 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010039 Args[0] = ArgsRes0.take();
10040
10041 ExprResult ArgsRes1 =
10042 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10043 Best->Conversions[1], AA_Passing);
10044 if (ArgsRes1.isInvalid())
10045 return ExprError();
10046 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010047
10048 break;
10049 }
10050 }
10051
10052 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010053 if (CandidateSet.empty())
10054 Diag(LLoc, diag::err_ovl_no_oper)
10055 << Args[0]->getType() << /*subscript*/ 0
10056 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10057 else
10058 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10059 << Args[0]->getType()
10060 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010061 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10062 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010063 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010064 }
10065
10066 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010067 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010068 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010069 << Args[0]->getType() << Args[1]->getType()
10070 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010071 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10072 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010073 return ExprError();
10074
10075 case OR_Deleted:
10076 Diag(LLoc, diag::err_ovl_deleted_oper)
10077 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010078 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010079 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010080 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10081 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010082 return ExprError();
10083 }
10084
10085 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010086 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010087}
10088
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010089/// BuildCallToMemberFunction - Build a call to a member
10090/// function. MemExpr is the expression that refers to the member
10091/// function (and includes the object parameter), Args/NumArgs are the
10092/// arguments to the function call (not including the object
10093/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010094/// expression refers to a non-static member function or an overloaded
10095/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010096ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010097Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10098 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010099 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010100 assert(MemExprE->getType() == Context.BoundMemberTy ||
10101 MemExprE->getType() == Context.OverloadTy);
10102
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010103 // Dig out the member expression. This holds both the object
10104 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010105 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010106
John McCall0009fcc2011-04-26 20:42:42 +000010107 // Determine whether this is a call to a pointer-to-member function.
10108 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10109 assert(op->getType() == Context.BoundMemberTy);
10110 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10111
10112 QualType fnType =
10113 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10114
10115 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10116 QualType resultType = proto->getCallResultType(Context);
10117 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10118
10119 // Check that the object type isn't more qualified than the
10120 // member function we're calling.
10121 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10122
10123 QualType objectType = op->getLHS()->getType();
10124 if (op->getOpcode() == BO_PtrMemI)
10125 objectType = objectType->castAs<PointerType>()->getPointeeType();
10126 Qualifiers objectQuals = objectType.getQualifiers();
10127
10128 Qualifiers difference = objectQuals - funcQuals;
10129 difference.removeObjCGCAttr();
10130 difference.removeAddressSpace();
10131 if (difference) {
10132 std::string qualsString = difference.getAsString();
10133 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10134 << fnType.getUnqualifiedType()
10135 << qualsString
10136 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10137 }
10138
10139 CXXMemberCallExpr *call
10140 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10141 resultType, valueKind, RParenLoc);
10142
10143 if (CheckCallReturnType(proto->getResultType(),
10144 op->getRHS()->getSourceRange().getBegin(),
10145 call, 0))
10146 return ExprError();
10147
10148 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10149 return ExprError();
10150
10151 return MaybeBindToTemporary(call);
10152 }
10153
John McCall4124c492011-10-17 18:40:02 +000010154 UnbridgedCastsSet UnbridgedCasts;
10155 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10156 return ExprError();
10157
John McCall10eae182009-11-30 22:42:35 +000010158 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010159 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010160 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010161 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010162 if (isa<MemberExpr>(NakedMemExpr)) {
10163 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010164 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010165 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010166 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010167 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010168 } else {
10169 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010170 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010171
John McCall6e9f8f62009-12-03 04:06:58 +000010172 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010173 Expr::Classification ObjectClassification
10174 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10175 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010176
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010177 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010178 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010179
John McCall2d74de92009-12-01 22:10:20 +000010180 // FIXME: avoid copy.
10181 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10182 if (UnresExpr->hasExplicitTemplateArgs()) {
10183 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10184 TemplateArgs = &TemplateArgsBuffer;
10185 }
10186
John McCall10eae182009-11-30 22:42:35 +000010187 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10188 E = UnresExpr->decls_end(); I != E; ++I) {
10189
John McCall6e9f8f62009-12-03 04:06:58 +000010190 NamedDecl *Func = *I;
10191 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10192 if (isa<UsingShadowDecl>(Func))
10193 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10194
Douglas Gregor02824322011-01-26 19:30:28 +000010195
Francois Pichet64225792011-01-18 05:04:39 +000010196 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +000010197 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +000010198 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
10199 CandidateSet);
10200 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010201 // If explicit template arguments were provided, we can't call a
10202 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010203 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010204 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010205
John McCalla0296f72010-03-19 07:35:19 +000010206 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010207 ObjectClassification,
10208 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010209 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010210 } else {
John McCall10eae182009-11-30 22:42:35 +000010211 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010212 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010213 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +000010214 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010215 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010216 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010217 }
Mike Stump11289f42009-09-09 15:08:12 +000010218
John McCall10eae182009-11-30 22:42:35 +000010219 DeclarationName DeclName = UnresExpr->getMemberName();
10220
John McCall4124c492011-10-17 18:40:02 +000010221 UnbridgedCasts.restore();
10222
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010223 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010224 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010225 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010226 case OR_Success:
10227 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010228 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010229 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010230 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010231 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010232 break;
10233
10234 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010235 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010236 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010237 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010238 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010239 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010240 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010241
10242 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010243 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010244 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010245 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010246 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010247 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010248
10249 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010250 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010251 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010252 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010253 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010254 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010255 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010256 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010257 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010258 }
10259
John McCall16df1e52010-03-30 21:47:33 +000010260 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010261
John McCall2d74de92009-12-01 22:10:20 +000010262 // If overload resolution picked a static member, build a
10263 // non-member call based on that function.
10264 if (Method->isStatic()) {
10265 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10266 Args, NumArgs, RParenLoc);
10267 }
10268
John McCall10eae182009-11-30 22:42:35 +000010269 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010270 }
10271
John McCall7decc9e2010-11-18 06:31:45 +000010272 QualType ResultType = Method->getResultType();
10273 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10274 ResultType = ResultType.getNonLValueExprType(Context);
10275
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010276 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010277 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010278 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010279 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010280
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010281 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010282 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010283 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010284 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010285
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010286 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010287 // We only need to do this if there was actually an overload; otherwise
10288 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010289 if (!Method->isStatic()) {
10290 ExprResult ObjectArg =
10291 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10292 FoundDecl, Method);
10293 if (ObjectArg.isInvalid())
10294 return ExprError();
10295 MemExpr->setBase(ObjectArg.take());
10296 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010297
10298 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010299 const FunctionProtoType *Proto =
10300 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010301 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010302 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010303 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010304
John McCallb268a282010-08-23 23:25:46 +000010305 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010306 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010307
Anders Carlsson47061ee2011-05-06 14:25:31 +000010308 if ((isa<CXXConstructorDecl>(CurContext) ||
10309 isa<CXXDestructorDecl>(CurContext)) &&
10310 TheCall->getMethodDecl()->isPure()) {
10311 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10312
Chandler Carruth59259262011-06-27 08:31:58 +000010313 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010314 Diag(MemExpr->getLocStart(),
10315 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10316 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10317 << MD->getParent()->getDeclName();
10318
10319 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010320 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010321 }
John McCallb268a282010-08-23 23:25:46 +000010322 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010323}
10324
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010325/// BuildCallToObjectOfClassType - Build a call to an object of class
10326/// type (C++ [over.call.object]), which can end up invoking an
10327/// overloaded function call operator (@c operator()) or performing a
10328/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010329ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010330Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010331 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010332 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010333 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010334 if (checkPlaceholderForOverload(*this, Obj))
10335 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010336 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010337
10338 UnbridgedCastsSet UnbridgedCasts;
10339 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10340 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010341
John Wiegley01296292011-04-08 18:41:53 +000010342 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10343 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010344
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010345 // C++ [over.call.object]p1:
10346 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010347 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010348 // candidate functions includes at least the function call
10349 // operators of T. The function call operators of T are obtained by
10350 // ordinary lookup of the name operator() in the context of
10351 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010352 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010353 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010354
John Wiegley01296292011-04-08 18:41:53 +000010355 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +000010356 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010357 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010358 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010359
John McCall27b18f82009-11-17 02:14:36 +000010360 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10361 LookupQualifiedName(R, Record->getDecl());
10362 R.suppressDiagnostics();
10363
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010364 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010365 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010366 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10367 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010368 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010370
Douglas Gregorab7897a2008-11-19 22:57:39 +000010371 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010372 // In addition, for each (non-explicit in C++0x) conversion function
10373 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010374 //
10375 // operator conversion-type-id () cv-qualifier;
10376 //
10377 // where cv-qualifier is the same cv-qualification as, or a
10378 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010379 // denotes the type "pointer to function of (P1,...,Pn) returning
10380 // R", or the type "reference to pointer to function of
10381 // (P1,...,Pn) returning R", or the type "reference to function
10382 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010383 // is also considered as a candidate function. Similarly,
10384 // surrogate call functions are added to the set of candidate
10385 // functions for each conversion function declared in an
10386 // accessible base class provided the function is not hidden
10387 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010388 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010389 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010390 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010391 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010392 NamedDecl *D = *I;
10393 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10394 if (isa<UsingShadowDecl>(D))
10395 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010396
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010397 // Skip over templated conversion functions; they aren't
10398 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010399 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010400 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010401
John McCall6e9f8f62009-12-03 04:06:58 +000010402 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010403 if (!Conv->isExplicit()) {
10404 // Strip the reference type (if any) and then the pointer type (if
10405 // any) to get down to what might be a function type.
10406 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10407 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10408 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010409
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010410 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10411 {
10412 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10413 Object.get(), Args, NumArgs, CandidateSet);
10414 }
10415 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010416 }
Mike Stump11289f42009-09-09 15:08:12 +000010417
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010418 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10419
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010420 // Perform overload resolution.
10421 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010422 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010423 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010424 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010425 // Overload resolution succeeded; we'll build the appropriate call
10426 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010427 break;
10428
10429 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010430 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +000010431 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
10432 << Object.get()->getType() << /*call*/ 1
10433 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010434 else
John Wiegley01296292011-04-08 18:41:53 +000010435 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +000010436 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010437 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010438 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010439 break;
10440
10441 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +000010442 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010443 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010444 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010445 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010446 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010447
10448 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +000010449 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010450 diag::err_ovl_deleted_object_call)
10451 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010452 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010453 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010454 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010455 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010456 break;
Mike Stump11289f42009-09-09 15:08:12 +000010457 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010458
Douglas Gregorb412e172010-07-25 18:17:45 +000010459 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010460 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010461
John McCall4124c492011-10-17 18:40:02 +000010462 UnbridgedCasts.restore();
10463
Douglas Gregorab7897a2008-11-19 22:57:39 +000010464 if (Best->Function == 0) {
10465 // Since there is no function declaration, this is one of the
10466 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010467 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010468 = cast<CXXConversionDecl>(
10469 Best->Conversions[0].UserDefined.ConversionFunction);
10470
John Wiegley01296292011-04-08 18:41:53 +000010471 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010472 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010473
Douglas Gregorab7897a2008-11-19 22:57:39 +000010474 // We selected one of the surrogate functions that converts the
10475 // object parameter to a function pointer. Perform the conversion
10476 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010477
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010478 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010479 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010480 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10481 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010482 if (Call.isInvalid())
10483 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010484 // Record usage of conversion in an implicit cast.
10485 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10486 CK_UserDefinedConversion,
10487 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010488
Douglas Gregor668443e2011-01-20 00:18:04 +000010489 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010490 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010491 }
10492
Eli Friedmanfa0df832012-02-02 03:46:19 +000010493 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010494 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010495 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010496
Douglas Gregorab7897a2008-11-19 22:57:39 +000010497 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10498 // that calls this method, using Object for the implicit object
10499 // parameter and passing along the remaining arguments.
10500 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010501 const FunctionProtoType *Proto =
10502 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010503
10504 unsigned NumArgsInProto = Proto->getNumArgs();
10505 unsigned NumArgsToCheck = NumArgs;
10506
10507 // Build the full argument list for the method call (the
10508 // implicit object parameter is placed at the beginning of the
10509 // list).
10510 Expr **MethodArgs;
10511 if (NumArgs < NumArgsInProto) {
10512 NumArgsToCheck = NumArgsInProto;
10513 MethodArgs = new Expr*[NumArgsInProto + 1];
10514 } else {
10515 MethodArgs = new Expr*[NumArgs + 1];
10516 }
John Wiegley01296292011-04-08 18:41:53 +000010517 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010518 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10519 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010520
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010521 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10522 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010523 if (NewFn.isInvalid())
10524 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010525
10526 // Once we've built TheCall, all of the expressions are properly
10527 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010528 QualType ResultTy = Method->getResultType();
10529 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10530 ResultTy = ResultTy.getNonLValueExprType(Context);
10531
John McCallb268a282010-08-23 23:25:46 +000010532 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010533 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010534 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010535 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010536 delete [] MethodArgs;
10537
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010538 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010539 Method))
10540 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010541
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010542 // We may have default arguments. If so, we need to allocate more
10543 // slots in the call for them.
10544 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010545 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010546 else if (NumArgs > NumArgsInProto)
10547 NumArgsToCheck = NumArgsInProto;
10548
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010549 bool IsError = false;
10550
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010551 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010552 ExprResult ObjRes =
10553 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10554 Best->FoundDecl, Method);
10555 if (ObjRes.isInvalid())
10556 IsError = true;
10557 else
10558 Object = move(ObjRes);
10559 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010560
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010561 // Check the argument types.
10562 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010563 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010564 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010565 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010566
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010567 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010568
John McCalldadc5752010-08-24 06:29:42 +000010569 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010570 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010571 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010572 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010573 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010574
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010575 IsError |= InputInit.isInvalid();
10576 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010577 } else {
John McCalldadc5752010-08-24 06:29:42 +000010578 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010579 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10580 if (DefArg.isInvalid()) {
10581 IsError = true;
10582 break;
10583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010584
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010585 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010586 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010587
10588 TheCall->setArg(i + 1, Arg);
10589 }
10590
10591 // If this is a variadic call, handle args passed through "...".
10592 if (Proto->isVariadic()) {
10593 // Promote the arguments (C99 6.5.2.2p7).
10594 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010595 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10596 IsError |= Arg.isInvalid();
10597 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010598 }
10599 }
10600
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010601 if (IsError) return true;
10602
John McCallb268a282010-08-23 23:25:46 +000010603 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010604 return true;
10605
John McCalle172be52010-08-24 06:09:16 +000010606 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010607}
10608
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010609/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010610/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010611/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010612ExprResult
John McCallb268a282010-08-23 23:25:46 +000010613Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010614 assert(Base->getType()->isRecordType() &&
10615 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010616
John McCall4124c492011-10-17 18:40:02 +000010617 if (checkPlaceholderForOverload(*this, Base))
10618 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010619
John McCallbc077cf2010-02-08 23:07:23 +000010620 SourceLocation Loc = Base->getExprLoc();
10621
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010622 // C++ [over.ref]p1:
10623 //
10624 // [...] An expression x->m is interpreted as (x.operator->())->m
10625 // for a class object x of type T if T::operator->() exists and if
10626 // the operator is selected as the best match function by the
10627 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010628 DeclarationName OpName =
10629 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010630 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010631 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010632
John McCallbc077cf2010-02-08 23:07:23 +000010633 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010634 PDiag(diag::err_typecheck_incomplete_tag)
10635 << Base->getSourceRange()))
10636 return ExprError();
10637
John McCall27b18f82009-11-17 02:14:36 +000010638 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10639 LookupQualifiedName(R, BaseRecord->getDecl());
10640 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010641
10642 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010643 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010644 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10645 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010646 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010647
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010648 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10649
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010650 // Perform overload resolution.
10651 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010652 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010653 case OR_Success:
10654 // Overload resolution succeeded; we'll build the call below.
10655 break;
10656
10657 case OR_No_Viable_Function:
10658 if (CandidateSet.empty())
10659 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010660 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010661 else
10662 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010663 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010664 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010665 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010666
10667 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010668 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10669 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010670 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010671 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010672
10673 case OR_Deleted:
10674 Diag(OpLoc, diag::err_ovl_deleted_oper)
10675 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010676 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010677 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010678 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010679 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010680 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010681 }
10682
Eli Friedmanfa0df832012-02-02 03:46:19 +000010683 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010684 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010685 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010686
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010687 // Convert the object parameter.
10688 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010689 ExprResult BaseResult =
10690 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10691 Best->FoundDecl, Method);
10692 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010693 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010694 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010695
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010696 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010697 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10698 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010699 if (FnExpr.isInvalid())
10700 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010701
John McCall7decc9e2010-11-18 06:31:45 +000010702 QualType ResultTy = Method->getResultType();
10703 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10704 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010705 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010706 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010707 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010708
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010709 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010710 Method))
10711 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010712
10713 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010714}
10715
Douglas Gregorcd695e52008-11-10 20:40:00 +000010716/// FixOverloadedFunctionReference - E is an expression that refers to
10717/// a C++ overloaded function (possibly with some parentheses and
10718/// perhaps a '&' around it). We have resolved the overloaded function
10719/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010720/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010721Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010722 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010723 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010724 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10725 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010726 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010727 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010728
Douglas Gregor51c538b2009-11-20 19:42:02 +000010729 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010730 }
10731
Douglas Gregor51c538b2009-11-20 19:42:02 +000010732 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010733 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10734 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010735 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010736 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010737 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010738 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010739 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010740 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010741
10742 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010743 ICE->getCastKind(),
10744 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010745 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010746 }
10747
Douglas Gregor51c538b2009-11-20 19:42:02 +000010748 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010749 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010750 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010751 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10752 if (Method->isStatic()) {
10753 // Do nothing: static member functions aren't any different
10754 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010755 } else {
John McCalle66edc12009-11-24 19:00:30 +000010756 // Fix the sub expression, which really has to be an
10757 // UnresolvedLookupExpr holding an overloaded member function
10758 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010759 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10760 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010761 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010762 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010763
John McCalld14a8642009-11-21 08:51:07 +000010764 assert(isa<DeclRefExpr>(SubExpr)
10765 && "fixed to something other than a decl ref");
10766 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10767 && "fixed to a member ref with no nested name qualifier");
10768
10769 // We have taken the address of a pointer to member
10770 // function. Perform the computation here so that we get the
10771 // appropriate pointer to member type.
10772 QualType ClassType
10773 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10774 QualType MemPtrType
10775 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10776
John McCall7decc9e2010-11-18 06:31:45 +000010777 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10778 VK_RValue, OK_Ordinary,
10779 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010780 }
10781 }
John McCall16df1e52010-03-30 21:47:33 +000010782 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10783 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010784 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010785 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010786
John McCalle3027922010-08-25 11:45:40 +000010787 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010788 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010789 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010790 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010791 }
John McCalld14a8642009-11-21 08:51:07 +000010792
10793 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010794 // FIXME: avoid copy.
10795 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010796 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010797 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10798 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010799 }
10800
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010801 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10802 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000010803 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010804 Fn,
10805 ULE->getNameLoc(),
10806 Fn->getType(),
10807 VK_LValue,
10808 Found.getDecl(),
10809 TemplateArgs);
10810 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10811 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010812 }
10813
John McCall10eae182009-11-30 22:42:35 +000010814 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010815 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010816 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10817 if (MemExpr->hasExplicitTemplateArgs()) {
10818 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10819 TemplateArgs = &TemplateArgsBuffer;
10820 }
John McCall6b51f282009-11-23 01:53:49 +000010821
John McCall2d74de92009-12-01 22:10:20 +000010822 Expr *Base;
10823
John McCall7decc9e2010-11-18 06:31:45 +000010824 // If we're filling in a static method where we used to have an
10825 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010826 if (MemExpr->isImplicitAccess()) {
10827 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010828 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10829 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000010830 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010831 Fn,
10832 MemExpr->getMemberLoc(),
10833 Fn->getType(),
10834 VK_LValue,
10835 Found.getDecl(),
10836 TemplateArgs);
10837 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10838 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010839 } else {
10840 SourceLocation Loc = MemExpr->getMemberLoc();
10841 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010842 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000010843 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000010844 Base = new (Context) CXXThisExpr(Loc,
10845 MemExpr->getBaseType(),
10846 /*isImplicit=*/true);
10847 }
John McCall2d74de92009-12-01 22:10:20 +000010848 } else
John McCallc3007a22010-10-26 07:05:15 +000010849 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010850
John McCall4adb38c2011-04-27 00:36:17 +000010851 ExprValueKind valueKind;
10852 QualType type;
10853 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10854 valueKind = VK_LValue;
10855 type = Fn->getType();
10856 } else {
10857 valueKind = VK_RValue;
10858 type = Context.BoundMemberTy;
10859 }
10860
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010861 MemberExpr *ME = MemberExpr::Create(Context, Base,
10862 MemExpr->isArrow(),
10863 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000010864 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010865 Fn,
10866 Found,
10867 MemExpr->getMemberNameInfo(),
10868 TemplateArgs,
10869 type, valueKind, OK_Ordinary);
10870 ME->setHadMultipleCandidates(true);
10871 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010873
John McCallc3007a22010-10-26 07:05:15 +000010874 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000010875}
10876
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010877ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010878 DeclAccessPair Found,
10879 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010880 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010881}
10882
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010883} // end namespace clang