blob: 2b567b3984220fe66cafde78cbd02169c29d9799 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara7cc58b42011-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 Wiegley429bb272011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000052}
53
John McCall120d63c2010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor60d62c22008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202}
203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000242bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregorf9af5242011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265 switch (ICE->getCastKind()) {
266 case CK_NoOp:
267 case CK_IntegralCast:
268 case CK_IntegralToBoolean:
269 case CK_IntegralToFloating:
270 case CK_FloatingToIntegral:
271 case CK_FloatingToBoolean:
272 case CK_FloatingCast:
273 Converted = ICE->getSubExpr();
274 continue;
275
276 default:
277 return Converted;
278 }
279 }
280
281 return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx The AST context.
288/// \param Converted The result of applying this standard conversion sequence.
289/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
290/// value of the expression prior to the narrowing conversion.
291NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue) const {
Richard Smith4c3fc9b2012-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 Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000422 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000423 bool PrintedSomething = false;
424 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000425 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000426 PrintedSomething = true;
427 }
428
429 if (Second != ICK_Identity) {
430 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000431 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000432 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434
435 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000436 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000437 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000438 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000439 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000440 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000441 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 PrintedSomething = true;
443 }
444
445 if (Third != ICK_Identity) {
446 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000447 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000448 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000449 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << "No conversions required";
Douglas Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000461 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000462 if (Before.First || Before.Second || Before.Third) {
463 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000464 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000466 if (ConversionFunction)
467 OS << '\'' << *ConversionFunction << '\'';
468 else
469 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 switch (ConversionKind) {
481 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000482 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 Standard.DebugPrint();
484 break;
485 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000486 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 UserDefined.DebugPrint();
488 break;
489 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 break;
John McCall1d318332010-01-12 00:44:57 +0000492 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000493 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000494 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 break;
498 }
499
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000500 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501}
502
John McCall1d318332010-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 Gregora9333192010-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 Takumidfbb02a2011-01-27 07:10:08 +0000527
Douglas Gregora9333192010-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 Gregorff5adac2010-05-08 20:18:54 +0000531static MakeDeductionFailureInfo(ASTContext &Context,
532 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000533 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000540 case Sema::TDK_TooManyArguments:
541 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000542 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000543
Douglas Gregora9333192010-05-08 17:41:32 +0000544 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000545 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000546 Result.Data = Info.Param.getOpaqueValue();
547 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000548
Douglas Gregora9333192010-05-08 17:41:32 +0000549 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000550 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-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 Gregora9333192010-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 Takumidfbb02a2011-01-27 07:10:08 +0000559
Douglas Gregora9333192010-05-08 17:41:32 +0000560 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000561 Result.Data = Info.take();
562 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000565 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora9333192010-05-08 17:41:32 +0000569 return Result;
570}
John McCall1d318332010-01-12 00:44:57 +0000571
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000577 case Sema::TDK_TooManyArguments:
578 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000579 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora9333192010-05-08 17:41:32 +0000582 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000583 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000584 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000585 Data = 0;
586 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000587
588 case Sema::TDK_SubstitutionFailure:
589 // FIXME: Destroy the template arugment list?
590 Data = 0;
591 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000592
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000593 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000594 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000595 case Sema::TDK_FailedOverloadResolution:
596 break;
597 }
598}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
600TemplateParameter
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000608 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora9333192010-05-08 17:41:32 +0000610 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000611 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000612 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000613
614 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000615 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000616 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora9333192010-05-08 17:41:32 +0000618 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
621 break;
622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregora9333192010-05-08 17:41:32 +0000624 return TemplateParameter();
625}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
Douglas Gregorec20f462010-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 McCall57e97782010-08-05 09:05:08 +0000637 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000638 return 0;
639
640 case Sema::TDK_SubstitutionFailure:
641 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642
Douglas Gregorec20f462010-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 Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000657 case Sema::TDK_TooManyArguments:
658 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000659 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000660 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000661 return 0;
662
Douglas Gregora9333192010-05-08 17:41:32 +0000663 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000664 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000666
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000667 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000668 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000669 case Sema::TDK_FailedOverloadResolution:
670 break;
671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672
Douglas Gregora9333192010-05-08 17:41:32 +0000673 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000674}
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000682 case Sema::TDK_TooManyArguments:
683 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000685 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000686 return 0;
687
Douglas Gregora9333192010-05-08 17:41:32 +0000688 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000689 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000690 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
691
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000692 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000693 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000694 case Sema::TDK_FailedOverloadResolution:
695 break;
696 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Douglas Gregora9333192010-05-08 17:41:32 +0000698 return 0;
699}
700
701void OverloadCandidateSet::clear() {
Benjamin Kramer9e2822b2012-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 Kramer314f5542012-01-14 19:31:39 +0000705 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000706 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000707 Functions.clear();
708}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000709
John McCall5acb0c92011-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) {
Richard Smith76f3f692012-02-22 02:04:18 +0000743 S.RequireCompleteType(E->getExprLoc(), E->getType(), 0);
744
John McCall5acb0c92011-10-17 18:40:02 +0000745 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
746 // We can't handle overloaded expressions here because overload
747 // resolution might reasonably tweak them.
748 if (placeholder->getKind() == BuiltinType::Overload) return false;
749
750 // If the context potentially accepts unbridged ARC casts, strip
751 // the unbridged cast and add it to the collection for later restoration.
752 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
753 unbridgedCasts) {
754 unbridgedCasts->save(S, E);
755 return false;
756 }
757
758 // Go ahead and check everything else.
759 ExprResult result = S.CheckPlaceholderExpr(E);
760 if (result.isInvalid())
761 return true;
762
763 E = result.take();
764 return false;
765 }
766
767 // Nothing to do.
768 return false;
769}
770
771/// checkArgPlaceholdersForOverload - Check a set of call operands for
772/// placeholders.
773static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
774 unsigned numArgs,
775 UnbridgedCastsSet &unbridged) {
776 for (unsigned i = 0; i != numArgs; ++i)
777 if (checkPlaceholderForOverload(S, args[i], &unbridged))
778 return true;
779
780 return false;
781}
782
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000783// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000784// overload of the declarations in Old. This routine returns false if
785// New and Old cannot be overloaded, e.g., if New has the same
786// signature as some function in Old (C++ 1.3.10) or if the Old
787// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000788// it does return false, MatchedDecl will point to the decl that New
789// cannot be overloaded with. This decl may be a UsingShadowDecl on
790// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000791//
792// Example: Given the following input:
793//
794// void f(int, float); // #1
795// void f(int, int); // #2
796// int f(int, int); // #3
797//
798// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000799// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000800//
John McCall51fa86f2009-12-02 08:47:38 +0000801// When we process #2, Old contains only the FunctionDecl for #1. By
802// comparing the parameter types, we see that #1 and #2 are overloaded
803// (since they have different signatures), so this routine returns
804// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805//
John McCall51fa86f2009-12-02 08:47:38 +0000806// When we process #3, Old is an overload set containing #1 and #2. We
807// compare the signatures of #3 to #1 (they're overloaded, so we do
808// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
809// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000810// signature), IsOverload returns false and MatchedDecl will be set to
811// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000812//
813// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
814// into a class by a using declaration. The rules for whether to hide
815// shadow declarations ignore some properties which otherwise figure
816// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000817Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000818Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
819 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000820 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000821 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000822 NamedDecl *OldD = *I;
823
824 bool OldIsUsingDecl = false;
825 if (isa<UsingShadowDecl>(OldD)) {
826 OldIsUsingDecl = true;
827
828 // We can always introduce two using declarations into the same
829 // context, even if they have identical signatures.
830 if (NewIsUsingDecl) continue;
831
832 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
833 }
834
835 // If either declaration was introduced by a using declaration,
836 // we'll need to use slightly different rules for matching.
837 // Essentially, these rules are the normal rules, except that
838 // function templates hide function templates with different
839 // return types or template parameter lists.
840 bool UseMemberUsingDeclRules =
841 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
842
John McCall51fa86f2009-12-02 08:47:38 +0000843 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000844 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
845 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
846 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
847 continue;
848 }
849
John McCall871b2e72009-12-09 03:35:25 +0000850 Match = *I;
851 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000852 }
John McCall51fa86f2009-12-02 08:47:38 +0000853 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000854 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
855 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
856 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
857 continue;
858 }
859
John McCall871b2e72009-12-09 03:35:25 +0000860 Match = *I;
861 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000862 }
John McCalld7945c62010-11-10 03:01:53 +0000863 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000864 // We can overload with these, which can show up when doing
865 // redeclaration checks for UsingDecls.
866 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000867 } else if (isa<TagDecl>(OldD)) {
868 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000869 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
870 // Optimistically assume that an unresolved using decl will
871 // overload; if it doesn't, we'll have to diagnose during
872 // template instantiation.
873 } else {
John McCall68263142009-11-18 22:49:29 +0000874 // (C++ 13p1):
875 // Only function declarations can be overloaded; object and type
876 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000877 Match = *I;
878 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000879 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000880 }
John McCall68263142009-11-18 22:49:29 +0000881
John McCall871b2e72009-12-09 03:35:25 +0000882 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000883}
884
John McCallad00b772010-06-16 08:42:20 +0000885bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
886 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000887 // If both of the functions are extern "C", then they are not
888 // overloads.
889 if (Old->isExternC() && New->isExternC())
890 return false;
891
John McCall68263142009-11-18 22:49:29 +0000892 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
893 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
894
895 // C++ [temp.fct]p2:
896 // A function template can be overloaded with other function templates
897 // and with normal (non-template) functions.
898 if ((OldTemplate == 0) != (NewTemplate == 0))
899 return true;
900
901 // Is the function New an overload of the function Old?
902 QualType OldQType = Context.getCanonicalType(Old->getType());
903 QualType NewQType = Context.getCanonicalType(New->getType());
904
905 // Compare the signatures (C++ 1.3.10) of the two functions to
906 // determine whether they are overloads. If we find any mismatch
907 // in the signature, they are overloads.
908
909 // If either of these functions is a K&R-style function (no
910 // prototype), then we consider them to have matching signatures.
911 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
912 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
913 return false;
914
John McCallf4c73712011-01-19 06:33:43 +0000915 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
916 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000917
918 // The signature of a function includes the types of its
919 // parameters (C++ 1.3.10), which includes the presence or absence
920 // of the ellipsis; see C++ DR 357).
921 if (OldQType != NewQType &&
922 (OldType->getNumArgs() != NewType->getNumArgs() ||
923 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000924 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000925 return true;
926
927 // C++ [temp.over.link]p4:
928 // The signature of a function template consists of its function
929 // signature, its return type and its template parameter list. The names
930 // of the template parameters are significant only for establishing the
931 // relationship between the template parameters and the rest of the
932 // signature.
933 //
934 // We check the return type and template parameter lists for function
935 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000936 //
937 // However, we don't consider either of these when deciding whether
938 // a member introduced by a shadow declaration is hidden.
939 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000940 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
941 OldTemplate->getTemplateParameters(),
942 false, TPL_TemplateMatch) ||
943 OldType->getResultType() != NewType->getResultType()))
944 return true;
945
946 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000947 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000948 //
949 // As part of this, also check whether one of the member functions
950 // is static, in which case they are not overloads (C++
951 // 13.1p2). While not part of the definition of the signature,
952 // this check is important to determine whether these functions
953 // can be overloaded.
954 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
955 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
956 if (OldMethod && NewMethod &&
957 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000958 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000959 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
960 if (!UseUsingDeclRules &&
961 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
962 (OldMethod->getRefQualifier() == RQ_None ||
963 NewMethod->getRefQualifier() == RQ_None)) {
964 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000965 // - Member function declarations with the same name and the same
966 // parameter-type-list as well as member function template
967 // declarations with the same name, the same parameter-type-list, and
968 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000969 // them, but not all, have a ref-qualifier (8.3.5).
970 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
971 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
972 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
973 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000974
John McCall68263142009-11-18 22:49:29 +0000975 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000976 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000977
John McCall68263142009-11-18 22:49:29 +0000978 // The signatures match; this is not an overload.
979 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000980}
981
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000982/// \brief Checks availability of the function depending on the current
983/// function context. Inside an unavailable function, unavailability is ignored.
984///
985/// \returns true if \arg FD is unavailable and current context is inside
986/// an available function, false otherwise.
987bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
988 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
989}
990
Sebastian Redlcf15cef2011-12-22 18:58:38 +0000991/// \brief Tries a user-defined conversion from From to ToType.
992///
993/// Produces an implicit conversion sequence for when a standard conversion
994/// is not an option. See TryImplicitConversion for more information.
995static ImplicitConversionSequence
996TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
997 bool SuppressUserConversions,
998 bool AllowExplicit,
999 bool InOverloadResolution,
1000 bool CStyle,
1001 bool AllowObjCWritebackConversion) {
1002 ImplicitConversionSequence ICS;
1003
1004 if (SuppressUserConversions) {
1005 // We're not in the case above, so there is no conversion that
1006 // we can perform.
1007 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1008 return ICS;
1009 }
1010
1011 // Attempt user-defined conversion.
1012 OverloadCandidateSet Conversions(From->getExprLoc());
1013 OverloadingResult UserDefResult
1014 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1015 AllowExplicit);
1016
1017 if (UserDefResult == OR_Success) {
1018 ICS.setUserDefined();
1019 // C++ [over.ics.user]p4:
1020 // A conversion of an expression of class type to the same class
1021 // type is given Exact Match rank, and a conversion of an
1022 // expression of class type to a base class of that type is
1023 // given Conversion rank, in spite of the fact that a copy
1024 // constructor (i.e., a user-defined conversion function) is
1025 // called for those cases.
1026 if (CXXConstructorDecl *Constructor
1027 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1028 QualType FromCanon
1029 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1030 QualType ToCanon
1031 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1032 if (Constructor->isCopyConstructor() &&
1033 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1034 // Turn this into a "standard" conversion sequence, so that it
1035 // gets ranked with standard conversion sequences.
1036 ICS.setStandard();
1037 ICS.Standard.setAsIdentityConversion();
1038 ICS.Standard.setFromType(From->getType());
1039 ICS.Standard.setAllToTypes(ToType);
1040 ICS.Standard.CopyConstructor = Constructor;
1041 if (ToCanon != FromCanon)
1042 ICS.Standard.Second = ICK_Derived_To_Base;
1043 }
1044 }
1045
1046 // C++ [over.best.ics]p4:
1047 // However, when considering the argument of a user-defined
1048 // conversion function that is a candidate by 13.3.1.3 when
1049 // invoked for the copying of the temporary in the second step
1050 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1051 // 13.3.1.6 in all cases, only standard conversion sequences and
1052 // ellipsis conversion sequences are allowed.
1053 if (SuppressUserConversions && ICS.isUserDefined()) {
1054 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1055 }
1056 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1057 ICS.setAmbiguous();
1058 ICS.Ambiguous.setFromType(From->getType());
1059 ICS.Ambiguous.setToType(ToType);
1060 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1061 Cand != Conversions.end(); ++Cand)
1062 if (Cand->Viable)
1063 ICS.Ambiguous.addConversion(Cand->Function);
1064 } else {
1065 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1066 }
1067
1068 return ICS;
1069}
1070
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001071/// TryImplicitConversion - Attempt to perform an implicit conversion
1072/// from the given expression (Expr) to the given type (ToType). This
1073/// function returns an implicit conversion sequence that can be used
1074/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001075///
1076/// void f(float f);
1077/// void g(int i) { f(i); }
1078///
1079/// this routine would produce an implicit conversion sequence to
1080/// describe the initialization of f from i, which will be a standard
1081/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1082/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1083//
1084/// Note that this routine only determines how the conversion can be
1085/// performed; it does not actually perform the conversion. As such,
1086/// it will not produce any diagnostics if no conversion is available,
1087/// but will instead return an implicit conversion sequence of kind
1088/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001089///
1090/// If @p SuppressUserConversions, then user-defined conversions are
1091/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001092/// If @p AllowExplicit, then explicit user-defined conversions are
1093/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001094///
1095/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1096/// writeback conversion, which allows __autoreleasing id* parameters to
1097/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001098static ImplicitConversionSequence
1099TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1100 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001101 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001102 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001103 bool CStyle,
1104 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001105 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001106 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001107 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001108 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001109 return ICS;
1110 }
1111
John McCall120d63c2010-08-24 20:38:10 +00001112 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001113 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001114 return ICS;
1115 }
1116
Douglas Gregor604eb652010-08-11 02:15:33 +00001117 // C++ [over.ics.user]p4:
1118 // A conversion of an expression of class type to the same class
1119 // type is given Exact Match rank, and a conversion of an
1120 // expression of class type to a base class of that type is
1121 // given Conversion rank, in spite of the fact that a copy/move
1122 // constructor (i.e., a user-defined conversion function) is
1123 // called for those cases.
1124 QualType FromType = From->getType();
1125 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001126 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1127 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001128 ICS.setStandard();
1129 ICS.Standard.setAsIdentityConversion();
1130 ICS.Standard.setFromType(FromType);
1131 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001132
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001133 // We don't actually check at this point whether there is a valid
1134 // copy/move constructor, since overloading just assumes that it
1135 // exists. When we actually perform initialization, we'll find the
1136 // appropriate constructor to copy the returned object, if needed.
1137 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001138
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001139 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001140 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001141 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001142
Douglas Gregor604eb652010-08-11 02:15:33 +00001143 return ICS;
1144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001146 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1147 AllowExplicit, InOverloadResolution, CStyle,
1148 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001149}
1150
John McCallf85e1932011-06-15 23:02:42 +00001151ImplicitConversionSequence
1152Sema::TryImplicitConversion(Expr *From, QualType ToType,
1153 bool SuppressUserConversions,
1154 bool AllowExplicit,
1155 bool InOverloadResolution,
1156 bool CStyle,
1157 bool AllowObjCWritebackConversion) {
1158 return clang::TryImplicitConversion(*this, From, ToType,
1159 SuppressUserConversions, AllowExplicit,
1160 InOverloadResolution, CStyle,
1161 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001162}
1163
Douglas Gregor575c63a2010-04-16 22:27:05 +00001164/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001165/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001166/// converted expression. Flavor is the kind of conversion we're
1167/// performing, used in the error message. If @p AllowExplicit,
1168/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001169ExprResult
1170Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001171 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001172 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001173 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001174}
1175
John Wiegley429bb272011-04-08 18:41:53 +00001176ExprResult
1177Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001178 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001179 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001180 if (checkPlaceholderForOverload(*this, From))
1181 return ExprError();
1182
John McCallf85e1932011-06-15 23:02:42 +00001183 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1184 bool AllowObjCWritebackConversion
1185 = getLangOptions().ObjCAutoRefCount &&
1186 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001187
John McCall120d63c2010-08-24 20:38:10 +00001188 ICS = clang::TryImplicitConversion(*this, From, ToType,
1189 /*SuppressUserConversions=*/false,
1190 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001191 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001192 /*CStyle=*/false,
1193 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001194 return PerformImplicitConversion(From, ToType, ICS, Action);
1195}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001196
1197/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001198/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001199bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1200 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001201 if (Context.hasSameUnqualifiedType(FromType, ToType))
1202 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001203
John McCall00ccbef2010-12-21 00:44:39 +00001204 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1205 // where F adds one of the following at most once:
1206 // - a pointer
1207 // - a member pointer
1208 // - a block pointer
1209 CanQualType CanTo = Context.getCanonicalType(ToType);
1210 CanQualType CanFrom = Context.getCanonicalType(FromType);
1211 Type::TypeClass TyClass = CanTo->getTypeClass();
1212 if (TyClass != CanFrom->getTypeClass()) return false;
1213 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1214 if (TyClass == Type::Pointer) {
1215 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1216 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1217 } else if (TyClass == Type::BlockPointer) {
1218 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1219 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1220 } else if (TyClass == Type::MemberPointer) {
1221 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1222 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1223 } else {
1224 return false;
1225 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001226
John McCall00ccbef2010-12-21 00:44:39 +00001227 TyClass = CanTo->getTypeClass();
1228 if (TyClass != CanFrom->getTypeClass()) return false;
1229 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1230 return false;
1231 }
1232
1233 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1234 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1235 if (!EInfo.getNoReturn()) return false;
1236
1237 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1238 assert(QualType(FromFn, 0).isCanonical());
1239 if (QualType(FromFn, 0) != CanTo) return false;
1240
1241 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001242 return true;
1243}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001245/// \brief Determine whether the conversion from FromType to ToType is a valid
1246/// vector conversion.
1247///
1248/// \param ICK Will be set to the vector conversion kind, if this is a vector
1249/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1251 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001252 // We need at least one of these types to be a vector type to have a vector
1253 // conversion.
1254 if (!ToType->isVectorType() && !FromType->isVectorType())
1255 return false;
1256
1257 // Identical types require no conversions.
1258 if (Context.hasSameUnqualifiedType(FromType, ToType))
1259 return false;
1260
1261 // There are no conversions between extended vector types, only identity.
1262 if (ToType->isExtVectorType()) {
1263 // There are no conversions between extended vector types other than the
1264 // identity conversion.
1265 if (FromType->isExtVectorType())
1266 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001268 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001269 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001270 ICK = ICK_Vector_Splat;
1271 return true;
1272 }
1273 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001274
1275 // We can perform the conversion between vector types in the following cases:
1276 // 1)vector types are equivalent AltiVec and GCC vector types
1277 // 2)lax vector conversions are permitted and the vector types are of the
1278 // same size
1279 if (ToType->isVectorType() && FromType->isVectorType()) {
1280 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001281 (Context.getLangOptions().LaxVectorConversions &&
1282 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001283 ICK = ICK_Vector_Conversion;
1284 return true;
1285 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001286 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001287
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001288 return false;
1289}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001290
Douglas Gregor60d62c22008-10-31 16:23:19 +00001291/// IsStandardConversion - Determines whether there is a standard
1292/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1293/// expression From to the type ToType. Standard conversion sequences
1294/// only consider non-class types; for conversions that involve class
1295/// types, use TryImplicitConversion. If a conversion exists, SCS will
1296/// contain the standard conversion sequence required to perform this
1297/// conversion and this routine will return true. Otherwise, this
1298/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001299static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1300 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001301 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001302 bool CStyle,
1303 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001305
Douglas Gregor60d62c22008-10-31 16:23:19 +00001306 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001307 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001308 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001309 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001310 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001311 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001312
Douglas Gregorf9201e02009-02-11 23:02:49 +00001313 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001314 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001315 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001316 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001317 return false;
1318
Mike Stump1eb44332009-09-09 15:08:12 +00001319 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001320 }
1321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001322 // The first conversion can be an lvalue-to-rvalue conversion,
1323 // array-to-pointer conversion, or function-to-pointer conversion
1324 // (C++ 4p1).
1325
John McCall120d63c2010-08-24 20:38:10 +00001326 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001327 DeclAccessPair AccessPair;
1328 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001329 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001330 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001331 // We were able to resolve the address of the overloaded function,
1332 // so we can convert to the type of that function.
1333 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001334
1335 // we can sometimes resolve &foo<int> regardless of ToType, so check
1336 // if the type matches (identity) or we are converting to bool
1337 if (!S.Context.hasSameUnqualifiedType(
1338 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1339 QualType resultTy;
1340 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001341 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001342 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1343 // otherwise, only a boolean conversion is standard
1344 if (!ToType->isBooleanType())
1345 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347
Chandler Carruth90434232011-03-29 08:08:18 +00001348 // Check if the "from" expression is taking the address of an overloaded
1349 // function and recompute the FromType accordingly. Take advantage of the
1350 // fact that non-static member functions *must* have such an address-of
1351 // expression.
1352 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1353 if (Method && !Method->isStatic()) {
1354 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1355 "Non-unary operator on non-static member address");
1356 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1357 == UO_AddrOf &&
1358 "Non-address-of operator on non-static member address");
1359 const Type *ClassType
1360 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1361 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001362 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1363 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1364 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001365 "Non-address-of operator for overloaded function expression");
1366 FromType = S.Context.getPointerType(FromType);
1367 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001368
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001369 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001370 assert(S.Context.hasSameType(
1371 FromType,
1372 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001373 } else {
1374 return false;
1375 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001376 }
John McCall21480112011-08-30 00:57:29 +00001377 // Lvalue-to-rvalue conversion (C++11 4.1):
1378 // A glvalue (3.10) of a non-function, non-array type T can
1379 // be converted to a prvalue.
1380 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001381 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001382 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001383 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001384 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001385
1386 // If T is a non-class type, the type of the rvalue is the
1387 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001388 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1389 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001390 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001391 } else if (FromType->isArrayType()) {
1392 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001393 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001394
1395 // An lvalue or rvalue of type "array of N T" or "array of unknown
1396 // bound of T" can be converted to an rvalue of type "pointer to
1397 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001398 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001399
John McCall120d63c2010-08-24 20:38:10 +00001400 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001401 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001402 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001403
1404 // For the purpose of ranking in overload resolution
1405 // (13.3.3.1.1), this conversion is considered an
1406 // array-to-pointer conversion followed by a qualification
1407 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001408 SCS.Second = ICK_Identity;
1409 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001410 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001411 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001412 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001413 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001414 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001415 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001416 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001417
1418 // An lvalue of function type T can be converted to an rvalue of
1419 // type "pointer to T." The result is a pointer to the
1420 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001421 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001422 } else {
1423 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001424 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001425 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001426 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001427
1428 // The second conversion can be an integral promotion, floating
1429 // point promotion, integral conversion, floating point conversion,
1430 // floating-integral conversion, pointer conversion,
1431 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001432 // For overloading in C, this can also be a "compatible-type"
1433 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001434 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001435 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001436 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001437 // The unqualified versions of the types are the same: there's no
1438 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001439 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001440 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001441 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001442 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001443 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001444 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001445 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001446 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001447 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001448 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001449 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001450 SCS.Second = ICK_Complex_Promotion;
1451 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001452 } else if (ToType->isBooleanType() &&
1453 (FromType->isArithmeticType() ||
1454 FromType->isAnyPointerType() ||
1455 FromType->isBlockPointerType() ||
1456 FromType->isMemberPointerType() ||
1457 FromType->isNullPtrType())) {
1458 // Boolean conversions (C++ 4.12).
1459 SCS.Second = ICK_Boolean_Conversion;
1460 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001461 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001462 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001463 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001464 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001465 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001466 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001467 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001468 SCS.Second = ICK_Complex_Conversion;
1469 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001470 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1471 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001472 // Complex-real conversions (C99 6.3.1.7)
1473 SCS.Second = ICK_Complex_Real;
1474 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001475 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001476 // Floating point conversions (C++ 4.8).
1477 SCS.Second = ICK_Floating_Conversion;
1478 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001479 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001480 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001481 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001482 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001483 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001484 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001485 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001486 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001487 SCS.Second = ICK_Block_Pointer_Conversion;
1488 } else if (AllowObjCWritebackConversion &&
1489 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1490 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001491 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1492 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001493 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001494 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001495 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001496 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001498 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001499 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001500 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001501 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001502 SCS.Second = SecondICK;
1503 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001504 } else if (!S.getLangOptions().CPlusPlus &&
1505 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001506 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001507 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001508 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001509 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001510 // Treat a conversion that strips "noreturn" as an identity conversion.
1511 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001512 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1513 InOverloadResolution,
1514 SCS, CStyle)) {
1515 SCS.Second = ICK_TransparentUnionConversion;
1516 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517 } else {
1518 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001519 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001520 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001521 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001522
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001523 QualType CanonFrom;
1524 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001525 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001526 bool ObjCLifetimeConversion;
1527 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1528 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001529 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001530 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001532 CanonFrom = S.Context.getCanonicalType(FromType);
1533 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001534 } else {
1535 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001536 SCS.Third = ICK_Identity;
1537
Mike Stump1eb44332009-09-09 15:08:12 +00001538 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001539 // [...] Any difference in top-level cv-qualification is
1540 // subsumed by the initialization itself and does not constitute
1541 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001542 CanonFrom = S.Context.getCanonicalType(FromType);
1543 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001544 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001545 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001546 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001547 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1548 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001549 FromType = ToType;
1550 CanonFrom = CanonTo;
1551 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001553 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001554
1555 // If we have not converted the argument type to the parameter type,
1556 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001557 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001558 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001559
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001561}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001562
1563static bool
1564IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1565 QualType &ToType,
1566 bool InOverloadResolution,
1567 StandardConversionSequence &SCS,
1568 bool CStyle) {
1569
1570 const RecordType *UT = ToType->getAsUnionType();
1571 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1572 return false;
1573 // The field to initialize within the transparent union.
1574 RecordDecl *UD = UT->getDecl();
1575 // It's compatible if the expression matches any of the fields.
1576 for (RecordDecl::field_iterator it = UD->field_begin(),
1577 itend = UD->field_end();
1578 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001579 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1580 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001581 ToType = it->getType();
1582 return true;
1583 }
1584 }
1585 return false;
1586}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001587
1588/// IsIntegralPromotion - Determines whether the conversion from the
1589/// expression From (whose potentially-adjusted type is FromType) to
1590/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1591/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001592bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001593 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001594 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001595 if (!To) {
1596 return false;
1597 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001598
1599 // An rvalue of type char, signed char, unsigned char, short int, or
1600 // unsigned short int can be converted to an rvalue of type int if
1601 // int can represent all the values of the source type; otherwise,
1602 // the source rvalue can be converted to an rvalue of type unsigned
1603 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001604 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1605 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001606 if (// We can promote any signed, promotable integer type to an int
1607 (FromType->isSignedIntegerType() ||
1608 // We can promote any unsigned integer type whose size is
1609 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001610 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001611 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001612 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001613 }
1614
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001615 return To->getKind() == BuiltinType::UInt;
1616 }
1617
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001618 // C++0x [conv.prom]p3:
1619 // A prvalue of an unscoped enumeration type whose underlying type is not
1620 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1621 // following types that can represent all the values of the enumeration
1622 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1623 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001624 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001625 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001626 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001627 // with lowest integer conversion rank (4.13) greater than the rank of long
1628 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001629 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001630 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1631 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1632 // provided for a scoped enumeration.
1633 if (FromEnumType->getDecl()->isScoped())
1634 return false;
1635
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001636 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001637 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001638 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001639 return Context.hasSameUnqualifiedType(ToType,
1640 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001641 }
John McCall842aef82009-12-09 09:09:27 +00001642
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001643 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001644 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1645 // to an rvalue a prvalue of the first of the following types that can
1646 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001647 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001649 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001651 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001652 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001653 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001654 // Determine whether the type we're converting from is signed or
1655 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001656 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001658
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001659 // The types we'll try to promote to, in the appropriate
1660 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001661 QualType PromoteTypes[6] = {
1662 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001663 Context.LongTy, Context.UnsignedLongTy ,
1664 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001666 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1668 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001669 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1671 // We found the type that we can promote to. If this is the
1672 // type we wanted, we have a promotion. Otherwise, no
1673 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001674 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001675 }
1676 }
1677 }
1678
1679 // An rvalue for an integral bit-field (9.6) can be converted to an
1680 // rvalue of type int if int can represent all the values of the
1681 // bit-field; otherwise, it can be converted to unsigned int if
1682 // unsigned int can represent all the values of the bit-field. If
1683 // the bit-field is larger yet, no integral promotion applies to
1684 // it. If the bit-field has an enumerated type, it is treated as any
1685 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001686 // FIXME: We should delay checking of bit-fields until we actually perform the
1687 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001688 using llvm::APSInt;
1689 if (From)
1690 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001691 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001692 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001693 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1694 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1695 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Douglas Gregor86f19402008-12-20 23:49:58 +00001697 // Are we promoting to an int from a bitfield that fits in an int?
1698 if (BitWidth < ToSize ||
1699 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1700 return To->getKind() == BuiltinType::Int;
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor86f19402008-12-20 23:49:58 +00001703 // Are we promoting to an unsigned int from an unsigned bitfield
1704 // that fits into an unsigned int?
1705 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1706 return To->getKind() == BuiltinType::UInt;
1707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor86f19402008-12-20 23:49:58 +00001709 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001710 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001713 // An rvalue of type bool can be converted to an rvalue of type int,
1714 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001715 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001716 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001717 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001718
1719 return false;
1720}
1721
1722/// IsFloatingPointPromotion - Determines whether the conversion from
1723/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1724/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001725bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001726 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1727 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001728 /// An rvalue of type float can be converted to an rvalue of type
1729 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001730 if (FromBuiltin->getKind() == BuiltinType::Float &&
1731 ToBuiltin->getKind() == BuiltinType::Double)
1732 return true;
1733
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001734 // C99 6.3.1.5p1:
1735 // When a float is promoted to double or long double, or a
1736 // double is promoted to long double [...].
1737 if (!getLangOptions().CPlusPlus &&
1738 (FromBuiltin->getKind() == BuiltinType::Float ||
1739 FromBuiltin->getKind() == BuiltinType::Double) &&
1740 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1741 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001742
1743 // Half can be promoted to float.
1744 if (FromBuiltin->getKind() == BuiltinType::Half &&
1745 ToBuiltin->getKind() == BuiltinType::Float)
1746 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001747 }
1748
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001749 return false;
1750}
1751
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001752/// \brief Determine if a conversion is a complex promotion.
1753///
1754/// A complex promotion is defined as a complex -> complex conversion
1755/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001756/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001757bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001758 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001759 if (!FromComplex)
1760 return false;
1761
John McCall183700f2009-09-21 23:43:11 +00001762 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001763 if (!ToComplex)
1764 return false;
1765
1766 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001767 ToComplex->getElementType()) ||
1768 IsIntegralPromotion(0, FromComplex->getElementType(),
1769 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001770}
1771
Douglas Gregorcb7de522008-11-26 23:31:11 +00001772/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1773/// the pointer type FromPtr to a pointer to type ToPointee, with the
1774/// same type qualifiers as FromPtr has on its pointee type. ToType,
1775/// if non-empty, will be a pointer to ToType that may or may not have
1776/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001777///
Mike Stump1eb44332009-09-09 15:08:12 +00001778static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001779BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001780 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001781 ASTContext &Context,
1782 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001783 assert((FromPtr->getTypeClass() == Type::Pointer ||
1784 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1785 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786
John McCallf85e1932011-06-15 23:02:42 +00001787 /// Conversions to 'id' subsume cv-qualifier conversions.
1788 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001789 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001790
1791 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001792 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001793 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001794 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001795
John McCallf85e1932011-06-15 23:02:42 +00001796 if (StripObjCLifetime)
1797 Quals.removeObjCLifetime();
1798
Mike Stump1eb44332009-09-09 15:08:12 +00001799 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001800 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001801 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001802 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001803 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001804
1805 // Build a pointer to ToPointee. It has the right qualifiers
1806 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001807 if (isa<ObjCObjectPointerType>(ToType))
1808 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001809 return Context.getPointerType(ToPointee);
1810 }
1811
1812 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001813 QualType QualifiedCanonToPointee
1814 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001815
Douglas Gregorda80f742010-12-01 21:43:58 +00001816 if (isa<ObjCObjectPointerType>(ToType))
1817 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1818 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001819}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001820
Mike Stump1eb44332009-09-09 15:08:12 +00001821static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001822 bool InOverloadResolution,
1823 ASTContext &Context) {
1824 // Handle value-dependent integral null pointer constants correctly.
1825 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1826 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001827 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001828 return !InOverloadResolution;
1829
Douglas Gregorce940492009-09-25 04:25:58 +00001830 return Expr->isNullPointerConstant(Context,
1831 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1832 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001833}
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001835/// IsPointerConversion - Determines whether the conversion of the
1836/// expression From, which has the (possibly adjusted) type FromType,
1837/// can be converted to the type ToType via a pointer conversion (C++
1838/// 4.10). If so, returns true and places the converted type (that
1839/// might differ from ToType in its cv-qualifiers at some level) into
1840/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001841///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001842/// This routine also supports conversions to and from block pointers
1843/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1844/// pointers to interfaces. FIXME: Once we've determined the
1845/// appropriate overloading rules for Objective-C, we may want to
1846/// split the Objective-C checks into a different routine; however,
1847/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001848/// conversions, so for now they live here. IncompatibleObjC will be
1849/// set if the conversion is an allowed Objective-C conversion that
1850/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001851bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001852 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001853 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001854 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001855 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001856 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1857 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001858 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001859
Mike Stump1eb44332009-09-09 15:08:12 +00001860 // Conversion from a null pointer constant to any Objective-C pointer type.
1861 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001862 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001863 ConvertedType = ToType;
1864 return true;
1865 }
1866
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001867 // Blocks: Block pointers can be converted to void*.
1868 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001869 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001870 ConvertedType = ToType;
1871 return true;
1872 }
1873 // Blocks: A null pointer constant can be converted to a block
1874 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001875 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001876 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001877 ConvertedType = ToType;
1878 return true;
1879 }
1880
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001881 // If the left-hand-side is nullptr_t, the right side can be a null
1882 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001883 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001884 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001885 ConvertedType = ToType;
1886 return true;
1887 }
1888
Ted Kremenek6217b802009-07-29 21:53:49 +00001889 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001890 if (!ToTypePtr)
1891 return false;
1892
1893 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001894 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001895 ConvertedType = ToType;
1896 return true;
1897 }
Sebastian Redl07779722008-10-31 14:43:28 +00001898
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001899 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001900 // , including objective-c pointers.
1901 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001902 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1903 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001904 ConvertedType = BuildSimilarlyQualifiedPointerType(
1905 FromType->getAs<ObjCObjectPointerType>(),
1906 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001907 ToType, Context);
1908 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001909 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001910 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001911 if (!FromTypePtr)
1912 return false;
1913
1914 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001915
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001916 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001917 // pointer conversion, so don't do all of the work below.
1918 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1919 return false;
1920
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001921 // An rvalue of type "pointer to cv T," where T is an object type,
1922 // can be converted to an rvalue of type "pointer to cv void" (C++
1923 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001924 if (FromPointeeType->isIncompleteOrObjectType() &&
1925 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001926 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001927 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001928 ToType, Context,
1929 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001930 return true;
1931 }
1932
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001933 // MSVC allows implicit function to void* type conversion.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001934 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001935 ToPointeeType->isVoidType()) {
1936 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1937 ToPointeeType,
1938 ToType, Context);
1939 return true;
1940 }
1941
Douglas Gregorf9201e02009-02-11 23:02:49 +00001942 // When we're overloading in C, we allow a special kind of pointer
1943 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001944 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001945 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001946 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001947 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001948 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001949 return true;
1950 }
1951
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001952 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001953 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001954 // An rvalue of type "pointer to cv D," where D is a class type,
1955 // can be converted to an rvalue of type "pointer to cv B," where
1956 // B is a base class (clause 10) of D. If B is an inaccessible
1957 // (clause 11) or ambiguous (10.2) base class of D, a program that
1958 // necessitates this conversion is ill-formed. The result of the
1959 // conversion is a pointer to the base class sub-object of the
1960 // derived class object. The null pointer value is converted to
1961 // the null pointer value of the destination type.
1962 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001963 // Note that we do not check for ambiguity or inaccessibility
1964 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001965 if (getLangOptions().CPlusPlus &&
1966 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001967 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001968 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001969 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001970 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001971 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001972 ToType, Context);
1973 return true;
1974 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001975
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001976 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1977 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1978 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1979 ToPointeeType,
1980 ToType, Context);
1981 return true;
1982 }
1983
Douglas Gregorc7887512008-12-19 19:13:09 +00001984 return false;
1985}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001986
1987/// \brief Adopt the given qualifiers for the given type.
1988static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1989 Qualifiers TQs = T.getQualifiers();
1990
1991 // Check whether qualifiers already match.
1992 if (TQs == Qs)
1993 return T;
1994
1995 if (Qs.compatiblyIncludes(TQs))
1996 return Context.getQualifiedType(T, Qs);
1997
1998 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1999}
Douglas Gregorc7887512008-12-19 19:13:09 +00002000
2001/// isObjCPointerConversion - Determines whether this is an
2002/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2003/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002004bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002005 QualType& ConvertedType,
2006 bool &IncompatibleObjC) {
2007 if (!getLangOptions().ObjC1)
2008 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002009
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002010 // The set of qualifiers on the type we're converting from.
2011 Qualifiers FromQualifiers = FromType.getQualifiers();
2012
Steve Naroff14108da2009-07-10 23:34:53 +00002013 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002014 const ObjCObjectPointerType* ToObjCPtr =
2015 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002016 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002017 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002018
Steve Naroff14108da2009-07-10 23:34:53 +00002019 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002020 // If the pointee types are the same (ignoring qualifications),
2021 // then this is not a pointer conversion.
2022 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2023 FromObjCPtr->getPointeeType()))
2024 return false;
2025
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002026 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002027 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002028 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002029 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002030 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002031 return true;
2032 }
2033 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002034 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002035 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002036 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002037 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002038 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002039 return true;
2040 }
2041 // Objective C++: We're able to convert from a pointer to an
2042 // interface to a pointer to a different interface.
2043 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002044 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2045 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2046 if (getLangOptions().CPlusPlus && LHS && RHS &&
2047 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2048 FromObjCPtr->getPointeeType()))
2049 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002050 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002051 ToObjCPtr->getPointeeType(),
2052 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002053 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002054 return true;
2055 }
2056
2057 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2058 // Okay: this is some kind of implicit downcast of Objective-C
2059 // interfaces, which is permitted. However, we're going to
2060 // complain about it.
2061 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002062 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002063 ToObjCPtr->getPointeeType(),
2064 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002065 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002066 return true;
2067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068 }
Steve Naroff14108da2009-07-10 23:34:53 +00002069 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002070 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002071 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002072 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002073 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002074 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002075 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002076 // to a block pointer type.
2077 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002078 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002079 return true;
2080 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002081 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002082 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002083 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002084 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002085 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002086 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002087 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002088 return true;
2089 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002090 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002091 return false;
2092
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002093 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002094 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002095 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002096 else if (const BlockPointerType *FromBlockPtr =
2097 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002098 FromPointeeType = FromBlockPtr->getPointeeType();
2099 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002100 return false;
2101
Douglas Gregorc7887512008-12-19 19:13:09 +00002102 // If we have pointers to pointers, recursively check whether this
2103 // is an Objective-C conversion.
2104 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2105 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2106 IncompatibleObjC)) {
2107 // We always complain about this conversion.
2108 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002109 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002110 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002111 return true;
2112 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002113 // Allow conversion of pointee being objective-c pointer to another one;
2114 // as in I* to id.
2115 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2116 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2117 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2118 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002119
Douglas Gregorda80f742010-12-01 21:43:58 +00002120 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002121 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002122 return true;
2123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002125 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002126 // differences in the argument and result types are in Objective-C
2127 // pointer conversions. If so, we permit the conversion (but
2128 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002129 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002130 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002131 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002132 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002133 if (FromFunctionType && ToFunctionType) {
2134 // If the function types are exactly the same, this isn't an
2135 // Objective-C pointer conversion.
2136 if (Context.getCanonicalType(FromPointeeType)
2137 == Context.getCanonicalType(ToPointeeType))
2138 return false;
2139
2140 // Perform the quick checks that will tell us whether these
2141 // function types are obviously different.
2142 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2143 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2144 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2145 return false;
2146
2147 bool HasObjCConversion = false;
2148 if (Context.getCanonicalType(FromFunctionType->getResultType())
2149 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2150 // Okay, the types match exactly. Nothing to do.
2151 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2152 ToFunctionType->getResultType(),
2153 ConvertedType, IncompatibleObjC)) {
2154 // Okay, we have an Objective-C pointer conversion.
2155 HasObjCConversion = true;
2156 } else {
2157 // Function types are too different. Abort.
2158 return false;
2159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Douglas Gregorc7887512008-12-19 19:13:09 +00002161 // Check argument types.
2162 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2163 ArgIdx != NumArgs; ++ArgIdx) {
2164 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2165 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2166 if (Context.getCanonicalType(FromArgType)
2167 == Context.getCanonicalType(ToArgType)) {
2168 // Okay, the types match exactly. Nothing to do.
2169 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2170 ConvertedType, IncompatibleObjC)) {
2171 // Okay, we have an Objective-C pointer conversion.
2172 HasObjCConversion = true;
2173 } else {
2174 // Argument types are too different. Abort.
2175 return false;
2176 }
2177 }
2178
2179 if (HasObjCConversion) {
2180 // We had an Objective-C conversion. Allow this pointer
2181 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002182 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002183 IncompatibleObjC = true;
2184 return true;
2185 }
2186 }
2187
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002188 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002189}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002190
John McCallf85e1932011-06-15 23:02:42 +00002191/// \brief Determine whether this is an Objective-C writeback conversion,
2192/// used for parameter passing when performing automatic reference counting.
2193///
2194/// \param FromType The type we're converting form.
2195///
2196/// \param ToType The type we're converting to.
2197///
2198/// \param ConvertedType The type that will be produced after applying
2199/// this conversion.
2200bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2201 QualType &ConvertedType) {
2202 if (!getLangOptions().ObjCAutoRefCount ||
2203 Context.hasSameUnqualifiedType(FromType, ToType))
2204 return false;
2205
2206 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2207 QualType ToPointee;
2208 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2209 ToPointee = ToPointer->getPointeeType();
2210 else
2211 return false;
2212
2213 Qualifiers ToQuals = ToPointee.getQualifiers();
2214 if (!ToPointee->isObjCLifetimeType() ||
2215 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002216 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002217 return false;
2218
2219 // Argument must be a pointer to __strong to __weak.
2220 QualType FromPointee;
2221 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2222 FromPointee = FromPointer->getPointeeType();
2223 else
2224 return false;
2225
2226 Qualifiers FromQuals = FromPointee.getQualifiers();
2227 if (!FromPointee->isObjCLifetimeType() ||
2228 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2229 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2230 return false;
2231
2232 // Make sure that we have compatible qualifiers.
2233 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2234 if (!ToQuals.compatiblyIncludes(FromQuals))
2235 return false;
2236
2237 // Remove qualifiers from the pointee type we're converting from; they
2238 // aren't used in the compatibility check belong, and we'll be adding back
2239 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2240 FromPointee = FromPointee.getUnqualifiedType();
2241
2242 // The unqualified form of the pointee types must be compatible.
2243 ToPointee = ToPointee.getUnqualifiedType();
2244 bool IncompatibleObjC;
2245 if (Context.typesAreCompatible(FromPointee, ToPointee))
2246 FromPointee = ToPointee;
2247 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2248 IncompatibleObjC))
2249 return false;
2250
2251 /// \brief Construct the type we're converting to, which is a pointer to
2252 /// __autoreleasing pointee.
2253 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2254 ConvertedType = Context.getPointerType(FromPointee);
2255 return true;
2256}
2257
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002258bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2259 QualType& ConvertedType) {
2260 QualType ToPointeeType;
2261 if (const BlockPointerType *ToBlockPtr =
2262 ToType->getAs<BlockPointerType>())
2263 ToPointeeType = ToBlockPtr->getPointeeType();
2264 else
2265 return false;
2266
2267 QualType FromPointeeType;
2268 if (const BlockPointerType *FromBlockPtr =
2269 FromType->getAs<BlockPointerType>())
2270 FromPointeeType = FromBlockPtr->getPointeeType();
2271 else
2272 return false;
2273 // We have pointer to blocks, check whether the only
2274 // differences in the argument and result types are in Objective-C
2275 // pointer conversions. If so, we permit the conversion.
2276
2277 const FunctionProtoType *FromFunctionType
2278 = FromPointeeType->getAs<FunctionProtoType>();
2279 const FunctionProtoType *ToFunctionType
2280 = ToPointeeType->getAs<FunctionProtoType>();
2281
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002282 if (!FromFunctionType || !ToFunctionType)
2283 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002284
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002285 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002286 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002287
2288 // Perform the quick checks that will tell us whether these
2289 // function types are obviously different.
2290 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2291 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2292 return false;
2293
2294 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2295 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2296 if (FromEInfo != ToEInfo)
2297 return false;
2298
2299 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002300 if (Context.hasSameType(FromFunctionType->getResultType(),
2301 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002302 // Okay, the types match exactly. Nothing to do.
2303 } else {
2304 QualType RHS = FromFunctionType->getResultType();
2305 QualType LHS = ToFunctionType->getResultType();
2306 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2307 !RHS.hasQualifiers() && LHS.hasQualifiers())
2308 LHS = LHS.getUnqualifiedType();
2309
2310 if (Context.hasSameType(RHS,LHS)) {
2311 // OK exact match.
2312 } else if (isObjCPointerConversion(RHS, LHS,
2313 ConvertedType, IncompatibleObjC)) {
2314 if (IncompatibleObjC)
2315 return false;
2316 // Okay, we have an Objective-C pointer conversion.
2317 }
2318 else
2319 return false;
2320 }
2321
2322 // Check argument types.
2323 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2324 ArgIdx != NumArgs; ++ArgIdx) {
2325 IncompatibleObjC = false;
2326 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2327 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2328 if (Context.hasSameType(FromArgType, ToArgType)) {
2329 // Okay, the types match exactly. Nothing to do.
2330 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2331 ConvertedType, IncompatibleObjC)) {
2332 if (IncompatibleObjC)
2333 return false;
2334 // Okay, we have an Objective-C pointer conversion.
2335 } else
2336 // Argument types are too different. Abort.
2337 return false;
2338 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002339 if (LangOpts.ObjCAutoRefCount &&
2340 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2341 ToFunctionType))
2342 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002343
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002344 ConvertedType = ToType;
2345 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002346}
2347
Richard Trieu6efd4c52011-11-23 22:32:32 +00002348enum {
2349 ft_default,
2350 ft_different_class,
2351 ft_parameter_arity,
2352 ft_parameter_mismatch,
2353 ft_return_type,
2354 ft_qualifer_mismatch
2355};
2356
2357/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2358/// function types. Catches different number of parameter, mismatch in
2359/// parameter types, and different return types.
2360void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2361 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002362 // If either type is not valid, include no extra info.
2363 if (FromType.isNull() || ToType.isNull()) {
2364 PDiag << ft_default;
2365 return;
2366 }
2367
Richard Trieu6efd4c52011-11-23 22:32:32 +00002368 // Get the function type from the pointers.
2369 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2370 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2371 *ToMember = ToType->getAs<MemberPointerType>();
2372 if (FromMember->getClass() != ToMember->getClass()) {
2373 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2374 << QualType(FromMember->getClass(), 0);
2375 return;
2376 }
2377 FromType = FromMember->getPointeeType();
2378 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002379 }
2380
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002381 if (FromType->isPointerType())
2382 FromType = FromType->getPointeeType();
2383 if (ToType->isPointerType())
2384 ToType = ToType->getPointeeType();
2385
2386 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002387 FromType = FromType.getNonReferenceType();
2388 ToType = ToType.getNonReferenceType();
2389
Richard Trieu6efd4c52011-11-23 22:32:32 +00002390 // Don't print extra info for non-specialized template functions.
2391 if (FromType->isInstantiationDependentType() &&
2392 !FromType->getAs<TemplateSpecializationType>()) {
2393 PDiag << ft_default;
2394 return;
2395 }
2396
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002397 // No extra info for same types.
2398 if (Context.hasSameType(FromType, ToType)) {
2399 PDiag << ft_default;
2400 return;
2401 }
2402
Richard Trieu6efd4c52011-11-23 22:32:32 +00002403 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2404 *ToFunction = ToType->getAs<FunctionProtoType>();
2405
2406 // Both types need to be function types.
2407 if (!FromFunction || !ToFunction) {
2408 PDiag << ft_default;
2409 return;
2410 }
2411
2412 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2413 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2414 << FromFunction->getNumArgs();
2415 return;
2416 }
2417
2418 // Handle different parameter types.
2419 unsigned ArgPos;
2420 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2421 PDiag << ft_parameter_mismatch << ArgPos + 1
2422 << ToFunction->getArgType(ArgPos)
2423 << FromFunction->getArgType(ArgPos);
2424 return;
2425 }
2426
2427 // Handle different return type.
2428 if (!Context.hasSameType(FromFunction->getResultType(),
2429 ToFunction->getResultType())) {
2430 PDiag << ft_return_type << ToFunction->getResultType()
2431 << FromFunction->getResultType();
2432 return;
2433 }
2434
2435 unsigned FromQuals = FromFunction->getTypeQuals(),
2436 ToQuals = ToFunction->getTypeQuals();
2437 if (FromQuals != ToQuals) {
2438 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2439 return;
2440 }
2441
2442 // Unable to find a difference, so add no extra info.
2443 PDiag << ft_default;
2444}
2445
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002446/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002447/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002448/// they have same number of arguments. This routine assumes that Objective-C
2449/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002450/// If the parameters are different, ArgPos will have the the parameter index
2451/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002452bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002453 const FunctionProtoType *NewType,
2454 unsigned *ArgPos) {
2455 if (!getLangOptions().ObjC1) {
2456 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2457 N = NewType->arg_type_begin(),
2458 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2459 if (!Context.hasSameType(*O, *N)) {
2460 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2461 return false;
2462 }
2463 }
2464 return true;
2465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002466
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002467 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2468 N = NewType->arg_type_begin(),
2469 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2470 QualType ToType = (*O);
2471 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002472 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002473 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2474 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002475 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2476 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2477 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2478 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002479 continue;
2480 }
John McCallc12c5bb2010-05-15 11:32:37 +00002481 else if (const ObjCObjectPointerType *PTTo =
2482 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002483 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002484 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002485 if (Context.hasSameUnqualifiedType(
2486 PTTo->getObjectType()->getBaseType(),
2487 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002488 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002489 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002490 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002491 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002492 }
2493 }
2494 return true;
2495}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002496
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002497/// CheckPointerConversion - Check the pointer conversion from the
2498/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002499/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002500/// conversions for which IsPointerConversion has already returned
2501/// true. It returns true and produces a diagnostic if there was an
2502/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002503bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002504 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002505 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002506 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002507 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002508 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002509
John McCalldaa8e4e2010-11-15 09:13:47 +00002510 Kind = CK_BitCast;
2511
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002512 if (!IsCStyleOrFunctionalCast &&
2513 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2514 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2515 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002516 PDiag(diag::warn_impcast_bool_to_null_pointer)
2517 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002518
John McCall1d9b3b22011-09-09 05:25:32 +00002519 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2520 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002521 QualType FromPointeeType = FromPtrType->getPointeeType(),
2522 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002523
Douglas Gregor5fccd362010-03-03 23:55:11 +00002524 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2525 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002526 // We must have a derived-to-base conversion. Check an
2527 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002528 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2529 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002530 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002531 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002532 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002533
Anders Carlsson61faec12009-09-12 04:46:44 +00002534 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002535 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002536 }
2537 }
John McCall1d9b3b22011-09-09 05:25:32 +00002538 } else if (const ObjCObjectPointerType *ToPtrType =
2539 ToType->getAs<ObjCObjectPointerType>()) {
2540 if (const ObjCObjectPointerType *FromPtrType =
2541 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002542 // Objective-C++ conversions are always okay.
2543 // FIXME: We should have a different class of conversions for the
2544 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002545 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002546 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002547 } else if (FromType->isBlockPointerType()) {
2548 Kind = CK_BlockPointerToObjCPointerCast;
2549 } else {
2550 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002551 }
John McCall1d9b3b22011-09-09 05:25:32 +00002552 } else if (ToType->isBlockPointerType()) {
2553 if (!FromType->isBlockPointerType())
2554 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002555 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002556
2557 // We shouldn't fall into this case unless it's valid for other
2558 // reasons.
2559 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2560 Kind = CK_NullToPointer;
2561
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002562 return false;
2563}
2564
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002565/// IsMemberPointerConversion - Determines whether the conversion of the
2566/// expression From, which has the (possibly adjusted) type FromType, can be
2567/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2568/// If so, returns true and places the converted type (that might differ from
2569/// ToType in its cv-qualifiers at some level) into ConvertedType.
2570bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002571 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002572 bool InOverloadResolution,
2573 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002574 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002575 if (!ToTypePtr)
2576 return false;
2577
2578 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002579 if (From->isNullPointerConstant(Context,
2580 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2581 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002582 ConvertedType = ToType;
2583 return true;
2584 }
2585
2586 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002587 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002588 if (!FromTypePtr)
2589 return false;
2590
2591 // A pointer to member of B can be converted to a pointer to member of D,
2592 // where D is derived from B (C++ 4.11p2).
2593 QualType FromClass(FromTypePtr->getClass(), 0);
2594 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002595
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002596 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2597 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2598 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002599 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2600 ToClass.getTypePtr());
2601 return true;
2602 }
2603
2604 return false;
2605}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002606
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002607/// CheckMemberPointerConversion - Check the member pointer conversion from the
2608/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002609/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002610/// for which IsMemberPointerConversion has already returned true. It returns
2611/// true and produces a diagnostic if there was an error, or returns false
2612/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002613bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002614 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002615 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002616 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002617 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002618 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002619 if (!FromPtrType) {
2620 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002621 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002622 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002623 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002624 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002625 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002626 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002627
Ted Kremenek6217b802009-07-29 21:53:49 +00002628 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002629 assert(ToPtrType && "No member pointer cast has a target type "
2630 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002631
Sebastian Redl21593ac2009-01-28 18:33:18 +00002632 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2633 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002634
Sebastian Redl21593ac2009-01-28 18:33:18 +00002635 // FIXME: What about dependent types?
2636 assert(FromClass->isRecordType() && "Pointer into non-class.");
2637 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002638
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002639 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002640 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002641 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2642 assert(DerivationOkay &&
2643 "Should not have been called if derivation isn't OK.");
2644 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002645
Sebastian Redl21593ac2009-01-28 18:33:18 +00002646 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2647 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002648 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2649 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2650 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2651 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002652 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002653
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002654 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002655 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2656 << FromClass << ToClass << QualType(VBase, 0)
2657 << From->getSourceRange();
2658 return true;
2659 }
2660
John McCall6b2accb2010-02-10 09:31:12 +00002661 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002662 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2663 Paths.front(),
2664 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002665
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002666 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002667 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002668 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002669 return false;
2670}
2671
Douglas Gregor98cd5992008-10-21 23:43:52 +00002672/// IsQualificationConversion - Determines whether the conversion from
2673/// an rvalue of type FromType to ToType is a qualification conversion
2674/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002675///
2676/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2677/// when the qualification conversion involves a change in the Objective-C
2678/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002679bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002680Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002681 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002682 FromType = Context.getCanonicalType(FromType);
2683 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002684 ObjCLifetimeConversion = false;
2685
Douglas Gregor98cd5992008-10-21 23:43:52 +00002686 // If FromType and ToType are the same type, this is not a
2687 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002688 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002689 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002690
Douglas Gregor98cd5992008-10-21 23:43:52 +00002691 // (C++ 4.4p4):
2692 // A conversion can add cv-qualifiers at levels other than the first
2693 // in multi-level pointers, subject to the following rules: [...]
2694 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002695 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002696 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002697 // Within each iteration of the loop, we check the qualifiers to
2698 // determine if this still looks like a qualification
2699 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002700 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002701 // until there are no more pointers or pointers-to-members left to
2702 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002703 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002704
Douglas Gregor621c92a2011-04-25 18:40:17 +00002705 Qualifiers FromQuals = FromType.getQualifiers();
2706 Qualifiers ToQuals = ToType.getQualifiers();
2707
John McCallf85e1932011-06-15 23:02:42 +00002708 // Objective-C ARC:
2709 // Check Objective-C lifetime conversions.
2710 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2711 UnwrappedAnyPointer) {
2712 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2713 ObjCLifetimeConversion = true;
2714 FromQuals.removeObjCLifetime();
2715 ToQuals.removeObjCLifetime();
2716 } else {
2717 // Qualification conversions cannot cast between different
2718 // Objective-C lifetime qualifiers.
2719 return false;
2720 }
2721 }
2722
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002723 // Allow addition/removal of GC attributes but not changing GC attributes.
2724 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2725 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2726 FromQuals.removeObjCGCAttr();
2727 ToQuals.removeObjCGCAttr();
2728 }
2729
Douglas Gregor98cd5992008-10-21 23:43:52 +00002730 // -- for every j > 0, if const is in cv 1,j then const is in cv
2731 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002732 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002733 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Douglas Gregor98cd5992008-10-21 23:43:52 +00002735 // -- if the cv 1,j and cv 2,j are different, then const is in
2736 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002737 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002738 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002739 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Douglas Gregor98cd5992008-10-21 23:43:52 +00002741 // Keep track of whether all prior cv-qualifiers in the "to" type
2742 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002743 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002744 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002745 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002746
2747 // We are left with FromType and ToType being the pointee types
2748 // after unwrapping the original FromType and ToType the same number
2749 // of types. If we unwrapped any pointers, and if FromType and
2750 // ToType have the same unqualified type (since we checked
2751 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002752 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002753}
2754
Sebastian Redl56a04282012-02-11 23:51:08 +00002755static OverloadingResult
2756IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2757 CXXRecordDecl *To,
2758 UserDefinedConversionSequence &User,
2759 OverloadCandidateSet &CandidateSet,
2760 bool AllowExplicit) {
2761 DeclContext::lookup_iterator Con, ConEnd;
2762 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2763 Con != ConEnd; ++Con) {
2764 NamedDecl *D = *Con;
2765 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2766
2767 // Find the constructor (which may be a template).
2768 CXXConstructorDecl *Constructor = 0;
2769 FunctionTemplateDecl *ConstructorTmpl
2770 = dyn_cast<FunctionTemplateDecl>(D);
2771 if (ConstructorTmpl)
2772 Constructor
2773 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2774 else
2775 Constructor = cast<CXXConstructorDecl>(D);
2776
2777 bool Usable = !Constructor->isInvalidDecl() &&
2778 S.isInitListConstructor(Constructor) &&
2779 (AllowExplicit || !Constructor->isExplicit());
2780 if (Usable) {
2781 if (ConstructorTmpl)
2782 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2783 /*ExplicitArgs*/ 0,
2784 &From, 1, CandidateSet,
2785 /*SuppressUserConversions=*/true);
2786 else
2787 S.AddOverloadCandidate(Constructor, FoundDecl,
2788 &From, 1, CandidateSet,
2789 /*SuppressUserConversions=*/true);
2790 }
2791 }
2792
2793 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2794
2795 OverloadCandidateSet::iterator Best;
2796 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2797 case OR_Success: {
2798 // Record the standard conversion we used and the conversion function.
2799 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2800 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2801
2802 QualType ThisType = Constructor->getThisType(S.Context);
2803 // Initializer lists don't have conversions as such.
2804 User.Before.setAsIdentityConversion();
2805 User.HadMultipleCandidates = HadMultipleCandidates;
2806 User.ConversionFunction = Constructor;
2807 User.FoundConversionFunction = Best->FoundDecl;
2808 User.After.setAsIdentityConversion();
2809 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2810 User.After.setAllToTypes(ToType);
2811 return OR_Success;
2812 }
2813
2814 case OR_No_Viable_Function:
2815 return OR_No_Viable_Function;
2816 case OR_Deleted:
2817 return OR_Deleted;
2818 case OR_Ambiguous:
2819 return OR_Ambiguous;
2820 }
2821
2822 llvm_unreachable("Invalid OverloadResult!");
2823}
2824
Douglas Gregor734d9862009-01-30 23:27:23 +00002825/// Determines whether there is a user-defined conversion sequence
2826/// (C++ [over.ics.user]) that converts expression From to the type
2827/// ToType. If such a conversion exists, User will contain the
2828/// user-defined conversion sequence that performs such a conversion
2829/// and this routine will return true. Otherwise, this routine returns
2830/// false and User is unspecified.
2831///
Douglas Gregor734d9862009-01-30 23:27:23 +00002832/// \param AllowExplicit true if the conversion should consider C++0x
2833/// "explicit" conversion functions as well as non-explicit conversion
2834/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002835static OverloadingResult
2836IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002837 UserDefinedConversionSequence &User,
2838 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002839 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002840 // Whether we will only visit constructors.
2841 bool ConstructorsOnly = false;
2842
2843 // If the type we are conversion to is a class type, enumerate its
2844 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002845 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002846 // C++ [over.match.ctor]p1:
2847 // When objects of class type are direct-initialized (8.5), or
2848 // copy-initialized from an expression of the same or a
2849 // derived class type (8.5), overload resolution selects the
2850 // constructor. [...] For copy-initialization, the candidate
2851 // functions are all the converting constructors (12.3.1) of
2852 // that class. The argument list is the expression-list within
2853 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002854 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002855 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002856 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002857 ConstructorsOnly = true;
2858
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002859 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2860 // RequireCompleteType may have returned true due to some invalid decl
2861 // during template instantiation, but ToType may be complete enough now
2862 // to try to recover.
2863 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002864 // We're not going to find any constructors.
2865 } else if (CXXRecordDecl *ToRecordDecl
2866 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002867
2868 Expr **Args = &From;
2869 unsigned NumArgs = 1;
2870 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002871 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002872 // But first, see if there is an init-list-contructor that will work.
2873 OverloadingResult Result = IsInitializerListConstructorConversion(
2874 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2875 if (Result != OR_No_Viable_Function)
2876 return Result;
2877 // Never mind.
2878 CandidateSet.clear();
2879
2880 // If we're list-initializing, we pass the individual elements as
2881 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002882 Args = InitList->getInits();
2883 NumArgs = InitList->getNumInits();
2884 ListInitializing = true;
2885 }
2886
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002887 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002888 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002889 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002890 NamedDecl *D = *Con;
2891 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2892
Douglas Gregordec06662009-08-21 18:42:58 +00002893 // Find the constructor (which may be a template).
2894 CXXConstructorDecl *Constructor = 0;
2895 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002896 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002897 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002898 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002899 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2900 else
John McCall9aa472c2010-03-19 07:35:19 +00002901 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002903 bool Usable = !Constructor->isInvalidDecl();
2904 if (ListInitializing)
2905 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2906 else
2907 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2908 if (Usable) {
Douglas Gregordec06662009-08-21 18:42:58 +00002909 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002910 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2911 /*ExplicitArgs*/ 0,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002912 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002913 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002914 !ConstructorsOnly &&
2915 !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002916 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002917 // Allow one user-defined conversion when user specifies a
2918 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002919 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002920 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002921 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002922 !ConstructorsOnly && !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002923 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002924 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002925 }
2926 }
2927
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002928 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002929 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall120d63c2010-08-24 20:38:10 +00002930 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2931 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002932 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002933 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002934 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002935 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002936 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2937 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002938 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002939 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002940 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002941 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002942 DeclAccessPair FoundDecl = I.getPair();
2943 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002944 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2945 if (isa<UsingShadowDecl>(D))
2946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2947
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002948 CXXConversionDecl *Conv;
2949 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002950 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2951 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002952 else
John McCall32daa422010-03-31 01:36:47 +00002953 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002954
2955 if (AllowExplicit || !Conv->isExplicit()) {
2956 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002957 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2958 ActingContext, From, ToType,
2959 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002960 else
John McCall120d63c2010-08-24 20:38:10 +00002961 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2962 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002963 }
2964 }
2965 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002966 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002967
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2969
Douglas Gregor60d62c22008-10-31 16:23:19 +00002970 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002971 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002972 case OR_Success:
2973 // Record the standard conversion we used and the conversion function.
2974 if (CXXConstructorDecl *Constructor
2975 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002976 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00002977
John McCall120d63c2010-08-24 20:38:10 +00002978 // C++ [over.ics.user]p1:
2979 // If the user-defined conversion is specified by a
2980 // constructor (12.3.1), the initial standard conversion
2981 // sequence converts the source type to the type required by
2982 // the argument of the constructor.
2983 //
2984 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002985 if (isa<InitListExpr>(From)) {
2986 // Initializer lists don't have conversions as such.
2987 User.Before.setAsIdentityConversion();
2988 } else {
2989 if (Best->Conversions[0].isEllipsis())
2990 User.EllipsisConversion = true;
2991 else {
2992 User.Before = Best->Conversions[0].Standard;
2993 User.EllipsisConversion = false;
2994 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002995 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002996 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002997 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00002998 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002999 User.After.setAsIdentityConversion();
3000 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3001 User.After.setAllToTypes(ToType);
3002 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003003 }
3004 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003005 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003006 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003007
John McCall120d63c2010-08-24 20:38:10 +00003008 // C++ [over.ics.user]p1:
3009 //
3010 // [...] If the user-defined conversion is specified by a
3011 // conversion function (12.3.2), the initial standard
3012 // conversion sequence converts the source type to the
3013 // implicit object parameter of the conversion function.
3014 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003015 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003016 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003017 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003018 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003019
John McCall120d63c2010-08-24 20:38:10 +00003020 // C++ [over.ics.user]p2:
3021 // The second standard conversion sequence converts the
3022 // result of the user-defined conversion to the target type
3023 // for the sequence. Since an implicit conversion sequence
3024 // is an initialization, the special rules for
3025 // initialization by user-defined conversion apply when
3026 // selecting the best user-defined conversion for a
3027 // user-defined conversion sequence (see 13.3.3 and
3028 // 13.3.3.1).
3029 User.After = Best->FinalConversion;
3030 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003031 }
David Blaikie7530c032012-01-17 06:56:22 +00003032 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003033
John McCall120d63c2010-08-24 20:38:10 +00003034 case OR_No_Viable_Function:
3035 return OR_No_Viable_Function;
3036 case OR_Deleted:
3037 // No conversion here! We're done.
3038 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
John McCall120d63c2010-08-24 20:38:10 +00003040 case OR_Ambiguous:
3041 return OR_Ambiguous;
3042 }
3043
David Blaikie7530c032012-01-17 06:56:22 +00003044 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003045}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003047bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003048Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003049 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003050 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003051 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003052 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003053 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003054 if (OvResult == OR_Ambiguous)
3055 Diag(From->getSourceRange().getBegin(),
3056 diag::err_typecheck_ambiguous_condition)
3057 << From->getType() << ToType << From->getSourceRange();
3058 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3059 Diag(From->getSourceRange().getBegin(),
3060 diag::err_typecheck_nonviable_condition)
3061 << From->getType() << ToType << From->getSourceRange();
3062 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003063 return false;
John McCall120d63c2010-08-24 20:38:10 +00003064 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003065 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003066}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003067
Douglas Gregorb734e242012-02-22 17:32:19 +00003068/// \brief Compare the user-defined conversion functions or constructors
3069/// of two user-defined conversion sequences to determine whether any ordering
3070/// is possible.
3071static ImplicitConversionSequence::CompareKind
3072compareConversionFunctions(Sema &S,
3073 FunctionDecl *Function1,
3074 FunctionDecl *Function2) {
3075 if (!S.getLangOptions().ObjC1 || !S.getLangOptions().CPlusPlus0x)
3076 return ImplicitConversionSequence::Indistinguishable;
3077
3078 // Objective-C++:
3079 // If both conversion functions are implicitly-declared conversions from
3080 // a lambda closure type to a function pointer and a block pointer,
3081 // respectively, always prefer the conversion to a function pointer,
3082 // because the function pointer is more lightweight and is more likely
3083 // to keep code working.
3084 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3085 if (!Conv1)
3086 return ImplicitConversionSequence::Indistinguishable;
3087
3088 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3089 if (!Conv2)
3090 return ImplicitConversionSequence::Indistinguishable;
3091
3092 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3093 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3094 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3095 if (Block1 != Block2)
3096 return Block1? ImplicitConversionSequence::Worse
3097 : ImplicitConversionSequence::Better;
3098 }
3099
3100 return ImplicitConversionSequence::Indistinguishable;
3101}
3102
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003103/// CompareImplicitConversionSequences - Compare two implicit
3104/// conversion sequences to determine whether one is better than the
3105/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003106static ImplicitConversionSequence::CompareKind
3107CompareImplicitConversionSequences(Sema &S,
3108 const ImplicitConversionSequence& ICS1,
3109 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003110{
3111 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3112 // conversion sequences (as defined in 13.3.3.1)
3113 // -- a standard conversion sequence (13.3.3.1.1) is a better
3114 // conversion sequence than a user-defined conversion sequence or
3115 // an ellipsis conversion sequence, and
3116 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3117 // conversion sequence than an ellipsis conversion sequence
3118 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003119 //
John McCall1d318332010-01-12 00:44:57 +00003120 // C++0x [over.best.ics]p10:
3121 // For the purpose of ranking implicit conversion sequences as
3122 // described in 13.3.3.2, the ambiguous conversion sequence is
3123 // treated as a user-defined sequence that is indistinguishable
3124 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003125 if (ICS1.getKindRank() < ICS2.getKindRank())
3126 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003127 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003128 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003129
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003130 // The following checks require both conversion sequences to be of
3131 // the same kind.
3132 if (ICS1.getKind() != ICS2.getKind())
3133 return ImplicitConversionSequence::Indistinguishable;
3134
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003135 ImplicitConversionSequence::CompareKind Result =
3136 ImplicitConversionSequence::Indistinguishable;
3137
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003138 // Two implicit conversion sequences of the same form are
3139 // indistinguishable conversion sequences unless one of the
3140 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003141 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003142 Result = CompareStandardConversionSequences(S,
3143 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003144 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003145 // User-defined conversion sequence U1 is a better conversion
3146 // sequence than another user-defined conversion sequence U2 if
3147 // they contain the same user-defined conversion function or
3148 // constructor and if the second standard conversion sequence of
3149 // U1 is better than the second standard conversion sequence of
3150 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003151 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003152 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003153 Result = CompareStandardConversionSequences(S,
3154 ICS1.UserDefined.After,
3155 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003156 else
3157 Result = compareConversionFunctions(S,
3158 ICS1.UserDefined.ConversionFunction,
3159 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003160 }
3161
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003162 // List-initialization sequence L1 is a better conversion sequence than
3163 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3164 // for some X and L2 does not.
3165 if (Result == ImplicitConversionSequence::Indistinguishable &&
3166 ICS1.isListInitializationSequence() &&
3167 ICS2.isListInitializationSequence()) {
3168 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
3169 }
3170
3171 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003172}
3173
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003174static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3175 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3176 Qualifiers Quals;
3177 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003178 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003181 return Context.hasSameUnqualifiedType(T1, T2);
3182}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183
Douglas Gregorad323a82010-01-27 03:51:04 +00003184// Per 13.3.3.2p3, compare the given standard conversion sequences to
3185// determine if one is a proper subset of the other.
3186static ImplicitConversionSequence::CompareKind
3187compareStandardConversionSubsets(ASTContext &Context,
3188 const StandardConversionSequence& SCS1,
3189 const StandardConversionSequence& SCS2) {
3190 ImplicitConversionSequence::CompareKind Result
3191 = ImplicitConversionSequence::Indistinguishable;
3192
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003194 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003195 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3196 return ImplicitConversionSequence::Better;
3197 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3198 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199
Douglas Gregorad323a82010-01-27 03:51:04 +00003200 if (SCS1.Second != SCS2.Second) {
3201 if (SCS1.Second == ICK_Identity)
3202 Result = ImplicitConversionSequence::Better;
3203 else if (SCS2.Second == ICK_Identity)
3204 Result = ImplicitConversionSequence::Worse;
3205 else
3206 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003207 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003208 return ImplicitConversionSequence::Indistinguishable;
3209
3210 if (SCS1.Third == SCS2.Third) {
3211 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3212 : ImplicitConversionSequence::Indistinguishable;
3213 }
3214
3215 if (SCS1.Third == ICK_Identity)
3216 return Result == ImplicitConversionSequence::Worse
3217 ? ImplicitConversionSequence::Indistinguishable
3218 : ImplicitConversionSequence::Better;
3219
3220 if (SCS2.Third == ICK_Identity)
3221 return Result == ImplicitConversionSequence::Better
3222 ? ImplicitConversionSequence::Indistinguishable
3223 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003224
Douglas Gregorad323a82010-01-27 03:51:04 +00003225 return ImplicitConversionSequence::Indistinguishable;
3226}
3227
Douglas Gregor440a4832011-01-26 14:52:12 +00003228/// \brief Determine whether one of the given reference bindings is better
3229/// than the other based on what kind of bindings they are.
3230static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3231 const StandardConversionSequence &SCS2) {
3232 // C++0x [over.ics.rank]p3b4:
3233 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3234 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003236 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003237 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003238 // reference*.
3239 //
3240 // FIXME: Rvalue references. We're going rogue with the above edits,
3241 // because the semantics in the current C++0x working paper (N3225 at the
3242 // time of this writing) break the standard definition of std::forward
3243 // and std::reference_wrapper when dealing with references to functions.
3244 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003245 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3246 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3247 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003248
Douglas Gregor440a4832011-01-26 14:52:12 +00003249 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3250 SCS2.IsLvalueReference) ||
3251 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3252 !SCS2.IsLvalueReference);
3253}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003254
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003255/// CompareStandardConversionSequences - Compare two standard
3256/// conversion sequences to determine whether one is better than the
3257/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003258static ImplicitConversionSequence::CompareKind
3259CompareStandardConversionSequences(Sema &S,
3260 const StandardConversionSequence& SCS1,
3261 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003262{
3263 // Standard conversion sequence S1 is a better conversion sequence
3264 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3265
3266 // -- S1 is a proper subsequence of S2 (comparing the conversion
3267 // sequences in the canonical form defined by 13.3.3.1.1,
3268 // excluding any Lvalue Transformation; the identity conversion
3269 // sequence is considered to be a subsequence of any
3270 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003271 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003272 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003273 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003274
3275 // -- the rank of S1 is better than the rank of S2 (by the rules
3276 // defined below), or, if not that,
3277 ImplicitConversionRank Rank1 = SCS1.getRank();
3278 ImplicitConversionRank Rank2 = SCS2.getRank();
3279 if (Rank1 < Rank2)
3280 return ImplicitConversionSequence::Better;
3281 else if (Rank2 < Rank1)
3282 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003283
Douglas Gregor57373262008-10-22 14:17:15 +00003284 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3285 // are indistinguishable unless one of the following rules
3286 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Douglas Gregor57373262008-10-22 14:17:15 +00003288 // A conversion that is not a conversion of a pointer, or
3289 // pointer to member, to bool is better than another conversion
3290 // that is such a conversion.
3291 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3292 return SCS2.isPointerConversionToBool()
3293 ? ImplicitConversionSequence::Better
3294 : ImplicitConversionSequence::Worse;
3295
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003296 // C++ [over.ics.rank]p4b2:
3297 //
3298 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003299 // conversion of B* to A* is better than conversion of B* to
3300 // void*, and conversion of A* to void* is better than conversion
3301 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003302 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003303 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003304 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003305 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003306 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3307 // Exactly one of the conversion sequences is a conversion to
3308 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003309 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3310 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003311 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3312 // Neither conversion sequence converts to a void pointer; compare
3313 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003314 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003315 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003316 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003317 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3318 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003319 // Both conversion sequences are conversions to void
3320 // pointers. Compare the source types to determine if there's an
3321 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003322 QualType FromType1 = SCS1.getFromType();
3323 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003324
3325 // Adjust the types we're converting from via the array-to-pointer
3326 // conversion, if we need to.
3327 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003328 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003329 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003330 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003331
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003332 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3333 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003334
John McCall120d63c2010-08-24 20:38:10 +00003335 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003336 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003337 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003338 return ImplicitConversionSequence::Worse;
3339
3340 // Objective-C++: If one interface is more specific than the
3341 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003342 const ObjCObjectPointerType* FromObjCPtr1
3343 = FromType1->getAs<ObjCObjectPointerType>();
3344 const ObjCObjectPointerType* FromObjCPtr2
3345 = FromType2->getAs<ObjCObjectPointerType>();
3346 if (FromObjCPtr1 && FromObjCPtr2) {
3347 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3348 FromObjCPtr2);
3349 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3350 FromObjCPtr1);
3351 if (AssignLeft != AssignRight) {
3352 return AssignLeft? ImplicitConversionSequence::Better
3353 : ImplicitConversionSequence::Worse;
3354 }
Douglas Gregor01919692009-12-13 21:37:05 +00003355 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003356 }
Douglas Gregor57373262008-10-22 14:17:15 +00003357
3358 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3359 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003360 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003361 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003362 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003363
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003364 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003365 // Check for a better reference binding based on the kind of bindings.
3366 if (isBetterReferenceBindingKind(SCS1, SCS2))
3367 return ImplicitConversionSequence::Better;
3368 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3369 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003370
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003371 // C++ [over.ics.rank]p3b4:
3372 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3373 // which the references refer are the same type except for
3374 // top-level cv-qualifiers, and the type to which the reference
3375 // initialized by S2 refers is more cv-qualified than the type
3376 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003377 QualType T1 = SCS1.getToType(2);
3378 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003379 T1 = S.Context.getCanonicalType(T1);
3380 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003381 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003382 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3383 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003384 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003385 // Objective-C++ ARC: If the references refer to objects with different
3386 // lifetimes, prefer bindings that don't change lifetime.
3387 if (SCS1.ObjCLifetimeConversionBinding !=
3388 SCS2.ObjCLifetimeConversionBinding) {
3389 return SCS1.ObjCLifetimeConversionBinding
3390 ? ImplicitConversionSequence::Worse
3391 : ImplicitConversionSequence::Better;
3392 }
3393
Chandler Carruth6df868e2010-12-12 08:17:55 +00003394 // If the type is an array type, promote the element qualifiers to the
3395 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003396 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003397 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003398 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003399 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003400 if (T2.isMoreQualifiedThan(T1))
3401 return ImplicitConversionSequence::Better;
3402 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003403 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003404 }
3405 }
Douglas Gregor57373262008-10-22 14:17:15 +00003406
Francois Pichet1c98d622011-09-18 21:37:37 +00003407 // In Microsoft mode, prefer an integral conversion to a
3408 // floating-to-integral conversion if the integral conversion
3409 // is between types of the same size.
3410 // For example:
3411 // void f(float);
3412 // void f(int);
3413 // int main {
3414 // long a;
3415 // f(a);
3416 // }
3417 // Here, MSVC will call f(int) instead of generating a compile error
3418 // as clang will do in standard mode.
3419 if (S.getLangOptions().MicrosoftMode &&
3420 SCS1.Second == ICK_Integral_Conversion &&
3421 SCS2.Second == ICK_Floating_Integral &&
3422 S.Context.getTypeSize(SCS1.getFromType()) ==
3423 S.Context.getTypeSize(SCS1.getToType(2)))
3424 return ImplicitConversionSequence::Better;
3425
Douglas Gregor57373262008-10-22 14:17:15 +00003426 return ImplicitConversionSequence::Indistinguishable;
3427}
3428
3429/// CompareQualificationConversions - Compares two standard conversion
3430/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003431/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3432ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003433CompareQualificationConversions(Sema &S,
3434 const StandardConversionSequence& SCS1,
3435 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003436 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003437 // -- S1 and S2 differ only in their qualification conversion and
3438 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3439 // cv-qualification signature of type T1 is a proper subset of
3440 // the cv-qualification signature of type T2, and S1 is not the
3441 // deprecated string literal array-to-pointer conversion (4.2).
3442 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3443 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3444 return ImplicitConversionSequence::Indistinguishable;
3445
3446 // FIXME: the example in the standard doesn't use a qualification
3447 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003448 QualType T1 = SCS1.getToType(2);
3449 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003450 T1 = S.Context.getCanonicalType(T1);
3451 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003452 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003453 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3454 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003455
3456 // If the types are the same, we won't learn anything by unwrapped
3457 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003458 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003459 return ImplicitConversionSequence::Indistinguishable;
3460
Chandler Carruth28e318c2009-12-29 07:16:59 +00003461 // If the type is an array type, promote the element qualifiers to the type
3462 // for comparison.
3463 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003464 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003465 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003466 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003467
Mike Stump1eb44332009-09-09 15:08:12 +00003468 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003469 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003470
3471 // Objective-C++ ARC:
3472 // Prefer qualification conversions not involving a change in lifetime
3473 // to qualification conversions that do not change lifetime.
3474 if (SCS1.QualificationIncludesObjCLifetime !=
3475 SCS2.QualificationIncludesObjCLifetime) {
3476 Result = SCS1.QualificationIncludesObjCLifetime
3477 ? ImplicitConversionSequence::Worse
3478 : ImplicitConversionSequence::Better;
3479 }
3480
John McCall120d63c2010-08-24 20:38:10 +00003481 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003482 // Within each iteration of the loop, we check the qualifiers to
3483 // determine if this still looks like a qualification
3484 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003485 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003486 // until there are no more pointers or pointers-to-members left
3487 // to unwrap. This essentially mimics what
3488 // IsQualificationConversion does, but here we're checking for a
3489 // strict subset of qualifiers.
3490 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3491 // The qualifiers are the same, so this doesn't tell us anything
3492 // about how the sequences rank.
3493 ;
3494 else if (T2.isMoreQualifiedThan(T1)) {
3495 // T1 has fewer qualifiers, so it could be the better sequence.
3496 if (Result == ImplicitConversionSequence::Worse)
3497 // Neither has qualifiers that are a subset of the other's
3498 // qualifiers.
3499 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003500
Douglas Gregor57373262008-10-22 14:17:15 +00003501 Result = ImplicitConversionSequence::Better;
3502 } else if (T1.isMoreQualifiedThan(T2)) {
3503 // T2 has fewer qualifiers, so it could be the better sequence.
3504 if (Result == ImplicitConversionSequence::Better)
3505 // Neither has qualifiers that are a subset of the other's
3506 // qualifiers.
3507 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Douglas Gregor57373262008-10-22 14:17:15 +00003509 Result = ImplicitConversionSequence::Worse;
3510 } else {
3511 // Qualifiers are disjoint.
3512 return ImplicitConversionSequence::Indistinguishable;
3513 }
3514
3515 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003516 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003517 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003518 }
3519
Douglas Gregor57373262008-10-22 14:17:15 +00003520 // Check that the winning standard conversion sequence isn't using
3521 // the deprecated string literal array to pointer conversion.
3522 switch (Result) {
3523 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003524 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003525 Result = ImplicitConversionSequence::Indistinguishable;
3526 break;
3527
3528 case ImplicitConversionSequence::Indistinguishable:
3529 break;
3530
3531 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003532 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003533 Result = ImplicitConversionSequence::Indistinguishable;
3534 break;
3535 }
3536
3537 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003538}
3539
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003540/// CompareDerivedToBaseConversions - Compares two standard conversion
3541/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003542/// various kinds of derived-to-base conversions (C++
3543/// [over.ics.rank]p4b3). As part of these checks, we also look at
3544/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003545ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003546CompareDerivedToBaseConversions(Sema &S,
3547 const StandardConversionSequence& SCS1,
3548 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003549 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003550 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003551 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003552 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003553
3554 // Adjust the types we're converting from via the array-to-pointer
3555 // conversion, if we need to.
3556 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003557 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003558 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003559 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003560
3561 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003562 FromType1 = S.Context.getCanonicalType(FromType1);
3563 ToType1 = S.Context.getCanonicalType(ToType1);
3564 FromType2 = S.Context.getCanonicalType(FromType2);
3565 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003566
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003567 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003568 //
3569 // If class B is derived directly or indirectly from class A and
3570 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003571 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003572 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003573 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003574 SCS2.Second == ICK_Pointer_Conversion &&
3575 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3576 FromType1->isPointerType() && FromType2->isPointerType() &&
3577 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003578 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003579 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003580 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003581 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003582 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003583 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003584 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003585 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003586
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003587 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003588 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003589 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003590 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003591 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003592 return ImplicitConversionSequence::Worse;
3593 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003594
3595 // -- conversion of B* to A* is better than conversion of C* to A*,
3596 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003597 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003598 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003599 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003600 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003601 }
3602 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3603 SCS2.Second == ICK_Pointer_Conversion) {
3604 const ObjCObjectPointerType *FromPtr1
3605 = FromType1->getAs<ObjCObjectPointerType>();
3606 const ObjCObjectPointerType *FromPtr2
3607 = FromType2->getAs<ObjCObjectPointerType>();
3608 const ObjCObjectPointerType *ToPtr1
3609 = ToType1->getAs<ObjCObjectPointerType>();
3610 const ObjCObjectPointerType *ToPtr2
3611 = ToType2->getAs<ObjCObjectPointerType>();
3612
3613 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3614 // Apply the same conversion ranking rules for Objective-C pointer types
3615 // that we do for C++ pointers to class types. However, we employ the
3616 // Objective-C pseudo-subtyping relationship used for assignment of
3617 // Objective-C pointer types.
3618 bool FromAssignLeft
3619 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3620 bool FromAssignRight
3621 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3622 bool ToAssignLeft
3623 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3624 bool ToAssignRight
3625 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3626
3627 // A conversion to an a non-id object pointer type or qualified 'id'
3628 // type is better than a conversion to 'id'.
3629 if (ToPtr1->isObjCIdType() &&
3630 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3631 return ImplicitConversionSequence::Worse;
3632 if (ToPtr2->isObjCIdType() &&
3633 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3634 return ImplicitConversionSequence::Better;
3635
3636 // A conversion to a non-id object pointer type is better than a
3637 // conversion to a qualified 'id' type
3638 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3639 return ImplicitConversionSequence::Worse;
3640 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3641 return ImplicitConversionSequence::Better;
3642
3643 // A conversion to an a non-Class object pointer type or qualified 'Class'
3644 // type is better than a conversion to 'Class'.
3645 if (ToPtr1->isObjCClassType() &&
3646 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3647 return ImplicitConversionSequence::Worse;
3648 if (ToPtr2->isObjCClassType() &&
3649 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3650 return ImplicitConversionSequence::Better;
3651
3652 // A conversion to a non-Class object pointer type is better than a
3653 // conversion to a qualified 'Class' type.
3654 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3655 return ImplicitConversionSequence::Worse;
3656 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3657 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Douglas Gregor395cc372011-01-31 18:51:41 +00003659 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3660 if (S.Context.hasSameType(FromType1, FromType2) &&
3661 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3662 (ToAssignLeft != ToAssignRight))
3663 return ToAssignLeft? ImplicitConversionSequence::Worse
3664 : ImplicitConversionSequence::Better;
3665
3666 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3667 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3668 (FromAssignLeft != FromAssignRight))
3669 return FromAssignLeft? ImplicitConversionSequence::Better
3670 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003671 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003672 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003673
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003674 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003675 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3676 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3677 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003678 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003679 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003680 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003681 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003682 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003683 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003685 ToType2->getAs<MemberPointerType>();
3686 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3687 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3688 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3689 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3690 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3691 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3692 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3693 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003694 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003695 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003696 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003697 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003698 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003699 return ImplicitConversionSequence::Better;
3700 }
3701 // conversion of B::* to C::* is better than conversion of A::* to C::*
3702 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003703 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003704 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003705 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003706 return ImplicitConversionSequence::Worse;
3707 }
3708 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003710 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003711 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003712 // -- binding of an expression of type C to a reference of type
3713 // B& is better than binding an expression of type C to a
3714 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003715 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3716 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3717 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003718 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003719 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003720 return ImplicitConversionSequence::Worse;
3721 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003722
Douglas Gregor225c41e2008-11-03 19:09:14 +00003723 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003724 // -- binding of an expression of type B to a reference of type
3725 // A& is better than binding an expression of type C to a
3726 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003727 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3728 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3729 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003730 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003731 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003732 return ImplicitConversionSequence::Worse;
3733 }
3734 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003735
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003736 return ImplicitConversionSequence::Indistinguishable;
3737}
3738
Douglas Gregorabe183d2010-04-13 16:31:36 +00003739/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3740/// determine whether they are reference-related,
3741/// reference-compatible, reference-compatible with added
3742/// qualification, or incompatible, for use in C++ initialization by
3743/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3744/// type, and the first type (T1) is the pointee type of the reference
3745/// type being initialized.
3746Sema::ReferenceCompareResult
3747Sema::CompareReferenceRelationship(SourceLocation Loc,
3748 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003749 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003750 bool &ObjCConversion,
3751 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003752 assert(!OrigT1->isReferenceType() &&
3753 "T1 must be the pointee type of the reference type");
3754 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3755
3756 QualType T1 = Context.getCanonicalType(OrigT1);
3757 QualType T2 = Context.getCanonicalType(OrigT2);
3758 Qualifiers T1Quals, T2Quals;
3759 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3760 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3761
3762 // C++ [dcl.init.ref]p4:
3763 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3764 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3765 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003766 DerivedToBase = false;
3767 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003768 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003769 if (UnqualT1 == UnqualT2) {
3770 // Nothing to do.
3771 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003772 IsDerivedFrom(UnqualT2, UnqualT1))
3773 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003774 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3775 UnqualT2->isObjCObjectOrInterfaceType() &&
3776 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3777 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003778 else
3779 return Ref_Incompatible;
3780
3781 // At this point, we know that T1 and T2 are reference-related (at
3782 // least).
3783
3784 // If the type is an array type, promote the element qualifiers to the type
3785 // for comparison.
3786 if (isa<ArrayType>(T1) && T1Quals)
3787 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3788 if (isa<ArrayType>(T2) && T2Quals)
3789 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3790
3791 // C++ [dcl.init.ref]p4:
3792 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3793 // reference-related to T2 and cv1 is the same cv-qualification
3794 // as, or greater cv-qualification than, cv2. For purposes of
3795 // overload resolution, cases for which cv1 is greater
3796 // cv-qualification than cv2 are identified as
3797 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003798 //
3799 // Note that we also require equivalence of Objective-C GC and address-space
3800 // qualifiers when performing these computations, so that e.g., an int in
3801 // address space 1 is not reference-compatible with an int in address
3802 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003803 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3804 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3805 T1Quals.removeObjCLifetime();
3806 T2Quals.removeObjCLifetime();
3807 ObjCLifetimeConversion = true;
3808 }
3809
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003810 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003811 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003812 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003813 return Ref_Compatible_With_Added_Qualification;
3814 else
3815 return Ref_Related;
3816}
3817
Douglas Gregor604eb652010-08-11 02:15:33 +00003818/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003819/// with DeclType. Return true if something definite is found.
3820static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003821FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3822 QualType DeclType, SourceLocation DeclLoc,
3823 Expr *Init, QualType T2, bool AllowRvalues,
3824 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003825 assert(T2->isRecordType() && "Can only find conversions of record types.");
3826 CXXRecordDecl *T2RecordDecl
3827 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3828
3829 OverloadCandidateSet CandidateSet(DeclLoc);
3830 const UnresolvedSetImpl *Conversions
3831 = T2RecordDecl->getVisibleConversionFunctions();
3832 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3833 E = Conversions->end(); I != E; ++I) {
3834 NamedDecl *D = *I;
3835 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3836 if (isa<UsingShadowDecl>(D))
3837 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3838
3839 FunctionTemplateDecl *ConvTemplate
3840 = dyn_cast<FunctionTemplateDecl>(D);
3841 CXXConversionDecl *Conv;
3842 if (ConvTemplate)
3843 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3844 else
3845 Conv = cast<CXXConversionDecl>(D);
3846
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003847 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003848 // explicit conversions, skip it.
3849 if (!AllowExplicit && Conv->isExplicit())
3850 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003851
Douglas Gregor604eb652010-08-11 02:15:33 +00003852 if (AllowRvalues) {
3853 bool DerivedToBase = false;
3854 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003855 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003856
3857 // If we are initializing an rvalue reference, don't permit conversion
3858 // functions that return lvalues.
3859 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3860 const ReferenceType *RefType
3861 = Conv->getConversionType()->getAs<LValueReferenceType>();
3862 if (RefType && !RefType->getPointeeType()->isFunctionType())
3863 continue;
3864 }
3865
Douglas Gregor604eb652010-08-11 02:15:33 +00003866 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003867 S.CompareReferenceRelationship(
3868 DeclLoc,
3869 Conv->getConversionType().getNonReferenceType()
3870 .getUnqualifiedType(),
3871 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003872 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003873 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003874 continue;
3875 } else {
3876 // If the conversion function doesn't return a reference type,
3877 // it can't be considered for this conversion. An rvalue reference
3878 // is only acceptable if its referencee is a function type.
3879
3880 const ReferenceType *RefType =
3881 Conv->getConversionType()->getAs<ReferenceType>();
3882 if (!RefType ||
3883 (!RefType->isLValueReferenceType() &&
3884 !RefType->getPointeeType()->isFunctionType()))
3885 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887
Douglas Gregor604eb652010-08-11 02:15:33 +00003888 if (ConvTemplate)
3889 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003890 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003891 else
3892 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003893 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003894 }
3895
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003896 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3897
Sebastian Redl4680bf22010-06-30 18:13:39 +00003898 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003899 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003900 case OR_Success:
3901 // C++ [over.ics.ref]p1:
3902 //
3903 // [...] If the parameter binds directly to the result of
3904 // applying a conversion function to the argument
3905 // expression, the implicit conversion sequence is a
3906 // user-defined conversion sequence (13.3.3.1.2), with the
3907 // second standard conversion sequence either an identity
3908 // conversion or, if the conversion function returns an
3909 // entity of a type that is a derived class of the parameter
3910 // type, a derived-to-base Conversion.
3911 if (!Best->FinalConversion.DirectBinding)
3912 return false;
3913
Chandler Carruth25ca4212011-02-25 19:41:05 +00003914 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003915 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003916 ICS.setUserDefined();
3917 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3918 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003919 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003920 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003921 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003922 ICS.UserDefined.EllipsisConversion = false;
3923 assert(ICS.UserDefined.After.ReferenceBinding &&
3924 ICS.UserDefined.After.DirectBinding &&
3925 "Expected a direct reference binding!");
3926 return true;
3927
3928 case OR_Ambiguous:
3929 ICS.setAmbiguous();
3930 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3931 Cand != CandidateSet.end(); ++Cand)
3932 if (Cand->Viable)
3933 ICS.Ambiguous.addConversion(Cand->Function);
3934 return true;
3935
3936 case OR_No_Viable_Function:
3937 case OR_Deleted:
3938 // There was no suitable conversion, or we found a deleted
3939 // conversion; continue with other checks.
3940 return false;
3941 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003942
David Blaikie7530c032012-01-17 06:56:22 +00003943 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00003944}
3945
Douglas Gregorabe183d2010-04-13 16:31:36 +00003946/// \brief Compute an implicit conversion sequence for reference
3947/// initialization.
3948static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00003949TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003950 SourceLocation DeclLoc,
3951 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003952 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003953 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3954
3955 // Most paths end in a failed conversion.
3956 ImplicitConversionSequence ICS;
3957 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3958
3959 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3960 QualType T2 = Init->getType();
3961
3962 // If the initializer is the address of an overloaded function, try
3963 // to resolve the overloaded function. If all goes well, T2 is the
3964 // type of the resulting function.
3965 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3966 DeclAccessPair Found;
3967 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3968 false, Found))
3969 T2 = Fn->getType();
3970 }
3971
3972 // Compute some basic properties of the types and the initializer.
3973 bool isRValRef = DeclType->isRValueReferenceType();
3974 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003975 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003976 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003977 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003978 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003979 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003980 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003981
Douglas Gregorabe183d2010-04-13 16:31:36 +00003982
Sebastian Redl4680bf22010-06-30 18:13:39 +00003983 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003984 // A reference to type "cv1 T1" is initialized by an expression
3985 // of type "cv2 T2" as follows:
3986
Sebastian Redl4680bf22010-06-30 18:13:39 +00003987 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003988 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003989 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3990 // reference-compatible with "cv2 T2," or
3991 //
3992 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3993 if (InitCategory.isLValue() &&
3994 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003995 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003996 // When a parameter of reference type binds directly (8.5.3)
3997 // to an argument expression, the implicit conversion sequence
3998 // is the identity conversion, unless the argument expression
3999 // has a type that is a derived class of the parameter type,
4000 // in which case the implicit conversion sequence is a
4001 // derived-to-base Conversion (13.3.3.1).
4002 ICS.setStandard();
4003 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004004 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4005 : ObjCConversion? ICK_Compatible_Conversion
4006 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004007 ICS.Standard.Third = ICK_Identity;
4008 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4009 ICS.Standard.setToType(0, T2);
4010 ICS.Standard.setToType(1, T1);
4011 ICS.Standard.setToType(2, T1);
4012 ICS.Standard.ReferenceBinding = true;
4013 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004014 ICS.Standard.IsLvalueReference = !isRValRef;
4015 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4016 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004017 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004018 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004019 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004020
Sebastian Redl4680bf22010-06-30 18:13:39 +00004021 // Nothing more to do: the inaccessibility/ambiguity check for
4022 // derived-to-base conversions is suppressed when we're
4023 // computing the implicit conversion sequence (C++
4024 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004025 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004026 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004027
Sebastian Redl4680bf22010-06-30 18:13:39 +00004028 // -- has a class type (i.e., T2 is a class type), where T1 is
4029 // not reference-related to T2, and can be implicitly
4030 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4031 // is reference-compatible with "cv3 T3" 92) (this
4032 // conversion is selected by enumerating the applicable
4033 // conversion functions (13.3.1.6) and choosing the best
4034 // one through overload resolution (13.3)),
4035 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004036 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004037 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004038 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4039 Init, T2, /*AllowRvalues=*/false,
4040 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004041 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004042 }
4043 }
4044
Sebastian Redl4680bf22010-06-30 18:13:39 +00004045 // -- Otherwise, the reference shall be an lvalue reference to a
4046 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004047 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004049 // We actually handle one oddity of C++ [over.ics.ref] at this
4050 // point, which is that, due to p2 (which short-circuits reference
4051 // binding by only attempting a simple conversion for non-direct
4052 // bindings) and p3's strange wording, we allow a const volatile
4053 // reference to bind to an rvalue. Hence the check for the presence
4054 // of "const" rather than checking for "const" being the only
4055 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004056 // This is also the point where rvalue references and lvalue inits no longer
4057 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004058 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00004059 return ICS;
4060
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004061 // -- If the initializer expression
4062 //
4063 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004064 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004065 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4066 (InitCategory.isXValue() ||
4067 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4068 (InitCategory.isLValue() && T2->isFunctionType()))) {
4069 ICS.setStandard();
4070 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004071 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004072 : ObjCConversion? ICK_Compatible_Conversion
4073 : ICK_Identity;
4074 ICS.Standard.Third = ICK_Identity;
4075 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4076 ICS.Standard.setToType(0, T2);
4077 ICS.Standard.setToType(1, T1);
4078 ICS.Standard.setToType(2, T1);
4079 ICS.Standard.ReferenceBinding = true;
4080 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4081 // binding unless we're binding to a class prvalue.
4082 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4083 // allow the use of rvalue references in C++98/03 for the benefit of
4084 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004085 ICS.Standard.DirectBinding =
4086 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004087 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004088 ICS.Standard.IsLvalueReference = !isRValRef;
4089 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004090 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004091 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004092 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004093 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004097 // -- has a class type (i.e., T2 is a class type), where T1 is not
4098 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004099 // an xvalue, class prvalue, or function lvalue of type
4100 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004101 // "cv3 T3",
4102 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004103 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004104 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004105 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004106 // class subobject).
4107 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004108 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004109 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4110 Init, T2, /*AllowRvalues=*/true,
4111 AllowExplicit)) {
4112 // In the second case, if the reference is an rvalue reference
4113 // and the second standard conversion sequence of the
4114 // user-defined conversion sequence includes an lvalue-to-rvalue
4115 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004117 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4118 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4119
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004120 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004122
Douglas Gregorabe183d2010-04-13 16:31:36 +00004123 // -- Otherwise, a temporary of type "cv1 T1" is created and
4124 // initialized from the initializer expression using the
4125 // rules for a non-reference copy initialization (8.5). The
4126 // reference is then bound to the temporary. If T1 is
4127 // reference-related to T2, cv1 must be the same
4128 // cv-qualification as, or greater cv-qualification than,
4129 // cv2; otherwise, the program is ill-formed.
4130 if (RefRelationship == Sema::Ref_Related) {
4131 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4132 // we would be reference-compatible or reference-compatible with
4133 // added qualification. But that wasn't the case, so the reference
4134 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004135 //
4136 // Note that we only want to check address spaces and cvr-qualifiers here.
4137 // ObjC GC and lifetime qualifiers aren't important.
4138 Qualifiers T1Quals = T1.getQualifiers();
4139 Qualifiers T2Quals = T2.getQualifiers();
4140 T1Quals.removeObjCGCAttr();
4141 T1Quals.removeObjCLifetime();
4142 T2Quals.removeObjCGCAttr();
4143 T2Quals.removeObjCLifetime();
4144 if (!T1Quals.compatiblyIncludes(T2Quals))
4145 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004146 }
4147
4148 // If at least one of the types is a class type, the types are not
4149 // related, and we aren't allowed any user conversions, the
4150 // reference binding fails. This case is important for breaking
4151 // recursion, since TryImplicitConversion below will attempt to
4152 // create a temporary through the use of a copy constructor.
4153 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4154 (T1->isRecordType() || T2->isRecordType()))
4155 return ICS;
4156
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004157 // If T1 is reference-related to T2 and the reference is an rvalue
4158 // reference, the initializer expression shall not be an lvalue.
4159 if (RefRelationship >= Sema::Ref_Related &&
4160 isRValRef && Init->Classify(S.Context).isLValue())
4161 return ICS;
4162
Douglas Gregorabe183d2010-04-13 16:31:36 +00004163 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004164 // When a parameter of reference type is not bound directly to
4165 // an argument expression, the conversion sequence is the one
4166 // required to convert the argument expression to the
4167 // underlying type of the reference according to
4168 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4169 // to copy-initializing a temporary of the underlying type with
4170 // the argument expression. Any difference in top-level
4171 // cv-qualification is subsumed by the initialization itself
4172 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004173 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4174 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004175 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004176 /*CStyle=*/false,
4177 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004178
4179 // Of course, that's still a reference binding.
4180 if (ICS.isStandard()) {
4181 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004182 ICS.Standard.IsLvalueReference = !isRValRef;
4183 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4184 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004185 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004186 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004187 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004188 // Don't allow rvalue references to bind to lvalues.
4189 if (DeclType->isRValueReferenceType()) {
4190 if (const ReferenceType *RefType
4191 = ICS.UserDefined.ConversionFunction->getResultType()
4192 ->getAs<LValueReferenceType>()) {
4193 if (!RefType->getPointeeType()->isFunctionType()) {
4194 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4195 DeclType);
4196 return ICS;
4197 }
4198 }
4199 }
4200
Douglas Gregorabe183d2010-04-13 16:31:36 +00004201 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004202 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4203 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4204 ICS.UserDefined.After.BindsToRvalue = true;
4205 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4206 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004207 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004208
Douglas Gregorabe183d2010-04-13 16:31:36 +00004209 return ICS;
4210}
4211
Sebastian Redl5405b812011-10-16 18:19:34 +00004212static ImplicitConversionSequence
4213TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4214 bool SuppressUserConversions,
4215 bool InOverloadResolution,
4216 bool AllowObjCWritebackConversion);
4217
4218/// TryListConversion - Try to copy-initialize a value of type ToType from the
4219/// initializer list From.
4220static ImplicitConversionSequence
4221TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4222 bool SuppressUserConversions,
4223 bool InOverloadResolution,
4224 bool AllowObjCWritebackConversion) {
4225 // C++11 [over.ics.list]p1:
4226 // When an argument is an initializer list, it is not an expression and
4227 // special rules apply for converting it to a parameter type.
4228
4229 ImplicitConversionSequence Result;
4230 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004231 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004232
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004233 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004234 // initialized from init lists.
4235 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4236 return Result;
4237
Sebastian Redl5405b812011-10-16 18:19:34 +00004238 // C++11 [over.ics.list]p2:
4239 // If the parameter type is std::initializer_list<X> or "array of X" and
4240 // all the elements can be implicitly converted to X, the implicit
4241 // conversion sequence is the worst conversion necessary to convert an
4242 // element of the list to X.
Sebastian Redlfe592282012-01-17 22:49:48 +00004243 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004244 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004245 X = S.Context.getBaseElementType(ToType);
4246 else
4247 (void)S.isStdInitializerList(ToType, &X);
4248 if (!X.isNull()) {
4249 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4250 Expr *Init = From->getInit(i);
4251 ImplicitConversionSequence ICS =
4252 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4253 InOverloadResolution,
4254 AllowObjCWritebackConversion);
4255 // If a single element isn't convertible, fail.
4256 if (ICS.isBad()) {
4257 Result = ICS;
4258 break;
4259 }
4260 // Otherwise, look for the worst conversion.
4261 if (Result.isBad() ||
4262 CompareImplicitConversionSequences(S, ICS, Result) ==
4263 ImplicitConversionSequence::Worse)
4264 Result = ICS;
4265 }
4266 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004267 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004268 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004269
4270 // C++11 [over.ics.list]p3:
4271 // Otherwise, if the parameter is a non-aggregate class X and overload
4272 // resolution chooses a single best constructor [...] the implicit
4273 // conversion sequence is a user-defined conversion sequence. If multiple
4274 // constructors are viable but none is better than the others, the
4275 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004276 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4277 // This function can deal with initializer lists.
4278 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4279 /*AllowExplicit=*/false,
4280 InOverloadResolution, /*CStyle=*/false,
4281 AllowObjCWritebackConversion);
4282 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004283 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004284 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004285
4286 // C++11 [over.ics.list]p4:
4287 // Otherwise, if the parameter has an aggregate type which can be
4288 // initialized from the initializer list [...] the implicit conversion
4289 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004290 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004291 // Type is an aggregate, argument is an init list. At this point it comes
4292 // down to checking whether the initialization works.
4293 // FIXME: Find out whether this parameter is consumed or not.
4294 InitializedEntity Entity =
4295 InitializedEntity::InitializeParameter(S.Context, ToType,
4296 /*Consumed=*/false);
4297 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4298 Result.setUserDefined();
4299 Result.UserDefined.Before.setAsIdentityConversion();
4300 // Initializer lists don't have a type.
4301 Result.UserDefined.Before.setFromType(QualType());
4302 Result.UserDefined.Before.setAllToTypes(QualType());
4303
4304 Result.UserDefined.After.setAsIdentityConversion();
4305 Result.UserDefined.After.setFromType(ToType);
4306 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004307 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004308 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004309 return Result;
4310 }
4311
4312 // C++11 [over.ics.list]p5:
4313 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004314 if (ToType->isReferenceType()) {
4315 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4316 // mention initializer lists in any way. So we go by what list-
4317 // initialization would do and try to extrapolate from that.
4318
4319 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4320
4321 // If the initializer list has a single element that is reference-related
4322 // to the parameter type, we initialize the reference from that.
4323 if (From->getNumInits() == 1) {
4324 Expr *Init = From->getInit(0);
4325
4326 QualType T2 = Init->getType();
4327
4328 // If the initializer is the address of an overloaded function, try
4329 // to resolve the overloaded function. If all goes well, T2 is the
4330 // type of the resulting function.
4331 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4332 DeclAccessPair Found;
4333 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4334 Init, ToType, false, Found))
4335 T2 = Fn->getType();
4336 }
4337
4338 // Compute some basic properties of the types and the initializer.
4339 bool dummy1 = false;
4340 bool dummy2 = false;
4341 bool dummy3 = false;
4342 Sema::ReferenceCompareResult RefRelationship
4343 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4344 dummy2, dummy3);
4345
4346 if (RefRelationship >= Sema::Ref_Related)
4347 return TryReferenceInit(S, Init, ToType,
4348 /*FIXME:*/From->getLocStart(),
4349 SuppressUserConversions,
4350 /*AllowExplicit=*/false);
4351 }
4352
4353 // Otherwise, we bind the reference to a temporary created from the
4354 // initializer list.
4355 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4356 InOverloadResolution,
4357 AllowObjCWritebackConversion);
4358 if (Result.isFailure())
4359 return Result;
4360 assert(!Result.isEllipsis() &&
4361 "Sub-initialization cannot result in ellipsis conversion.");
4362
4363 // Can we even bind to a temporary?
4364 if (ToType->isRValueReferenceType() ||
4365 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4366 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4367 Result.UserDefined.After;
4368 SCS.ReferenceBinding = true;
4369 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4370 SCS.BindsToRvalue = true;
4371 SCS.BindsToFunctionLvalue = false;
4372 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4373 SCS.ObjCLifetimeConversionBinding = false;
4374 } else
4375 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4376 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004377 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004378 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004379
4380 // C++11 [over.ics.list]p6:
4381 // Otherwise, if the parameter type is not a class:
4382 if (!ToType->isRecordType()) {
4383 // - if the initializer list has one element, the implicit conversion
4384 // sequence is the one required to convert the element to the
4385 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004386 unsigned NumInits = From->getNumInits();
4387 if (NumInits == 1)
4388 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4389 SuppressUserConversions,
4390 InOverloadResolution,
4391 AllowObjCWritebackConversion);
4392 // - if the initializer list has no elements, the implicit conversion
4393 // sequence is the identity conversion.
4394 else if (NumInits == 0) {
4395 Result.setStandard();
4396 Result.Standard.setAsIdentityConversion();
4397 }
4398 return Result;
4399 }
4400
4401 // C++11 [over.ics.list]p7:
4402 // In all cases other than those enumerated above, no conversion is possible
4403 return Result;
4404}
4405
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004406/// TryCopyInitialization - Try to copy-initialize a value of type
4407/// ToType from the expression From. Return the implicit conversion
4408/// sequence required to pass this argument, which may be a bad
4409/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004410/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004411/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004412static ImplicitConversionSequence
4413TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004414 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004415 bool InOverloadResolution,
4416 bool AllowObjCWritebackConversion) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004417 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4418 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4419 InOverloadResolution,AllowObjCWritebackConversion);
4420
Douglas Gregorabe183d2010-04-13 16:31:36 +00004421 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004422 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004423 /*FIXME:*/From->getLocStart(),
4424 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004425 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004426
John McCall120d63c2010-08-24 20:38:10 +00004427 return TryImplicitConversion(S, From, ToType,
4428 SuppressUserConversions,
4429 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004430 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004431 /*CStyle=*/false,
4432 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004433}
4434
Anna Zaksf3546ee2011-07-28 19:46:48 +00004435static bool TryCopyInitialization(const CanQualType FromQTy,
4436 const CanQualType ToQTy,
4437 Sema &S,
4438 SourceLocation Loc,
4439 ExprValueKind FromVK) {
4440 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4441 ImplicitConversionSequence ICS =
4442 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4443
4444 return !ICS.isBad();
4445}
4446
Douglas Gregor96176b32008-11-18 23:14:02 +00004447/// TryObjectArgumentInitialization - Try to initialize the object
4448/// parameter of the given member function (@c Method) from the
4449/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004450static ImplicitConversionSequence
4451TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004452 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004453 CXXMethodDecl *Method,
4454 CXXRecordDecl *ActingContext) {
4455 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004456 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4457 // const volatile object.
4458 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4459 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004460 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004461
4462 // Set up the conversion sequence as a "bad" conversion, to allow us
4463 // to exit early.
4464 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004465
4466 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004467 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004468 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004469 FromType = PT->getPointeeType();
4470
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004471 // When we had a pointer, it's implicitly dereferenced, so we
4472 // better have an lvalue.
4473 assert(FromClassification.isLValue());
4474 }
4475
Anders Carlssona552f7c2009-05-01 18:34:30 +00004476 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004477
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004478 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004479 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004480 // parameter is
4481 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004482 // - "lvalue reference to cv X" for functions declared without a
4483 // ref-qualifier or with the & ref-qualifier
4484 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004485 // ref-qualifier
4486 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004488 // cv-qualification on the member function declaration.
4489 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004490 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004491 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004492 // (C++ [over.match.funcs]p5). We perform a simplified version of
4493 // reference binding here, that allows class rvalues to bind to
4494 // non-constant references.
4495
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004496 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004497 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004498 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004499 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004500 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004501 ICS.setBad(BadConversionSequence::bad_qualifiers,
4502 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004503 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004504 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004505
4506 // Check that we have either the same type or a derived type. It
4507 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004508 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004509 ImplicitConversionKind SecondKind;
4510 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4511 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004512 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004513 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004514 else {
John McCallb1bdc622010-02-25 01:37:24 +00004515 ICS.setBad(BadConversionSequence::unrelated_class,
4516 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004517 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004518 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004519
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004520 // Check the ref-qualifier.
4521 switch (Method->getRefQualifier()) {
4522 case RQ_None:
4523 // Do nothing; we don't care about lvalueness or rvalueness.
4524 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004526 case RQ_LValue:
4527 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4528 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004529 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004530 ImplicitParamType);
4531 return ICS;
4532 }
4533 break;
4534
4535 case RQ_RValue:
4536 if (!FromClassification.isRValue()) {
4537 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004538 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004539 ImplicitParamType);
4540 return ICS;
4541 }
4542 break;
4543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004544
Douglas Gregor96176b32008-11-18 23:14:02 +00004545 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004546 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004547 ICS.Standard.setAsIdentityConversion();
4548 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004549 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004550 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004551 ICS.Standard.ReferenceBinding = true;
4552 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004553 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004554 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004555 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4556 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4557 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004558 return ICS;
4559}
4560
4561/// PerformObjectArgumentInitialization - Perform initialization of
4562/// the implicit object parameter for the given Method with the given
4563/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004564ExprResult
4565Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004566 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004567 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004568 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004569 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004570 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004571 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004572
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004573 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004574 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004575 FromRecordType = PT->getPointeeType();
4576 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004577 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004578 } else {
4579 FromRecordType = From->getType();
4580 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004581 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004582 }
4583
John McCall701c89e2009-12-03 04:06:58 +00004584 // Note that we always use the true parent context when performing
4585 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004586 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004587 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4588 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004589 if (ICS.isBad()) {
4590 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4591 Qualifiers FromQs = FromRecordType.getQualifiers();
4592 Qualifiers ToQs = DestType.getQualifiers();
4593 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4594 if (CVR) {
4595 Diag(From->getSourceRange().getBegin(),
4596 diag::err_member_function_call_bad_cvr)
4597 << Method->getDeclName() << FromRecordType << (CVR - 1)
4598 << From->getSourceRange();
4599 Diag(Method->getLocation(), diag::note_previous_decl)
4600 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004601 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004602 }
4603 }
4604
Douglas Gregor96176b32008-11-18 23:14:02 +00004605 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004606 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004607 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004608 }
Mike Stump1eb44332009-09-09 15:08:12 +00004609
John Wiegley429bb272011-04-08 18:41:53 +00004610 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4611 ExprResult FromRes =
4612 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4613 if (FromRes.isInvalid())
4614 return ExprError();
4615 From = FromRes.take();
4616 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004617
Douglas Gregor5fccd362010-03-03 23:55:11 +00004618 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004619 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004620 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004621 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004622}
4623
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004624/// TryContextuallyConvertToBool - Attempt to contextually convert the
4625/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004626static ImplicitConversionSequence
4627TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004628 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004629 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004630 // FIXME: Are these flags correct?
4631 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004632 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004633 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004634 /*CStyle=*/false,
4635 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004636}
4637
4638/// PerformContextuallyConvertToBool - Perform a contextual conversion
4639/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004640ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004641 if (checkPlaceholderForOverload(*this, From))
4642 return ExprError();
4643
John McCall120d63c2010-08-24 20:38:10 +00004644 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004645 if (!ICS.isBad())
4646 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004647
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004648 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00004649 return Diag(From->getSourceRange().getBegin(),
4650 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004651 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004652 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004653}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004654
Richard Smith8ef7b202012-01-18 23:55:52 +00004655/// Check that the specified conversion is permitted in a converted constant
4656/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4657/// is acceptable.
4658static bool CheckConvertedConstantConversions(Sema &S,
4659 StandardConversionSequence &SCS) {
4660 // Since we know that the target type is an integral or unscoped enumeration
4661 // type, most conversion kinds are impossible. All possible First and Third
4662 // conversions are fine.
4663 switch (SCS.Second) {
4664 case ICK_Identity:
4665 case ICK_Integral_Promotion:
4666 case ICK_Integral_Conversion:
4667 return true;
4668
4669 case ICK_Boolean_Conversion:
4670 // Conversion from an integral or unscoped enumeration type to bool is
4671 // classified as ICK_Boolean_Conversion, but it's also an integral
4672 // conversion, so it's permitted in a converted constant expression.
4673 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4674 SCS.getToType(2)->isBooleanType();
4675
4676 case ICK_Floating_Integral:
4677 case ICK_Complex_Real:
4678 return false;
4679
4680 case ICK_Lvalue_To_Rvalue:
4681 case ICK_Array_To_Pointer:
4682 case ICK_Function_To_Pointer:
4683 case ICK_NoReturn_Adjustment:
4684 case ICK_Qualification:
4685 case ICK_Compatible_Conversion:
4686 case ICK_Vector_Conversion:
4687 case ICK_Vector_Splat:
4688 case ICK_Derived_To_Base:
4689 case ICK_Pointer_Conversion:
4690 case ICK_Pointer_Member:
4691 case ICK_Block_Pointer_Conversion:
4692 case ICK_Writeback_Conversion:
4693 case ICK_Floating_Promotion:
4694 case ICK_Complex_Promotion:
4695 case ICK_Complex_Conversion:
4696 case ICK_Floating_Conversion:
4697 case ICK_TransparentUnionConversion:
4698 llvm_unreachable("unexpected second conversion kind");
4699
4700 case ICK_Num_Conversion_Kinds:
4701 break;
4702 }
4703
4704 llvm_unreachable("unknown conversion kind");
4705}
4706
4707/// CheckConvertedConstantExpression - Check that the expression From is a
4708/// converted constant expression of type T, perform the conversion and produce
4709/// the converted expression, per C++11 [expr.const]p3.
4710ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4711 llvm::APSInt &Value,
4712 CCEKind CCE) {
4713 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4714 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4715
4716 if (checkPlaceholderForOverload(*this, From))
4717 return ExprError();
4718
4719 // C++11 [expr.const]p3 with proposed wording fixes:
4720 // A converted constant expression of type T is a core constant expression,
4721 // implicitly converted to a prvalue of type T, where the converted
4722 // expression is a literal constant expression and the implicit conversion
4723 // sequence contains only user-defined conversions, lvalue-to-rvalue
4724 // conversions, integral promotions, and integral conversions other than
4725 // narrowing conversions.
4726 ImplicitConversionSequence ICS =
4727 TryImplicitConversion(From, T,
4728 /*SuppressUserConversions=*/false,
4729 /*AllowExplicit=*/false,
4730 /*InOverloadResolution=*/false,
4731 /*CStyle=*/false,
4732 /*AllowObjcWritebackConversion=*/false);
4733 StandardConversionSequence *SCS = 0;
4734 switch (ICS.getKind()) {
4735 case ImplicitConversionSequence::StandardConversion:
4736 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4737 return Diag(From->getSourceRange().getBegin(),
4738 diag::err_typecheck_converted_constant_expression_disallowed)
4739 << From->getType() << From->getSourceRange() << T;
4740 SCS = &ICS.Standard;
4741 break;
4742 case ImplicitConversionSequence::UserDefinedConversion:
4743 // We are converting from class type to an integral or enumeration type, so
4744 // the Before sequence must be trivial.
4745 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4746 return Diag(From->getSourceRange().getBegin(),
4747 diag::err_typecheck_converted_constant_expression_disallowed)
4748 << From->getType() << From->getSourceRange() << T;
4749 SCS = &ICS.UserDefined.After;
4750 break;
4751 case ImplicitConversionSequence::AmbiguousConversion:
4752 case ImplicitConversionSequence::BadConversion:
4753 if (!DiagnoseMultipleUserDefinedConversion(From, T))
4754 return Diag(From->getSourceRange().getBegin(),
4755 diag::err_typecheck_converted_constant_expression)
4756 << From->getType() << From->getSourceRange() << T;
4757 return ExprError();
4758
4759 case ImplicitConversionSequence::EllipsisConversion:
4760 llvm_unreachable("ellipsis conversion in converted constant expression");
4761 }
4762
4763 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4764 if (Result.isInvalid())
4765 return Result;
4766
4767 // Check for a narrowing implicit conversion.
4768 APValue PreNarrowingValue;
Richard Smithf72fccf2012-01-30 22:27:01 +00004769 bool Diagnosed = false;
Richard Smith8ef7b202012-01-18 23:55:52 +00004770 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue)) {
4771 case NK_Variable_Narrowing:
4772 // Implicit conversion to a narrower type, and the value is not a constant
4773 // expression. We'll diagnose this in a moment.
4774 case NK_Not_Narrowing:
4775 break;
4776
4777 case NK_Constant_Narrowing:
4778 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4779 << CCE << /*Constant*/1
4780 << PreNarrowingValue.getAsString(Context, QualType()) << T;
Richard Smithf72fccf2012-01-30 22:27:01 +00004781 Diagnosed = true;
Richard Smith8ef7b202012-01-18 23:55:52 +00004782 break;
4783
4784 case NK_Type_Narrowing:
4785 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4786 << CCE << /*Constant*/0 << From->getType() << T;
Richard Smithf72fccf2012-01-30 22:27:01 +00004787 Diagnosed = true;
Richard Smith8ef7b202012-01-18 23:55:52 +00004788 break;
4789 }
4790
4791 // Check the expression is a constant expression.
4792 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4793 Expr::EvalResult Eval;
4794 Eval.Diag = &Notes;
4795
4796 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4797 // The expression can't be folded, so we can't keep it at this position in
4798 // the AST.
4799 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004800 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004801 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004802
4803 if (Notes.empty()) {
4804 // It's a constant expression.
4805 return Result;
4806 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004807 }
4808
Richard Smithf72fccf2012-01-30 22:27:01 +00004809 // Only issue one narrowing diagnostic.
4810 if (Diagnosed)
4811 return Result;
4812
Richard Smith8ef7b202012-01-18 23:55:52 +00004813 // It's not a constant expression. Produce an appropriate diagnostic.
4814 if (Notes.size() == 1 &&
4815 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4816 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4817 else {
4818 Diag(From->getSourceRange().getBegin(), diag::err_expr_not_cce)
4819 << CCE << From->getSourceRange();
4820 for (unsigned I = 0; I < Notes.size(); ++I)
4821 Diag(Notes[I].first, Notes[I].second);
4822 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004823 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004824}
4825
John McCall0bcc9bc2011-09-09 06:11:02 +00004826/// dropPointerConversions - If the given standard conversion sequence
4827/// involves any pointer conversions, remove them. This may change
4828/// the result type of the conversion sequence.
4829static void dropPointerConversion(StandardConversionSequence &SCS) {
4830 if (SCS.Second == ICK_Pointer_Conversion) {
4831 SCS.Second = ICK_Identity;
4832 SCS.Third = ICK_Identity;
4833 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4834 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004835}
John McCall120d63c2010-08-24 20:38:10 +00004836
John McCall0bcc9bc2011-09-09 06:11:02 +00004837/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4838/// convert the expression From to an Objective-C pointer type.
4839static ImplicitConversionSequence
4840TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4841 // Do an implicit conversion to 'id'.
4842 QualType Ty = S.Context.getObjCIdType();
4843 ImplicitConversionSequence ICS
4844 = TryImplicitConversion(S, From, Ty,
4845 // FIXME: Are these flags correct?
4846 /*SuppressUserConversions=*/false,
4847 /*AllowExplicit=*/true,
4848 /*InOverloadResolution=*/false,
4849 /*CStyle=*/false,
4850 /*AllowObjCWritebackConversion=*/false);
4851
4852 // Strip off any final conversions to 'id'.
4853 switch (ICS.getKind()) {
4854 case ImplicitConversionSequence::BadConversion:
4855 case ImplicitConversionSequence::AmbiguousConversion:
4856 case ImplicitConversionSequence::EllipsisConversion:
4857 break;
4858
4859 case ImplicitConversionSequence::UserDefinedConversion:
4860 dropPointerConversion(ICS.UserDefined.After);
4861 break;
4862
4863 case ImplicitConversionSequence::StandardConversion:
4864 dropPointerConversion(ICS.Standard);
4865 break;
4866 }
4867
4868 return ICS;
4869}
4870
4871/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4872/// conversion of the expression From to an Objective-C pointer type.
4873ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004874 if (checkPlaceholderForOverload(*this, From))
4875 return ExprError();
4876
John McCallc12c5bb2010-05-15 11:32:37 +00004877 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004878 ImplicitConversionSequence ICS =
4879 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004880 if (!ICS.isBad())
4881 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004882 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004883}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004884
Richard Smithf39aec12012-02-04 07:07:42 +00004885/// Determine whether the provided type is an integral type, or an enumeration
4886/// type of a permitted flavor.
4887static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4888 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4889 : T->isIntegralOrUnscopedEnumerationType();
4890}
4891
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004892/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004893/// enumeration type.
4894///
4895/// This routine will attempt to convert an expression of class type to an
4896/// integral or enumeration type, if that class type only has a single
4897/// conversion to an integral or enumeration type.
4898///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004899/// \param Loc The source location of the construct that requires the
4900/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004901///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004902/// \param FromE The expression we're converting from.
4903///
4904/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4905/// have integral or enumeration type.
4906///
4907/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4908/// incomplete class type.
4909///
4910/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4911/// explicit conversion function (because no implicit conversion functions
4912/// were available). This is a recovery mode.
4913///
4914/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4915/// showing which conversion was picked.
4916///
4917/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4918/// conversion function that could convert to integral or enumeration type.
4919///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004920/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004921/// usable conversion function.
4922///
4923/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4924/// function, which may be an extension in this case.
4925///
Richard Smithf39aec12012-02-04 07:07:42 +00004926/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4927/// enumerations should be considered.
4928///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004929/// \returns The expression, converted to an integral or enumeration type if
4930/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004931ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004932Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004933 const PartialDiagnostic &NotIntDiag,
4934 const PartialDiagnostic &IncompleteDiag,
4935 const PartialDiagnostic &ExplicitConvDiag,
4936 const PartialDiagnostic &ExplicitConvNote,
4937 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004938 const PartialDiagnostic &AmbigNote,
Richard Smithf39aec12012-02-04 07:07:42 +00004939 const PartialDiagnostic &ConvDiag,
4940 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004941 // We can't perform any more checking for type-dependent expressions.
4942 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004943 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004944
Eli Friedmanceccab92012-01-26 00:26:18 +00004945 // Process placeholders immediately.
4946 if (From->hasPlaceholderType()) {
4947 ExprResult result = CheckPlaceholderExpr(From);
4948 if (result.isInvalid()) return result;
4949 From = result.take();
4950 }
4951
Douglas Gregorc30614b2010-06-29 23:17:37 +00004952 // If the expression already has integral or enumeration type, we're golden.
4953 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00004954 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00004955 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004956
4957 // FIXME: Check for missing '()' if T is a function type?
4958
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004959 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00004960 // expression of integral or enumeration type.
4961 const RecordType *RecordTy = T->getAs<RecordType>();
4962 if (!RecordTy || !getLangOptions().CPlusPlus) {
Richard Smith282e7e62012-02-04 09:53:13 +00004963 if (NotIntDiag.getDiagID())
4964 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00004965 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004966 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004967
Douglas Gregorc30614b2010-06-29 23:17:37 +00004968 // We must have a complete class type.
4969 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00004970 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004971
Douglas Gregorc30614b2010-06-29 23:17:37 +00004972 // Look for a conversion to an integral or enumeration type.
4973 UnresolvedSet<4> ViableConversions;
4974 UnresolvedSet<4> ExplicitConversions;
4975 const UnresolvedSetImpl *Conversions
4976 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004977
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004978 bool HadMultipleCandidates = (Conversions->size() > 1);
4979
Douglas Gregorc30614b2010-06-29 23:17:37 +00004980 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004981 E = Conversions->end();
4982 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00004983 ++I) {
4984 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00004985 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
4986 if (isIntegralOrEnumerationType(
4987 Conversion->getConversionType().getNonReferenceType(),
4988 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004989 if (Conversion->isExplicit())
4990 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4991 else
4992 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4993 }
Richard Smithf39aec12012-02-04 07:07:42 +00004994 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00004995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004996
Douglas Gregorc30614b2010-06-29 23:17:37 +00004997 switch (ViableConversions.size()) {
4998 case 0:
Richard Smith282e7e62012-02-04 09:53:13 +00004999 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005000 DeclAccessPair Found = ExplicitConversions[0];
5001 CXXConversionDecl *Conversion
5002 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003
Douglas Gregorc30614b2010-06-29 23:17:37 +00005004 // The user probably meant to invoke the given explicit
5005 // conversion; use it.
5006 QualType ConvTy
5007 = Conversion->getConversionType().getNonReferenceType();
5008 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005009 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005010
Douglas Gregorc30614b2010-06-29 23:17:37 +00005011 Diag(Loc, ExplicitConvDiag)
5012 << T << ConvTy
5013 << FixItHint::CreateInsertion(From->getLocStart(),
5014 "static_cast<" + TypeStr + ">(")
5015 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5016 ")");
5017 Diag(Conversion->getLocation(), ExplicitConvNote)
5018 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005019
5020 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005021 // explicit conversion function.
5022 if (isSFINAEContext())
5023 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005024
Douglas Gregorc30614b2010-06-29 23:17:37 +00005025 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005026 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5027 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005028 if (Result.isInvalid())
5029 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005030 // Record usage of conversion in an implicit cast.
5031 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5032 CK_UserDefinedConversion,
5033 Result.get(), 0,
5034 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005035 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005036
Douglas Gregorc30614b2010-06-29 23:17:37 +00005037 // We'll complain below about a non-integral condition type.
5038 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005039
Douglas Gregorc30614b2010-06-29 23:17:37 +00005040 case 1: {
5041 // Apply this conversion.
5042 DeclAccessPair Found = ViableConversions[0];
5043 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005044
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005045 CXXConversionDecl *Conversion
5046 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5047 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005048 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005049 if (ConvDiag.getDiagID()) {
5050 if (isSFINAEContext())
5051 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005052
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005053 Diag(Loc, ConvDiag)
5054 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005056
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005057 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5058 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005059 if (Result.isInvalid())
5060 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005061 // Record usage of conversion in an implicit cast.
5062 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5063 CK_UserDefinedConversion,
5064 Result.get(), 0,
5065 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005066 break;
5067 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005068
Douglas Gregorc30614b2010-06-29 23:17:37 +00005069 default:
Richard Smith282e7e62012-02-04 09:53:13 +00005070 if (!AmbigDiag.getDiagID())
5071 return Owned(From);
5072
Douglas Gregorc30614b2010-06-29 23:17:37 +00005073 Diag(Loc, AmbigDiag)
5074 << T << From->getSourceRange();
5075 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5076 CXXConversionDecl *Conv
5077 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5078 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5079 Diag(Conv->getLocation(), AmbigNote)
5080 << ConvTy->isEnumeralType() << ConvTy;
5081 }
John McCall9ae2f072010-08-23 23:25:46 +00005082 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005084
Richard Smith282e7e62012-02-04 09:53:13 +00005085 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5086 NotIntDiag.getDiagID())
5087 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005088
Eli Friedmanceccab92012-01-26 00:26:18 +00005089 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005090}
5091
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005092/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005093/// candidate functions, using the given function call arguments. If
5094/// @p SuppressUserConversions, then don't allow user-defined
5095/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005096///
5097/// \para PartialOverloading true if we are performing "partial" overloading
5098/// based on an incomplete set of function arguments. This feature is used by
5099/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005100void
5101Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005102 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005103 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005104 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005105 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005106 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00005107 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005108 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005109 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005110 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005111 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005112
Douglas Gregor88a35142008-12-22 05:46:06 +00005113 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005114 if (!isa<CXXConstructorDecl>(Method)) {
5115 // If we get here, it's because we're calling a member function
5116 // that is named without a member access expression (e.g.,
5117 // "this->f") that was either written explicitly or created
5118 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005119 // function, e.g., X::f(). We use an empty type for the implied
5120 // object argument (C++ [over.call.func]p3), and the acting context
5121 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005122 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005123 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005124 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005125 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005126 return;
5127 }
5128 // We treat a constructor like a non-member function, since its object
5129 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005130 }
5131
Douglas Gregorfd476482009-11-13 23:59:09 +00005132 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005133 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005134
Douglas Gregor7edfb692009-11-23 12:27:39 +00005135 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005136 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005137
Douglas Gregor66724ea2009-11-14 01:20:54 +00005138 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5139 // C++ [class.copy]p3:
5140 // A member function template is never instantiated to perform the copy
5141 // of a class object to an object of its class type.
5142 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005143 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005144 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005145 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5146 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005147 return;
5148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005149
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005150 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005151 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005152 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005153 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005154 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005155 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005156 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005157 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005158
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005159 unsigned NumArgsInProto = Proto->getNumArgs();
5160
5161 // (C++ 13.3.2p2): A candidate function having fewer than m
5162 // parameters is viable only if it has an ellipsis in its parameter
5163 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005164 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005165 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005166 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005167 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005168 return;
5169 }
5170
5171 // (C++ 13.3.2p2): A candidate function having more than m parameters
5172 // is viable only if the (m+1)st parameter has a default argument
5173 // (8.3.6). For the purposes of overload resolution, the
5174 // parameter list is truncated on the right, so that there are
5175 // exactly m parameters.
5176 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005177 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005178 // Not enough arguments.
5179 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005180 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005181 return;
5182 }
5183
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005184 // (CUDA B.1): Check for invalid calls between targets.
5185 if (getLangOptions().CUDA)
5186 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5187 if (CheckCUDATarget(Caller, Function)) {
5188 Candidate.Viable = false;
5189 Candidate.FailureKind = ovl_fail_bad_target;
5190 return;
5191 }
5192
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005193 // Determine the implicit conversion sequences for each of the
5194 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005195 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5196 if (ArgIdx < NumArgsInProto) {
5197 // (C++ 13.3.2p3): for F to be a viable function, there shall
5198 // exist for each argument an implicit conversion sequence
5199 // (13.3.3.1) that converts that argument to the corresponding
5200 // parameter of F.
5201 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005202 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005203 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005204 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005205 /*InOverloadResolution=*/true,
5206 /*AllowObjCWritebackConversion=*/
5207 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005208 if (Candidate.Conversions[ArgIdx].isBad()) {
5209 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005210 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005211 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005212 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005213 } else {
5214 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5215 // argument for which there is no corresponding parameter is
5216 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005217 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005218 }
5219 }
5220}
5221
Douglas Gregor063daf62009-03-13 18:40:31 +00005222/// \brief Add all of the function declarations in the given function set to
5223/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005224void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005225 Expr **Args, unsigned NumArgs,
5226 OverloadCandidateSet& CandidateSet,
5227 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00005228 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005229 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5230 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005231 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005232 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005233 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005234 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005235 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00005236 CandidateSet, SuppressUserConversions);
5237 else
John McCall9aa472c2010-03-19 07:35:19 +00005238 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005239 SuppressUserConversions);
5240 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005241 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005242 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5243 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005244 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005245 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00005246 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005247 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005248 Args[0]->Classify(Context),
5249 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00005250 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00005251 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005252 else
John McCall9aa472c2010-03-19 07:35:19 +00005253 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00005254 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00005255 Args, NumArgs, CandidateSet,
5256 SuppressUserConversions);
5257 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005258 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005259}
5260
John McCall314be4e2009-11-17 07:50:12 +00005261/// AddMethodCandidate - Adds a named decl (which is some kind of
5262/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005263void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005264 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005265 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005266 Expr **Args, unsigned NumArgs,
5267 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005268 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005269 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005270 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005271
5272 if (isa<UsingShadowDecl>(Decl))
5273 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005274
John McCall314be4e2009-11-17 07:50:12 +00005275 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5276 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5277 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005278 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5279 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005280 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00005281 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005282 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005283 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005284 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005285 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005286 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005287 }
5288}
5289
Douglas Gregor96176b32008-11-18 23:14:02 +00005290/// AddMethodCandidate - Adds the given C++ member function to the set
5291/// of candidate functions, using the given function call arguments
5292/// and the object argument (@c Object). For example, in a call
5293/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5294/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5295/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005296/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005297void
John McCall9aa472c2010-03-19 07:35:19 +00005298Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005299 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005300 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00005301 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00005302 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005303 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005304 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005305 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005306 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005307 assert(!isa<CXXConstructorDecl>(Method) &&
5308 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005309
Douglas Gregor3f396022009-09-28 04:47:19 +00005310 if (!CandidateSet.isNewCandidate(Method))
5311 return;
5312
Douglas Gregor7edfb692009-11-23 12:27:39 +00005313 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005314 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005315
Douglas Gregor96176b32008-11-18 23:14:02 +00005316 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005317 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005318 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005319 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005320 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005321 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005322 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00005323
5324 unsigned NumArgsInProto = Proto->getNumArgs();
5325
5326 // (C++ 13.3.2p2): A candidate function having fewer than m
5327 // parameters is viable only if it has an ellipsis in its parameter
5328 // list (8.3.5).
5329 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5330 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005331 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005332 return;
5333 }
5334
5335 // (C++ 13.3.2p2): A candidate function having more than m parameters
5336 // is viable only if the (m+1)st parameter has a default argument
5337 // (8.3.6). For the purposes of overload resolution, the
5338 // parameter list is truncated on the right, so that there are
5339 // exactly m parameters.
5340 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5341 if (NumArgs < MinRequiredArgs) {
5342 // Not enough arguments.
5343 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005344 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005345 return;
5346 }
5347
5348 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005349
John McCall701c89e2009-12-03 04:06:58 +00005350 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005351 // The implicit object argument is ignored.
5352 Candidate.IgnoreObjectArgument = true;
5353 else {
5354 // Determine the implicit conversion sequence for the object
5355 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005356 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005357 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5358 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005359 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005360 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005361 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005362 return;
5363 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005364 }
5365
5366 // Determine the implicit conversion sequences for each of the
5367 // arguments.
5368 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5369 if (ArgIdx < NumArgsInProto) {
5370 // (C++ 13.3.2p3): for F to be a viable function, there shall
5371 // exist for each argument an implicit conversion sequence
5372 // (13.3.3.1) that converts that argument to the corresponding
5373 // parameter of F.
5374 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005375 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005376 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005377 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005378 /*InOverloadResolution=*/true,
5379 /*AllowObjCWritebackConversion=*/
5380 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005381 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005382 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005383 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005384 break;
5385 }
5386 } else {
5387 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5388 // argument for which there is no corresponding parameter is
5389 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005390 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005391 }
5392 }
5393}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005394
Douglas Gregor6b906862009-08-21 00:16:32 +00005395/// \brief Add a C++ member function template as a candidate to the candidate
5396/// set, using template argument deduction to produce an appropriate member
5397/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005398void
Douglas Gregor6b906862009-08-21 00:16:32 +00005399Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005400 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005401 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005402 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005403 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005404 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00005405 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00005406 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005407 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005408 if (!CandidateSet.isNewCandidate(MethodTmpl))
5409 return;
5410
Douglas Gregor6b906862009-08-21 00:16:32 +00005411 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005412 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005413 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005414 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005415 // candidate functions in the usual way.113) A given name can refer to one
5416 // or more function templates and also to a set of overloaded non-template
5417 // functions. In such a case, the candidate functions generated from each
5418 // function template are combined with the set of non-template candidate
5419 // functions.
John McCall5769d612010-02-08 23:07:23 +00005420 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005421 FunctionDecl *Specialization = 0;
5422 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00005423 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00005424 Args, NumArgs, Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005425 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005426 Candidate.FoundDecl = FoundDecl;
5427 Candidate.Function = MethodTmpl->getTemplatedDecl();
5428 Candidate.Viable = false;
5429 Candidate.FailureKind = ovl_fail_bad_deduction;
5430 Candidate.IsSurrogate = false;
5431 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005432 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005433 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005434 Info);
5435 return;
5436 }
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Douglas Gregor6b906862009-08-21 00:16:32 +00005438 // Add the function template specialization produced by template argument
5439 // deduction as a candidate.
5440 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005441 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005442 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005443 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005444 ActingContext, ObjectType, ObjectClassification,
5445 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005446}
5447
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005448/// \brief Add a C++ function template specialization as a candidate
5449/// in the candidate set, using template argument deduction to produce
5450/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005451void
Douglas Gregore53060f2009-06-25 22:08:12 +00005452Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005453 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005454 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00005455 Expr **Args, unsigned NumArgs,
5456 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005457 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005458 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5459 return;
5460
Douglas Gregore53060f2009-06-25 22:08:12 +00005461 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005462 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005463 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005464 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005465 // candidate functions in the usual way.113) A given name can refer to one
5466 // or more function templates and also to a set of overloaded non-template
5467 // functions. In such a case, the candidate functions generated from each
5468 // function template are combined with the set of non-template candidate
5469 // functions.
John McCall5769d612010-02-08 23:07:23 +00005470 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005471 FunctionDecl *Specialization = 0;
5472 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00005473 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005474 Args, NumArgs, Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005475 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005476 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005477 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5478 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005479 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005480 Candidate.IsSurrogate = false;
5481 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005482 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005483 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005484 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005485 return;
5486 }
Mike Stump1eb44332009-09-09 15:08:12 +00005487
Douglas Gregore53060f2009-06-25 22:08:12 +00005488 // Add the function template specialization produced by template argument
5489 // deduction as a candidate.
5490 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005491 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005492 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005493}
Mike Stump1eb44332009-09-09 15:08:12 +00005494
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005495/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005496/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005497/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005498/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005499/// (which may or may not be the same type as the type that the
5500/// conversion function produces).
5501void
5502Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005503 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005504 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005505 Expr *From, QualType ToType,
5506 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005507 assert(!Conversion->getDescribedFunctionTemplate() &&
5508 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005509 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005510 if (!CandidateSet.isNewCandidate(Conversion))
5511 return;
5512
Douglas Gregor7edfb692009-11-23 12:27:39 +00005513 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005514 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005515
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005516 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005517 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005518 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005519 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005520 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005521 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005522 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005523 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005524 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005525 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005526 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005527
Douglas Gregorbca39322010-08-19 15:37:02 +00005528 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005529 // For conversion functions, the function is considered to be a member of
5530 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005531 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005532 //
5533 // Determine the implicit conversion sequence for the implicit
5534 // object parameter.
5535 QualType ImplicitParamType = From->getType();
5536 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5537 ImplicitParamType = FromPtrType->getPointeeType();
5538 CXXRecordDecl *ConversionContext
5539 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005540
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005541 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005542 = TryObjectArgumentInitialization(*this, From->getType(),
5543 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005544 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005545
John McCall1d318332010-01-12 00:44:57 +00005546 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005547 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005548 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005549 return;
5550 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005551
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005552 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005553 // derived to base as such conversions are given Conversion Rank. They only
5554 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5555 QualType FromCanon
5556 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5557 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5558 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5559 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005560 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005561 return;
5562 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005563
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005564 // To determine what the conversion from the result of calling the
5565 // conversion function to the type we're eventually trying to
5566 // convert to (ToType), we need to synthesize a call to the
5567 // conversion function and attempt copy initialization from it. This
5568 // makes sure that we get the right semantics with respect to
5569 // lvalues/rvalues and the type. Fortunately, we can allocate this
5570 // call on the stack and we don't need its arguments to be
5571 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00005572 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005573 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005574 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5575 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005576 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005577 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005578
Richard Smith87c1f1f2011-07-13 22:53:21 +00005579 QualType ConversionType = Conversion->getConversionType();
5580 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005581 Candidate.Viable = false;
5582 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5583 return;
5584 }
5585
Richard Smith87c1f1f2011-07-13 22:53:21 +00005586 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005587
Mike Stump1eb44332009-09-09 15:08:12 +00005588 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005589 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5590 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005591 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005592 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005593 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005594 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005595 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005596 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005597 /*InOverloadResolution=*/false,
5598 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005599
John McCall1d318332010-01-12 00:44:57 +00005600 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005601 case ImplicitConversionSequence::StandardConversion:
5602 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005603
Douglas Gregorc520c842010-04-12 23:42:09 +00005604 // C++ [over.ics.user]p3:
5605 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005606 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005607 // shall have exact match rank.
5608 if (Conversion->getPrimaryTemplate() &&
5609 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5610 Candidate.Viable = false;
5611 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5612 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005613
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005614 // C++0x [dcl.init.ref]p5:
5615 // In the second case, if the reference is an rvalue reference and
5616 // the second standard conversion sequence of the user-defined
5617 // conversion sequence includes an lvalue-to-rvalue conversion, the
5618 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005619 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005620 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5621 Candidate.Viable = false;
5622 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5623 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005624 break;
5625
5626 case ImplicitConversionSequence::BadConversion:
5627 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005628 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005629 break;
5630
5631 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005632 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005633 "Can only end up with a standard conversion sequence or failure");
5634 }
5635}
5636
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005637/// \brief Adds a conversion function template specialization
5638/// candidate to the overload set, using template argument deduction
5639/// to deduce the template arguments of the conversion function
5640/// template from the type that we are converting to (C++
5641/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005642void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005643Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005644 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005645 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005646 Expr *From, QualType ToType,
5647 OverloadCandidateSet &CandidateSet) {
5648 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5649 "Only conversion function templates permitted here");
5650
Douglas Gregor3f396022009-09-28 04:47:19 +00005651 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5652 return;
5653
John McCall5769d612010-02-08 23:07:23 +00005654 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005655 CXXConversionDecl *Specialization = 0;
5656 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005657 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005658 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005659 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005660 Candidate.FoundDecl = FoundDecl;
5661 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5662 Candidate.Viable = false;
5663 Candidate.FailureKind = ovl_fail_bad_deduction;
5664 Candidate.IsSurrogate = false;
5665 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005666 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005667 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005668 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005669 return;
5670 }
Mike Stump1eb44332009-09-09 15:08:12 +00005671
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005672 // Add the conversion function template specialization produced by
5673 // template argument deduction as a candidate.
5674 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005675 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005676 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005677}
5678
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005679/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5680/// converts the given @c Object to a function pointer via the
5681/// conversion function @c Conversion, and then attempts to call it
5682/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5683/// the type of function that we'll eventually be calling.
5684void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005685 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005686 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005687 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005688 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00005689 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005690 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005691 if (!CandidateSet.isNewCandidate(Conversion))
5692 return;
5693
Douglas Gregor7edfb692009-11-23 12:27:39 +00005694 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005695 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005696
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005697 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005698 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005699 Candidate.Function = 0;
5700 Candidate.Surrogate = Conversion;
5701 Candidate.Viable = true;
5702 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005703 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005704 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005705
5706 // Determine the implicit conversion sequence for the implicit
5707 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005708 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005709 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005710 Object->Classify(Context),
5711 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005712 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005713 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005714 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005715 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005716 return;
5717 }
5718
5719 // The first conversion is actually a user-defined conversion whose
5720 // first conversion is ObjectInit's standard conversion (which is
5721 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005722 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005723 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005724 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005725 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005726 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005727 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005728 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005729 = Candidate.Conversions[0].UserDefined.Before;
5730 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5731
Mike Stump1eb44332009-09-09 15:08:12 +00005732 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005733 unsigned NumArgsInProto = Proto->getNumArgs();
5734
5735 // (C++ 13.3.2p2): A candidate function having fewer than m
5736 // parameters is viable only if it has an ellipsis in its parameter
5737 // list (8.3.5).
5738 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5739 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005740 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005741 return;
5742 }
5743
5744 // Function types don't have any default arguments, so just check if
5745 // we have enough arguments.
5746 if (NumArgs < NumArgsInProto) {
5747 // Not enough arguments.
5748 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005749 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005750 return;
5751 }
5752
5753 // Determine the implicit conversion sequences for each of the
5754 // arguments.
5755 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5756 if (ArgIdx < NumArgsInProto) {
5757 // (C++ 13.3.2p3): for F to be a viable function, there shall
5758 // exist for each argument an implicit conversion sequence
5759 // (13.3.3.1) that converts that argument to the corresponding
5760 // parameter of F.
5761 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005762 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005763 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005764 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005765 /*InOverloadResolution=*/false,
5766 /*AllowObjCWritebackConversion=*/
5767 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005768 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005769 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005770 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005771 break;
5772 }
5773 } else {
5774 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5775 // argument for which there is no corresponding parameter is
5776 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005777 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005778 }
5779 }
5780}
5781
Douglas Gregor063daf62009-03-13 18:40:31 +00005782/// \brief Add overload candidates for overloaded operators that are
5783/// member functions.
5784///
5785/// Add the overloaded operator candidates that are member functions
5786/// for the operator Op that was used in an operator expression such
5787/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5788/// CandidateSet will store the added overload candidates. (C++
5789/// [over.match.oper]).
5790void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5791 SourceLocation OpLoc,
5792 Expr **Args, unsigned NumArgs,
5793 OverloadCandidateSet& CandidateSet,
5794 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005795 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5796
5797 // C++ [over.match.oper]p3:
5798 // For a unary operator @ with an operand of a type whose
5799 // cv-unqualified version is T1, and for a binary operator @ with
5800 // a left operand of a type whose cv-unqualified version is T1 and
5801 // a right operand of a type whose cv-unqualified version is T2,
5802 // three sets of candidate functions, designated member
5803 // candidates, non-member candidates and built-in candidates, are
5804 // constructed as follows:
5805 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005806
5807 // -- If T1 is a class type, the set of member candidates is the
5808 // result of the qualified lookup of T1::operator@
5809 // (13.3.1.1.1); otherwise, the set of member candidates is
5810 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005811 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005812 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005813 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005814 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005815
John McCalla24dc2e2009-11-17 02:14:36 +00005816 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5817 LookupQualifiedName(Operators, T1Rec->getDecl());
5818 Operators.suppressDiagnostics();
5819
Mike Stump1eb44332009-09-09 15:08:12 +00005820 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005821 OperEnd = Operators.end();
5822 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005823 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005824 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005825 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005826 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005827 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005828 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005829}
5830
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005831/// AddBuiltinCandidate - Add a candidate for a built-in
5832/// operator. ResultTy and ParamTys are the result and parameter types
5833/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005834/// arguments being passed to the candidate. IsAssignmentOperator
5835/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005836/// operator. NumContextualBoolArguments is the number of arguments
5837/// (at the beginning of the argument list) that will be contextually
5838/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005839void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005840 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005841 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005842 bool IsAssignmentOperator,
5843 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005844 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005845 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005846
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005847 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005848 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005849 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005850 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005851 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005852 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005853 Candidate.BuiltinTypes.ResultTy = ResultTy;
5854 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5855 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5856
5857 // Determine the implicit conversion sequences for each of the
5858 // arguments.
5859 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005860 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005861 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005862 // C++ [over.match.oper]p4:
5863 // For the built-in assignment operators, conversions of the
5864 // left operand are restricted as follows:
5865 // -- no temporaries are introduced to hold the left operand, and
5866 // -- no user-defined conversions are applied to the left
5867 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005868 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005869 //
5870 // We block these conversions by turning off user-defined
5871 // conversions, since that is the only way that initialization of
5872 // a reference to a non-class type can occur from something that
5873 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005874 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005875 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005876 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005877 Candidate.Conversions[ArgIdx]
5878 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005879 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005880 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005881 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005882 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005883 /*InOverloadResolution=*/false,
5884 /*AllowObjCWritebackConversion=*/
5885 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005886 }
John McCall1d318332010-01-12 00:44:57 +00005887 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005888 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005889 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005890 break;
5891 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005892 }
5893}
5894
5895/// BuiltinCandidateTypeSet - A set of types that will be used for the
5896/// candidate operator functions for built-in operators (C++
5897/// [over.built]). The types are separated into pointer types and
5898/// enumeration types.
5899class BuiltinCandidateTypeSet {
5900 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005901 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005902
5903 /// PointerTypes - The set of pointer types that will be used in the
5904 /// built-in candidates.
5905 TypeSet PointerTypes;
5906
Sebastian Redl78eb8742009-04-19 21:53:20 +00005907 /// MemberPointerTypes - The set of member pointer types that will be
5908 /// used in the built-in candidates.
5909 TypeSet MemberPointerTypes;
5910
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005911 /// EnumerationTypes - The set of enumeration types that will be
5912 /// used in the built-in candidates.
5913 TypeSet EnumerationTypes;
5914
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005915 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005916 /// candidates.
5917 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005918
5919 /// \brief A flag indicating non-record types are viable candidates
5920 bool HasNonRecordTypes;
5921
5922 /// \brief A flag indicating whether either arithmetic or enumeration types
5923 /// were present in the candidate set.
5924 bool HasArithmeticOrEnumeralTypes;
5925
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005926 /// \brief A flag indicating whether the nullptr type was present in the
5927 /// candidate set.
5928 bool HasNullPtrType;
5929
Douglas Gregor5842ba92009-08-24 15:23:48 +00005930 /// Sema - The semantic analysis instance where we are building the
5931 /// candidate type set.
5932 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005933
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005934 /// Context - The AST context in which we will build the type sets.
5935 ASTContext &Context;
5936
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005937 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5938 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005939 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005940
5941public:
5942 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005943 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005944
Mike Stump1eb44332009-09-09 15:08:12 +00005945 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005946 : HasNonRecordTypes(false),
5947 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005948 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00005949 SemaRef(SemaRef),
5950 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005951
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005953 SourceLocation Loc,
5954 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005955 bool AllowExplicitConversions,
5956 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005957
5958 /// pointer_begin - First pointer type found;
5959 iterator pointer_begin() { return PointerTypes.begin(); }
5960
Sebastian Redl78eb8742009-04-19 21:53:20 +00005961 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005962 iterator pointer_end() { return PointerTypes.end(); }
5963
Sebastian Redl78eb8742009-04-19 21:53:20 +00005964 /// member_pointer_begin - First member pointer type found;
5965 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5966
5967 /// member_pointer_end - Past the last member pointer type found;
5968 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5969
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005970 /// enumeration_begin - First enumeration type found;
5971 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5972
Sebastian Redl78eb8742009-04-19 21:53:20 +00005973 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005974 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005975
Douglas Gregor26bcf672010-05-19 03:21:00 +00005976 iterator vector_begin() { return VectorTypes.begin(); }
5977 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00005978
5979 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5980 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005981 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005982};
5983
Sebastian Redl78eb8742009-04-19 21:53:20 +00005984/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005985/// the set of pointer types along with any more-qualified variants of
5986/// that type. For example, if @p Ty is "int const *", this routine
5987/// will add "int const *", "int const volatile *", "int const
5988/// restrict *", and "int const volatile restrict *" to the set of
5989/// pointer types. Returns true if the add of @p Ty itself succeeded,
5990/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005991///
5992/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005993bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00005994BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5995 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00005996
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005997 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005998 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005999 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006000
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006001 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006002 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006003 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006004 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006005 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006006 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006007 buildObjCPtr = true;
6008 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006009 else
David Blaikieb219cfc2011-09-23 05:06:16 +00006010 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006011 }
6012 else
6013 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006014
Sebastian Redla9efada2009-11-18 20:39:26 +00006015 // Don't add qualified variants of arrays. For one, they're not allowed
6016 // (the qualifier would sink to the element type), and for another, the
6017 // only overload situation where it matters is subscript or pointer +- int,
6018 // and those shouldn't have qualifier variants anyway.
6019 if (PointeeTy->isArrayType())
6020 return true;
John McCall0953e762009-09-24 19:53:00 +00006021 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00006022 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00006023 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006024 bool hasVolatile = VisibleQuals.hasVolatile();
6025 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006026
John McCall0953e762009-09-24 19:53:00 +00006027 // Iterate through all strict supersets of BaseCVR.
6028 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6029 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006030 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6031 // in the types.
6032 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6033 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00006034 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006035 if (!buildObjCPtr)
6036 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6037 else
6038 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006039 }
6040
6041 return true;
6042}
6043
Sebastian Redl78eb8742009-04-19 21:53:20 +00006044/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6045/// to the set of pointer types along with any more-qualified variants of
6046/// that type. For example, if @p Ty is "int const *", this routine
6047/// will add "int const *", "int const volatile *", "int const
6048/// restrict *", and "int const volatile restrict *" to the set of
6049/// pointer types. Returns true if the add of @p Ty itself succeeded,
6050/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006051///
6052/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006053bool
6054BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6055 QualType Ty) {
6056 // Insert this type.
6057 if (!MemberPointerTypes.insert(Ty))
6058 return false;
6059
John McCall0953e762009-09-24 19:53:00 +00006060 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6061 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006062
John McCall0953e762009-09-24 19:53:00 +00006063 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006064 // Don't add qualified variants of arrays. For one, they're not allowed
6065 // (the qualifier would sink to the element type), and for another, the
6066 // only overload situation where it matters is subscript or pointer +- int,
6067 // and those shouldn't have qualifier variants anyway.
6068 if (PointeeTy->isArrayType())
6069 return true;
John McCall0953e762009-09-24 19:53:00 +00006070 const Type *ClassTy = PointerTy->getClass();
6071
6072 // Iterate through all strict supersets of the pointee type's CVR
6073 // qualifiers.
6074 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6075 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6076 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006077
John McCall0953e762009-09-24 19:53:00 +00006078 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006079 MemberPointerTypes.insert(
6080 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006081 }
6082
6083 return true;
6084}
6085
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006086/// AddTypesConvertedFrom - Add each of the types to which the type @p
6087/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006088/// primarily interested in pointer types and enumeration types. We also
6089/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006090/// AllowUserConversions is true if we should look at the conversion
6091/// functions of a class type, and AllowExplicitConversions if we
6092/// should also include the explicit conversion functions of a class
6093/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006094void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006095BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006096 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006097 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006098 bool AllowExplicitConversions,
6099 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006100 // Only deal with canonical types.
6101 Ty = Context.getCanonicalType(Ty);
6102
6103 // Look through reference types; they aren't part of the type of an
6104 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006105 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006106 Ty = RefTy->getPointeeType();
6107
John McCall3b657512011-01-19 10:06:00 +00006108 // If we're dealing with an array type, decay to the pointer.
6109 if (Ty->isArrayType())
6110 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6111
6112 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006113 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006114
Chandler Carruth6a577462010-12-13 01:44:01 +00006115 // Flag if we ever add a non-record type.
6116 const RecordType *TyRec = Ty->getAs<RecordType>();
6117 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6118
Chandler Carruth6a577462010-12-13 01:44:01 +00006119 // Flag if we encounter an arithmetic type.
6120 HasArithmeticOrEnumeralTypes =
6121 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6122
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006123 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6124 PointerTypes.insert(Ty);
6125 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006126 // Insert our type, and its more-qualified variants, into the set
6127 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006128 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006129 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006130 } else if (Ty->isMemberPointerType()) {
6131 // Member pointers are far easier, since the pointee can't be converted.
6132 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6133 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006134 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006135 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006136 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006137 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006138 // We treat vector types as arithmetic types in many contexts as an
6139 // extension.
6140 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006141 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006142 } else if (Ty->isNullPtrType()) {
6143 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006144 } else if (AllowUserConversions && TyRec) {
6145 // No conversion functions in incomplete types.
6146 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6147 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006148
Chandler Carruth6a577462010-12-13 01:44:01 +00006149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6150 const UnresolvedSetImpl *Conversions
6151 = ClassDecl->getVisibleConversionFunctions();
6152 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6153 E = Conversions->end(); I != E; ++I) {
6154 NamedDecl *D = I.getDecl();
6155 if (isa<UsingShadowDecl>(D))
6156 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006157
Chandler Carruth6a577462010-12-13 01:44:01 +00006158 // Skip conversion function templates; they don't tell us anything
6159 // about which builtin types we can convert to.
6160 if (isa<FunctionTemplateDecl>(D))
6161 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006162
Chandler Carruth6a577462010-12-13 01:44:01 +00006163 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6164 if (AllowExplicitConversions || !Conv->isExplicit()) {
6165 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6166 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006167 }
6168 }
6169 }
6170}
6171
Douglas Gregor19b7b152009-08-24 13:43:27 +00006172/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6173/// the volatile- and non-volatile-qualified assignment operators for the
6174/// given type to the candidate set.
6175static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6176 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006177 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006178 unsigned NumArgs,
6179 OverloadCandidateSet &CandidateSet) {
6180 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006181
Douglas Gregor19b7b152009-08-24 13:43:27 +00006182 // T& operator=(T&, T)
6183 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6184 ParamTypes[1] = T;
6185 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6186 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006187
Douglas Gregor19b7b152009-08-24 13:43:27 +00006188 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6189 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006190 ParamTypes[0]
6191 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006192 ParamTypes[1] = T;
6193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006194 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006195 }
6196}
Mike Stump1eb44332009-09-09 15:08:12 +00006197
Sebastian Redl9994a342009-10-25 17:03:50 +00006198/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6199/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006200static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6201 Qualifiers VRQuals;
6202 const RecordType *TyRec;
6203 if (const MemberPointerType *RHSMPType =
6204 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006205 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006206 else
6207 TyRec = ArgExpr->getType()->getAs<RecordType>();
6208 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006209 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006210 VRQuals.addVolatile();
6211 VRQuals.addRestrict();
6212 return VRQuals;
6213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006214
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006215 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006216 if (!ClassDecl->hasDefinition())
6217 return VRQuals;
6218
John McCalleec51cf2010-01-20 00:46:10 +00006219 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006220 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006221
John McCalleec51cf2010-01-20 00:46:10 +00006222 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006223 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006224 NamedDecl *D = I.getDecl();
6225 if (isa<UsingShadowDecl>(D))
6226 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6227 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006228 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6229 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6230 CanTy = ResTypeRef->getPointeeType();
6231 // Need to go down the pointer/mempointer chain and add qualifiers
6232 // as see them.
6233 bool done = false;
6234 while (!done) {
6235 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6236 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006237 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006238 CanTy->getAs<MemberPointerType>())
6239 CanTy = ResTypeMPtr->getPointeeType();
6240 else
6241 done = true;
6242 if (CanTy.isVolatileQualified())
6243 VRQuals.addVolatile();
6244 if (CanTy.isRestrictQualified())
6245 VRQuals.addRestrict();
6246 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6247 return VRQuals;
6248 }
6249 }
6250 }
6251 return VRQuals;
6252}
John McCall00071ec2010-11-13 05:51:15 +00006253
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006254namespace {
John McCall00071ec2010-11-13 05:51:15 +00006255
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006256/// \brief Helper class to manage the addition of builtin operator overload
6257/// candidates. It provides shared state and utility methods used throughout
6258/// the process, as well as a helper method to add each group of builtin
6259/// operator overloads from the standard to a candidate set.
6260class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006261 // Common instance state available to all overload candidate addition methods.
6262 Sema &S;
6263 Expr **Args;
6264 unsigned NumArgs;
6265 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006266 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006267 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006268 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006269
Chandler Carruth6d695582010-12-12 10:35:00 +00006270 // Define some constants used to index and iterate over the arithemetic types
6271 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006272 // The "promoted arithmetic types" are the arithmetic
6273 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006274 static const unsigned FirstIntegralType = 3;
6275 static const unsigned LastIntegralType = 18;
6276 static const unsigned FirstPromotedIntegralType = 3,
6277 LastPromotedIntegralType = 9;
6278 static const unsigned FirstPromotedArithmeticType = 0,
6279 LastPromotedArithmeticType = 9;
6280 static const unsigned NumArithmeticTypes = 18;
6281
Chandler Carruth6d695582010-12-12 10:35:00 +00006282 /// \brief Get the canonical type for a given arithmetic type index.
6283 CanQualType getArithmeticType(unsigned index) {
6284 assert(index < NumArithmeticTypes);
6285 static CanQualType ASTContext::* const
6286 ArithmeticTypes[NumArithmeticTypes] = {
6287 // Start of promoted types.
6288 &ASTContext::FloatTy,
6289 &ASTContext::DoubleTy,
6290 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006291
Chandler Carruth6d695582010-12-12 10:35:00 +00006292 // Start of integral types.
6293 &ASTContext::IntTy,
6294 &ASTContext::LongTy,
6295 &ASTContext::LongLongTy,
6296 &ASTContext::UnsignedIntTy,
6297 &ASTContext::UnsignedLongTy,
6298 &ASTContext::UnsignedLongLongTy,
6299 // End of promoted types.
6300
6301 &ASTContext::BoolTy,
6302 &ASTContext::CharTy,
6303 &ASTContext::WCharTy,
6304 &ASTContext::Char16Ty,
6305 &ASTContext::Char32Ty,
6306 &ASTContext::SignedCharTy,
6307 &ASTContext::ShortTy,
6308 &ASTContext::UnsignedCharTy,
6309 &ASTContext::UnsignedShortTy,
6310 // End of integral types.
6311 // FIXME: What about complex?
6312 };
6313 return S.Context.*ArithmeticTypes[index];
6314 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006315
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006316 /// \brief Gets the canonical type resulting from the usual arithemetic
6317 /// converions for the given arithmetic types.
6318 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6319 // Accelerator table for performing the usual arithmetic conversions.
6320 // The rules are basically:
6321 // - if either is floating-point, use the wider floating-point
6322 // - if same signedness, use the higher rank
6323 // - if same size, use unsigned of the higher rank
6324 // - use the larger type
6325 // These rules, together with the axiom that higher ranks are
6326 // never smaller, are sufficient to precompute all of these results
6327 // *except* when dealing with signed types of higher rank.
6328 // (we could precompute SLL x UI for all known platforms, but it's
6329 // better not to make any assumptions).
6330 enum PromotedType {
6331 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6332 };
6333 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6334 [LastPromotedArithmeticType] = {
6335 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6336 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6337 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6338 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6339 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6340 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6341 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6342 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6343 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6344 };
6345
6346 assert(L < LastPromotedArithmeticType);
6347 assert(R < LastPromotedArithmeticType);
6348 int Idx = ConversionsTable[L][R];
6349
6350 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006351 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006352
6353 // Slow path: we need to compare widths.
6354 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006355 CanQualType LT = getArithmeticType(L),
6356 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006357 unsigned LW = S.Context.getIntWidth(LT),
6358 RW = S.Context.getIntWidth(RT);
6359
6360 // If they're different widths, use the signed type.
6361 if (LW > RW) return LT;
6362 else if (LW < RW) return RT;
6363
6364 // Otherwise, use the unsigned type of the signed type's rank.
6365 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6366 assert(L == SLL || R == SLL);
6367 return S.Context.UnsignedLongLongTy;
6368 }
6369
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006370 /// \brief Helper method to factor out the common pattern of adding overloads
6371 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006372 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6373 bool HasVolatile) {
6374 QualType ParamTypes[2] = {
6375 S.Context.getLValueReferenceType(CandidateTy),
6376 S.Context.IntTy
6377 };
6378
6379 // Non-volatile version.
6380 if (NumArgs == 1)
6381 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6382 else
6383 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6384
6385 // Use a heuristic to reduce number of builtin candidates in the set:
6386 // add volatile version only if there are conversions to a volatile type.
6387 if (HasVolatile) {
6388 ParamTypes[0] =
6389 S.Context.getLValueReferenceType(
6390 S.Context.getVolatileType(CandidateTy));
6391 if (NumArgs == 1)
6392 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6393 else
6394 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6395 }
6396 }
6397
6398public:
6399 BuiltinOperatorOverloadBuilder(
6400 Sema &S, Expr **Args, unsigned NumArgs,
6401 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006402 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006403 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006404 OverloadCandidateSet &CandidateSet)
6405 : S(S), Args(Args), NumArgs(NumArgs),
6406 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006407 HasArithmeticOrEnumeralCandidateType(
6408 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006409 CandidateTypes(CandidateTypes),
6410 CandidateSet(CandidateSet) {
6411 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006412 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006413 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006414 assert(getArithmeticType(LastPromotedIntegralType - 1)
6415 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006416 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006417 assert(getArithmeticType(FirstPromotedArithmeticType)
6418 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006419 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006420 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6421 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006422 "Invalid last promoted arithmetic type");
6423 }
6424
6425 // C++ [over.built]p3:
6426 //
6427 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6428 // is either volatile or empty, there exist candidate operator
6429 // functions of the form
6430 //
6431 // VQ T& operator++(VQ T&);
6432 // T operator++(VQ T&, int);
6433 //
6434 // C++ [over.built]p4:
6435 //
6436 // For every pair (T, VQ), where T is an arithmetic type other
6437 // than bool, and VQ is either volatile or empty, there exist
6438 // candidate operator functions of the form
6439 //
6440 // VQ T& operator--(VQ T&);
6441 // T operator--(VQ T&, int);
6442 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006443 if (!HasArithmeticOrEnumeralCandidateType)
6444 return;
6445
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006446 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6447 Arith < NumArithmeticTypes; ++Arith) {
6448 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006449 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006450 VisibleTypeConversionsQuals.hasVolatile());
6451 }
6452 }
6453
6454 // C++ [over.built]p5:
6455 //
6456 // For every pair (T, VQ), where T is a cv-qualified or
6457 // cv-unqualified object type, and VQ is either volatile or
6458 // empty, there exist candidate operator functions of the form
6459 //
6460 // T*VQ& operator++(T*VQ&);
6461 // T*VQ& operator--(T*VQ&);
6462 // T* operator++(T*VQ&, int);
6463 // T* operator--(T*VQ&, int);
6464 void addPlusPlusMinusMinusPointerOverloads() {
6465 for (BuiltinCandidateTypeSet::iterator
6466 Ptr = CandidateTypes[0].pointer_begin(),
6467 PtrEnd = CandidateTypes[0].pointer_end();
6468 Ptr != PtrEnd; ++Ptr) {
6469 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006470 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006471 continue;
6472
6473 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6474 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6475 VisibleTypeConversionsQuals.hasVolatile()));
6476 }
6477 }
6478
6479 // C++ [over.built]p6:
6480 // For every cv-qualified or cv-unqualified object type T, there
6481 // exist candidate operator functions of the form
6482 //
6483 // T& operator*(T*);
6484 //
6485 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006486 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006487 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006488 // T& operator*(T*);
6489 void addUnaryStarPointerOverloads() {
6490 for (BuiltinCandidateTypeSet::iterator
6491 Ptr = CandidateTypes[0].pointer_begin(),
6492 PtrEnd = CandidateTypes[0].pointer_end();
6493 Ptr != PtrEnd; ++Ptr) {
6494 QualType ParamTy = *Ptr;
6495 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006496 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6497 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006498
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006499 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6500 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6501 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006502
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006503 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6504 &ParamTy, Args, 1, CandidateSet);
6505 }
6506 }
6507
6508 // C++ [over.built]p9:
6509 // For every promoted arithmetic type T, there exist candidate
6510 // operator functions of the form
6511 //
6512 // T operator+(T);
6513 // T operator-(T);
6514 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006515 if (!HasArithmeticOrEnumeralCandidateType)
6516 return;
6517
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006518 for (unsigned Arith = FirstPromotedArithmeticType;
6519 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006520 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006521 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6522 }
6523
6524 // Extension: We also add these operators for vector types.
6525 for (BuiltinCandidateTypeSet::iterator
6526 Vec = CandidateTypes[0].vector_begin(),
6527 VecEnd = CandidateTypes[0].vector_end();
6528 Vec != VecEnd; ++Vec) {
6529 QualType VecTy = *Vec;
6530 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6531 }
6532 }
6533
6534 // C++ [over.built]p8:
6535 // For every type T, there exist candidate operator functions of
6536 // the form
6537 //
6538 // T* operator+(T*);
6539 void addUnaryPlusPointerOverloads() {
6540 for (BuiltinCandidateTypeSet::iterator
6541 Ptr = CandidateTypes[0].pointer_begin(),
6542 PtrEnd = CandidateTypes[0].pointer_end();
6543 Ptr != PtrEnd; ++Ptr) {
6544 QualType ParamTy = *Ptr;
6545 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6546 }
6547 }
6548
6549 // C++ [over.built]p10:
6550 // For every promoted integral type T, there exist candidate
6551 // operator functions of the form
6552 //
6553 // T operator~(T);
6554 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006555 if (!HasArithmeticOrEnumeralCandidateType)
6556 return;
6557
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006558 for (unsigned Int = FirstPromotedIntegralType;
6559 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006560 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006561 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6562 }
6563
6564 // Extension: We also add this operator for vector types.
6565 for (BuiltinCandidateTypeSet::iterator
6566 Vec = CandidateTypes[0].vector_begin(),
6567 VecEnd = CandidateTypes[0].vector_end();
6568 Vec != VecEnd; ++Vec) {
6569 QualType VecTy = *Vec;
6570 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6571 }
6572 }
6573
6574 // C++ [over.match.oper]p16:
6575 // For every pointer to member type T, there exist candidate operator
6576 // functions of the form
6577 //
6578 // bool operator==(T,T);
6579 // bool operator!=(T,T);
6580 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6581 /// Set of (canonical) types that we've already handled.
6582 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6583
6584 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6585 for (BuiltinCandidateTypeSet::iterator
6586 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6587 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6588 MemPtr != MemPtrEnd;
6589 ++MemPtr) {
6590 // Don't add the same builtin candidate twice.
6591 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6592 continue;
6593
6594 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6595 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6596 CandidateSet);
6597 }
6598 }
6599 }
6600
6601 // C++ [over.built]p15:
6602 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006603 // For every T, where T is an enumeration type, a pointer type, or
6604 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006605 //
6606 // bool operator<(T, T);
6607 // bool operator>(T, T);
6608 // bool operator<=(T, T);
6609 // bool operator>=(T, T);
6610 // bool operator==(T, T);
6611 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006612 void addRelationalPointerOrEnumeralOverloads() {
6613 // C++ [over.built]p1:
6614 // If there is a user-written candidate with the same name and parameter
6615 // types as a built-in candidate operator function, the built-in operator
6616 // function is hidden and is not included in the set of candidate
6617 // functions.
6618 //
6619 // The text is actually in a note, but if we don't implement it then we end
6620 // up with ambiguities when the user provides an overloaded operator for
6621 // an enumeration type. Note that only enumeration types have this problem,
6622 // so we track which enumeration types we've seen operators for. Also, the
6623 // only other overloaded operator with enumeration argumenst, operator=,
6624 // cannot be overloaded for enumeration types, so this is the only place
6625 // where we must suppress candidates like this.
6626 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6627 UserDefinedBinaryOperators;
6628
6629 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6630 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6631 CandidateTypes[ArgIdx].enumeration_end()) {
6632 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6633 CEnd = CandidateSet.end();
6634 C != CEnd; ++C) {
6635 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6636 continue;
6637
6638 QualType FirstParamType =
6639 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6640 QualType SecondParamType =
6641 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6642
6643 // Skip if either parameter isn't of enumeral type.
6644 if (!FirstParamType->isEnumeralType() ||
6645 !SecondParamType->isEnumeralType())
6646 continue;
6647
6648 // Add this operator to the set of known user-defined operators.
6649 UserDefinedBinaryOperators.insert(
6650 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6651 S.Context.getCanonicalType(SecondParamType)));
6652 }
6653 }
6654 }
6655
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006656 /// Set of (canonical) types that we've already handled.
6657 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6658
6659 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6660 for (BuiltinCandidateTypeSet::iterator
6661 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6662 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6663 Ptr != PtrEnd; ++Ptr) {
6664 // Don't add the same builtin candidate twice.
6665 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6666 continue;
6667
6668 QualType ParamTypes[2] = { *Ptr, *Ptr };
6669 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6670 CandidateSet);
6671 }
6672 for (BuiltinCandidateTypeSet::iterator
6673 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6674 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6675 Enum != EnumEnd; ++Enum) {
6676 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6677
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006678 // Don't add the same builtin candidate twice, or if a user defined
6679 // candidate exists.
6680 if (!AddedTypes.insert(CanonType) ||
6681 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6682 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006683 continue;
6684
6685 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006686 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6687 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006688 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006689
6690 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6691 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6692 if (AddedTypes.insert(NullPtrTy) &&
6693 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6694 NullPtrTy))) {
6695 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6696 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6697 CandidateSet);
6698 }
6699 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006700 }
6701 }
6702
6703 // C++ [over.built]p13:
6704 //
6705 // For every cv-qualified or cv-unqualified object type T
6706 // there exist candidate operator functions of the form
6707 //
6708 // T* operator+(T*, ptrdiff_t);
6709 // T& operator[](T*, ptrdiff_t); [BELOW]
6710 // T* operator-(T*, ptrdiff_t);
6711 // T* operator+(ptrdiff_t, T*);
6712 // T& operator[](ptrdiff_t, T*); [BELOW]
6713 //
6714 // C++ [over.built]p14:
6715 //
6716 // For every T, where T is a pointer to object type, there
6717 // exist candidate operator functions of the form
6718 //
6719 // ptrdiff_t operator-(T, T);
6720 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6721 /// Set of (canonical) types that we've already handled.
6722 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6723
6724 for (int Arg = 0; Arg < 2; ++Arg) {
6725 QualType AsymetricParamTypes[2] = {
6726 S.Context.getPointerDiffType(),
6727 S.Context.getPointerDiffType(),
6728 };
6729 for (BuiltinCandidateTypeSet::iterator
6730 Ptr = CandidateTypes[Arg].pointer_begin(),
6731 PtrEnd = CandidateTypes[Arg].pointer_end();
6732 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006733 QualType PointeeTy = (*Ptr)->getPointeeType();
6734 if (!PointeeTy->isObjectType())
6735 continue;
6736
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006737 AsymetricParamTypes[Arg] = *Ptr;
6738 if (Arg == 0 || Op == OO_Plus) {
6739 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6740 // T* operator+(ptrdiff_t, T*);
6741 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6742 CandidateSet);
6743 }
6744 if (Op == OO_Minus) {
6745 // ptrdiff_t operator-(T, T);
6746 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6747 continue;
6748
6749 QualType ParamTypes[2] = { *Ptr, *Ptr };
6750 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6751 Args, 2, CandidateSet);
6752 }
6753 }
6754 }
6755 }
6756
6757 // C++ [over.built]p12:
6758 //
6759 // For every pair of promoted arithmetic types L and R, there
6760 // exist candidate operator functions of the form
6761 //
6762 // LR operator*(L, R);
6763 // LR operator/(L, R);
6764 // LR operator+(L, R);
6765 // LR operator-(L, R);
6766 // bool operator<(L, R);
6767 // bool operator>(L, R);
6768 // bool operator<=(L, R);
6769 // bool operator>=(L, R);
6770 // bool operator==(L, R);
6771 // bool operator!=(L, R);
6772 //
6773 // where LR is the result of the usual arithmetic conversions
6774 // between types L and R.
6775 //
6776 // C++ [over.built]p24:
6777 //
6778 // For every pair of promoted arithmetic types L and R, there exist
6779 // candidate operator functions of the form
6780 //
6781 // LR operator?(bool, L, R);
6782 //
6783 // where LR is the result of the usual arithmetic conversions
6784 // between types L and R.
6785 // Our candidates ignore the first parameter.
6786 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006787 if (!HasArithmeticOrEnumeralCandidateType)
6788 return;
6789
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006790 for (unsigned Left = FirstPromotedArithmeticType;
6791 Left < LastPromotedArithmeticType; ++Left) {
6792 for (unsigned Right = FirstPromotedArithmeticType;
6793 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006794 QualType LandR[2] = { getArithmeticType(Left),
6795 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006796 QualType Result =
6797 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006798 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006799 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6800 }
6801 }
6802
6803 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6804 // conditional operator for vector types.
6805 for (BuiltinCandidateTypeSet::iterator
6806 Vec1 = CandidateTypes[0].vector_begin(),
6807 Vec1End = CandidateTypes[0].vector_end();
6808 Vec1 != Vec1End; ++Vec1) {
6809 for (BuiltinCandidateTypeSet::iterator
6810 Vec2 = CandidateTypes[1].vector_begin(),
6811 Vec2End = CandidateTypes[1].vector_end();
6812 Vec2 != Vec2End; ++Vec2) {
6813 QualType LandR[2] = { *Vec1, *Vec2 };
6814 QualType Result = S.Context.BoolTy;
6815 if (!isComparison) {
6816 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6817 Result = *Vec1;
6818 else
6819 Result = *Vec2;
6820 }
6821
6822 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6823 }
6824 }
6825 }
6826
6827 // C++ [over.built]p17:
6828 //
6829 // For every pair of promoted integral types L and R, there
6830 // exist candidate operator functions of the form
6831 //
6832 // LR operator%(L, R);
6833 // LR operator&(L, R);
6834 // LR operator^(L, R);
6835 // LR operator|(L, R);
6836 // L operator<<(L, R);
6837 // L operator>>(L, R);
6838 //
6839 // where LR is the result of the usual arithmetic conversions
6840 // between types L and R.
6841 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006842 if (!HasArithmeticOrEnumeralCandidateType)
6843 return;
6844
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006845 for (unsigned Left = FirstPromotedIntegralType;
6846 Left < LastPromotedIntegralType; ++Left) {
6847 for (unsigned Right = FirstPromotedIntegralType;
6848 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006849 QualType LandR[2] = { getArithmeticType(Left),
6850 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006851 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6852 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006853 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006854 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6855 }
6856 }
6857 }
6858
6859 // C++ [over.built]p20:
6860 //
6861 // For every pair (T, VQ), where T is an enumeration or
6862 // pointer to member type and VQ is either volatile or
6863 // empty, there exist candidate operator functions of the form
6864 //
6865 // VQ T& operator=(VQ T&, T);
6866 void addAssignmentMemberPointerOrEnumeralOverloads() {
6867 /// Set of (canonical) types that we've already handled.
6868 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6869
6870 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6871 for (BuiltinCandidateTypeSet::iterator
6872 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6873 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6874 Enum != EnumEnd; ++Enum) {
6875 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6876 continue;
6877
6878 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6879 CandidateSet);
6880 }
6881
6882 for (BuiltinCandidateTypeSet::iterator
6883 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6884 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6885 MemPtr != MemPtrEnd; ++MemPtr) {
6886 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6887 continue;
6888
6889 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6890 CandidateSet);
6891 }
6892 }
6893 }
6894
6895 // C++ [over.built]p19:
6896 //
6897 // For every pair (T, VQ), where T is any type and VQ is either
6898 // volatile or empty, there exist candidate operator functions
6899 // of the form
6900 //
6901 // T*VQ& operator=(T*VQ&, T*);
6902 //
6903 // C++ [over.built]p21:
6904 //
6905 // For every pair (T, VQ), where T is a cv-qualified or
6906 // cv-unqualified object type and VQ is either volatile or
6907 // empty, there exist candidate operator functions of the form
6908 //
6909 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6910 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6911 void addAssignmentPointerOverloads(bool isEqualOp) {
6912 /// Set of (canonical) types that we've already handled.
6913 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6914
6915 for (BuiltinCandidateTypeSet::iterator
6916 Ptr = CandidateTypes[0].pointer_begin(),
6917 PtrEnd = CandidateTypes[0].pointer_end();
6918 Ptr != PtrEnd; ++Ptr) {
6919 // If this is operator=, keep track of the builtin candidates we added.
6920 if (isEqualOp)
6921 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006922 else if (!(*Ptr)->getPointeeType()->isObjectType())
6923 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006924
6925 // non-volatile version
6926 QualType ParamTypes[2] = {
6927 S.Context.getLValueReferenceType(*Ptr),
6928 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6929 };
6930 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6931 /*IsAssigmentOperator=*/ isEqualOp);
6932
6933 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6934 VisibleTypeConversionsQuals.hasVolatile()) {
6935 // volatile version
6936 ParamTypes[0] =
6937 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6938 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6939 /*IsAssigmentOperator=*/isEqualOp);
6940 }
6941 }
6942
6943 if (isEqualOp) {
6944 for (BuiltinCandidateTypeSet::iterator
6945 Ptr = CandidateTypes[1].pointer_begin(),
6946 PtrEnd = CandidateTypes[1].pointer_end();
6947 Ptr != PtrEnd; ++Ptr) {
6948 // Make sure we don't add the same candidate twice.
6949 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6950 continue;
6951
Chandler Carruth6df868e2010-12-12 08:17:55 +00006952 QualType ParamTypes[2] = {
6953 S.Context.getLValueReferenceType(*Ptr),
6954 *Ptr,
6955 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006956
6957 // non-volatile version
6958 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6959 /*IsAssigmentOperator=*/true);
6960
6961 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6962 VisibleTypeConversionsQuals.hasVolatile()) {
6963 // volatile version
6964 ParamTypes[0] =
6965 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00006966 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6967 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006968 }
6969 }
6970 }
6971 }
6972
6973 // C++ [over.built]p18:
6974 //
6975 // For every triple (L, VQ, R), where L is an arithmetic type,
6976 // VQ is either volatile or empty, and R is a promoted
6977 // arithmetic type, there exist candidate operator functions of
6978 // the form
6979 //
6980 // VQ L& operator=(VQ L&, R);
6981 // VQ L& operator*=(VQ L&, R);
6982 // VQ L& operator/=(VQ L&, R);
6983 // VQ L& operator+=(VQ L&, R);
6984 // VQ L& operator-=(VQ L&, R);
6985 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006986 if (!HasArithmeticOrEnumeralCandidateType)
6987 return;
6988
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006989 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6990 for (unsigned Right = FirstPromotedArithmeticType;
6991 Right < LastPromotedArithmeticType; ++Right) {
6992 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006993 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006994
6995 // Add this built-in operator as a candidate (VQ is empty).
6996 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006997 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006998 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6999 /*IsAssigmentOperator=*/isEqualOp);
7000
7001 // Add this built-in operator as a candidate (VQ is 'volatile').
7002 if (VisibleTypeConversionsQuals.hasVolatile()) {
7003 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007004 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007005 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007006 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7007 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007008 /*IsAssigmentOperator=*/isEqualOp);
7009 }
7010 }
7011 }
7012
7013 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7014 for (BuiltinCandidateTypeSet::iterator
7015 Vec1 = CandidateTypes[0].vector_begin(),
7016 Vec1End = CandidateTypes[0].vector_end();
7017 Vec1 != Vec1End; ++Vec1) {
7018 for (BuiltinCandidateTypeSet::iterator
7019 Vec2 = CandidateTypes[1].vector_begin(),
7020 Vec2End = CandidateTypes[1].vector_end();
7021 Vec2 != Vec2End; ++Vec2) {
7022 QualType ParamTypes[2];
7023 ParamTypes[1] = *Vec2;
7024 // Add this built-in operator as a candidate (VQ is empty).
7025 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7026 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7027 /*IsAssigmentOperator=*/isEqualOp);
7028
7029 // Add this built-in operator as a candidate (VQ is 'volatile').
7030 if (VisibleTypeConversionsQuals.hasVolatile()) {
7031 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7032 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007033 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7034 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007035 /*IsAssigmentOperator=*/isEqualOp);
7036 }
7037 }
7038 }
7039 }
7040
7041 // C++ [over.built]p22:
7042 //
7043 // For every triple (L, VQ, R), where L is an integral type, VQ
7044 // is either volatile or empty, and R is a promoted integral
7045 // type, there exist candidate operator functions of the form
7046 //
7047 // VQ L& operator%=(VQ L&, R);
7048 // VQ L& operator<<=(VQ L&, R);
7049 // VQ L& operator>>=(VQ L&, R);
7050 // VQ L& operator&=(VQ L&, R);
7051 // VQ L& operator^=(VQ L&, R);
7052 // VQ L& operator|=(VQ L&, R);
7053 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007054 if (!HasArithmeticOrEnumeralCandidateType)
7055 return;
7056
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007057 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7058 for (unsigned Right = FirstPromotedIntegralType;
7059 Right < LastPromotedIntegralType; ++Right) {
7060 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007061 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007062
7063 // Add this built-in operator as a candidate (VQ is empty).
7064 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007065 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007066 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7067 if (VisibleTypeConversionsQuals.hasVolatile()) {
7068 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007069 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007070 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7071 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7072 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7073 CandidateSet);
7074 }
7075 }
7076 }
7077 }
7078
7079 // C++ [over.operator]p23:
7080 //
7081 // There also exist candidate operator functions of the form
7082 //
7083 // bool operator!(bool);
7084 // bool operator&&(bool, bool);
7085 // bool operator||(bool, bool);
7086 void addExclaimOverload() {
7087 QualType ParamTy = S.Context.BoolTy;
7088 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7089 /*IsAssignmentOperator=*/false,
7090 /*NumContextualBoolArguments=*/1);
7091 }
7092 void addAmpAmpOrPipePipeOverload() {
7093 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7094 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7095 /*IsAssignmentOperator=*/false,
7096 /*NumContextualBoolArguments=*/2);
7097 }
7098
7099 // C++ [over.built]p13:
7100 //
7101 // For every cv-qualified or cv-unqualified object type T there
7102 // exist candidate operator functions of the form
7103 //
7104 // T* operator+(T*, ptrdiff_t); [ABOVE]
7105 // T& operator[](T*, ptrdiff_t);
7106 // T* operator-(T*, ptrdiff_t); [ABOVE]
7107 // T* operator+(ptrdiff_t, T*); [ABOVE]
7108 // T& operator[](ptrdiff_t, T*);
7109 void addSubscriptOverloads() {
7110 for (BuiltinCandidateTypeSet::iterator
7111 Ptr = CandidateTypes[0].pointer_begin(),
7112 PtrEnd = CandidateTypes[0].pointer_end();
7113 Ptr != PtrEnd; ++Ptr) {
7114 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7115 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007116 if (!PointeeType->isObjectType())
7117 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007118
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007119 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7120
7121 // T& operator[](T*, ptrdiff_t)
7122 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7123 }
7124
7125 for (BuiltinCandidateTypeSet::iterator
7126 Ptr = CandidateTypes[1].pointer_begin(),
7127 PtrEnd = CandidateTypes[1].pointer_end();
7128 Ptr != PtrEnd; ++Ptr) {
7129 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7130 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007131 if (!PointeeType->isObjectType())
7132 continue;
7133
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007134 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7135
7136 // T& operator[](ptrdiff_t, T*)
7137 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7138 }
7139 }
7140
7141 // C++ [over.built]p11:
7142 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7143 // C1 is the same type as C2 or is a derived class of C2, T is an object
7144 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7145 // there exist candidate operator functions of the form
7146 //
7147 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7148 //
7149 // where CV12 is the union of CV1 and CV2.
7150 void addArrowStarOverloads() {
7151 for (BuiltinCandidateTypeSet::iterator
7152 Ptr = CandidateTypes[0].pointer_begin(),
7153 PtrEnd = CandidateTypes[0].pointer_end();
7154 Ptr != PtrEnd; ++Ptr) {
7155 QualType C1Ty = (*Ptr);
7156 QualType C1;
7157 QualifierCollector Q1;
7158 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7159 if (!isa<RecordType>(C1))
7160 continue;
7161 // heuristic to reduce number of builtin candidates in the set.
7162 // Add volatile/restrict version only if there are conversions to a
7163 // volatile/restrict type.
7164 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7165 continue;
7166 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7167 continue;
7168 for (BuiltinCandidateTypeSet::iterator
7169 MemPtr = CandidateTypes[1].member_pointer_begin(),
7170 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7171 MemPtr != MemPtrEnd; ++MemPtr) {
7172 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7173 QualType C2 = QualType(mptr->getClass(), 0);
7174 C2 = C2.getUnqualifiedType();
7175 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7176 break;
7177 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7178 // build CV12 T&
7179 QualType T = mptr->getPointeeType();
7180 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7181 T.isVolatileQualified())
7182 continue;
7183 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7184 T.isRestrictQualified())
7185 continue;
7186 T = Q1.apply(S.Context, T);
7187 QualType ResultTy = S.Context.getLValueReferenceType(T);
7188 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7189 }
7190 }
7191 }
7192
7193 // Note that we don't consider the first argument, since it has been
7194 // contextually converted to bool long ago. The candidates below are
7195 // therefore added as binary.
7196 //
7197 // C++ [over.built]p25:
7198 // For every type T, where T is a pointer, pointer-to-member, or scoped
7199 // enumeration type, there exist candidate operator functions of the form
7200 //
7201 // T operator?(bool, T, T);
7202 //
7203 void addConditionalOperatorOverloads() {
7204 /// Set of (canonical) types that we've already handled.
7205 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7206
7207 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7208 for (BuiltinCandidateTypeSet::iterator
7209 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7210 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7211 Ptr != PtrEnd; ++Ptr) {
7212 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7213 continue;
7214
7215 QualType ParamTypes[2] = { *Ptr, *Ptr };
7216 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7217 }
7218
7219 for (BuiltinCandidateTypeSet::iterator
7220 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7221 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7222 MemPtr != MemPtrEnd; ++MemPtr) {
7223 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7224 continue;
7225
7226 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7227 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7228 }
7229
7230 if (S.getLangOptions().CPlusPlus0x) {
7231 for (BuiltinCandidateTypeSet::iterator
7232 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7233 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7234 Enum != EnumEnd; ++Enum) {
7235 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7236 continue;
7237
7238 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7239 continue;
7240
7241 QualType ParamTypes[2] = { *Enum, *Enum };
7242 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7243 }
7244 }
7245 }
7246 }
7247};
7248
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007249} // end anonymous namespace
7250
7251/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7252/// operator overloads to the candidate set (C++ [over.built]), based
7253/// on the operator @p Op and the arguments given. For example, if the
7254/// operator is a binary '+', this routine might add "int
7255/// operator+(int, int)" to cover integer addition.
7256void
7257Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7258 SourceLocation OpLoc,
7259 Expr **Args, unsigned NumArgs,
7260 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007261 // Find all of the types that the arguments can convert to, but only
7262 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007263 // that make use of these types. Also record whether we encounter non-record
7264 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007265 Qualifiers VisibleTypeConversionsQuals;
7266 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007267 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7268 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007269
7270 bool HasNonRecordCandidateType = false;
7271 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007272 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007273 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7274 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7275 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7276 OpLoc,
7277 true,
7278 (Op == OO_Exclaim ||
7279 Op == OO_AmpAmp ||
7280 Op == OO_PipePipe),
7281 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007282 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7283 CandidateTypes[ArgIdx].hasNonRecordTypes();
7284 HasArithmeticOrEnumeralCandidateType =
7285 HasArithmeticOrEnumeralCandidateType ||
7286 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007287 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007288
Chandler Carruth6a577462010-12-13 01:44:01 +00007289 // Exit early when no non-record types have been added to the candidate set
7290 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007291 //
7292 // We can't exit early for !, ||, or &&, since there we have always have
7293 // 'bool' overloads.
7294 if (!HasNonRecordCandidateType &&
7295 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007296 return;
7297
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007298 // Setup an object to manage the common state for building overloads.
7299 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7300 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007301 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007302 CandidateTypes, CandidateSet);
7303
7304 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007305 switch (Op) {
7306 case OO_None:
7307 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007308 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007309
Chandler Carruthabb71842010-12-12 08:51:33 +00007310 case OO_New:
7311 case OO_Delete:
7312 case OO_Array_New:
7313 case OO_Array_Delete:
7314 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007315 llvm_unreachable(
7316 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007317
7318 case OO_Comma:
7319 case OO_Arrow:
7320 // C++ [over.match.oper]p3:
7321 // -- For the operator ',', the unary operator '&', or the
7322 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007323 break;
7324
7325 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007326 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007327 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007328 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007329
7330 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007331 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007332 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007333 } else {
7334 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7335 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7336 }
Douglas Gregor74253732008-11-19 15:42:04 +00007337 break;
7338
Chandler Carruthabb71842010-12-12 08:51:33 +00007339 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007340 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007341 OpBuilder.addUnaryStarPointerOverloads();
7342 else
7343 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7344 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007345
Chandler Carruthabb71842010-12-12 08:51:33 +00007346 case OO_Slash:
7347 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007348 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007349
7350 case OO_PlusPlus:
7351 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007352 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7353 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007354 break;
7355
Douglas Gregor19b7b152009-08-24 13:43:27 +00007356 case OO_EqualEqual:
7357 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007358 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007359 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007360
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007361 case OO_Less:
7362 case OO_Greater:
7363 case OO_LessEqual:
7364 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007365 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007366 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7367 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007368
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007369 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007370 case OO_Caret:
7371 case OO_Pipe:
7372 case OO_LessLess:
7373 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007374 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007375 break;
7376
Chandler Carruthabb71842010-12-12 08:51:33 +00007377 case OO_Amp: // '&' is either unary or binary
7378 if (NumArgs == 1)
7379 // C++ [over.match.oper]p3:
7380 // -- For the operator ',', the unary operator '&', or the
7381 // operator '->', the built-in candidates set is empty.
7382 break;
7383
7384 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7385 break;
7386
7387 case OO_Tilde:
7388 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7389 break;
7390
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007391 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007392 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007393 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007394
7395 case OO_PlusEqual:
7396 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007397 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007398 // Fall through.
7399
7400 case OO_StarEqual:
7401 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007402 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007403 break;
7404
7405 case OO_PercentEqual:
7406 case OO_LessLessEqual:
7407 case OO_GreaterGreaterEqual:
7408 case OO_AmpEqual:
7409 case OO_CaretEqual:
7410 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007411 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007412 break;
7413
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007414 case OO_Exclaim:
7415 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007416 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007417
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007418 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007419 case OO_PipePipe:
7420 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007421 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007422
7423 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007424 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007425 break;
7426
7427 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007428 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007429 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007430
7431 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007432 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007433 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7434 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007435 }
7436}
7437
Douglas Gregorfa047642009-02-04 00:32:51 +00007438/// \brief Add function candidates found via argument-dependent lookup
7439/// to the set of overloading candidates.
7440///
7441/// This routine performs argument-dependent name lookup based on the
7442/// given function name (which may also be an operator name) and adds
7443/// all of the overload candidates found by ADL to the overload
7444/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007445void
Douglas Gregorfa047642009-02-04 00:32:51 +00007446Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00007447 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00007448 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00007449 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007450 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007451 bool PartialOverloading,
7452 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007453 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007454
John McCalla113e722010-01-26 06:04:06 +00007455 // FIXME: This approach for uniquing ADL results (and removing
7456 // redundant candidates from the set) relies on pointer-equality,
7457 // which means we need to key off the canonical decl. However,
7458 // always going back to the canonical decl might not get us the
7459 // right set of default arguments. What default arguments are
7460 // we supposed to consider on ADL candidates, anyway?
7461
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007462 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00007463 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
7464 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007465
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007466 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007467 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7468 CandEnd = CandidateSet.end();
7469 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007470 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007471 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007472 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007473 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007474 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007475
7476 // For each of the ADL candidates we found, add it to the overload
7477 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007478 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007479 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007480 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007481 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007482 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007483
John McCall9aa472c2010-03-19 07:35:19 +00007484 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007485 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007486 } else
John McCall6e266892010-01-26 03:27:55 +00007487 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007488 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00007489 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007490 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007491}
7492
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007493/// isBetterOverloadCandidate - Determines whether the first overload
7494/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007495bool
John McCall120d63c2010-08-24 20:38:10 +00007496isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007497 const OverloadCandidate &Cand1,
7498 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007499 SourceLocation Loc,
7500 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007501 // Define viable functions to be better candidates than non-viable
7502 // functions.
7503 if (!Cand2.Viable)
7504 return Cand1.Viable;
7505 else if (!Cand1.Viable)
7506 return false;
7507
Douglas Gregor88a35142008-12-22 05:46:06 +00007508 // C++ [over.match.best]p1:
7509 //
7510 // -- if F is a static member function, ICS1(F) is defined such
7511 // that ICS1(F) is neither better nor worse than ICS1(G) for
7512 // any function G, and, symmetrically, ICS1(G) is neither
7513 // better nor worse than ICS1(F).
7514 unsigned StartArg = 0;
7515 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7516 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007517
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007518 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007519 // A viable function F1 is defined to be a better function than another
7520 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007521 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007522 unsigned NumArgs = Cand1.NumConversions;
7523 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007524 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007525 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007526 switch (CompareImplicitConversionSequences(S,
7527 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007528 Cand2.Conversions[ArgIdx])) {
7529 case ImplicitConversionSequence::Better:
7530 // Cand1 has a better conversion sequence.
7531 HasBetterConversion = true;
7532 break;
7533
7534 case ImplicitConversionSequence::Worse:
7535 // Cand1 can't be better than Cand2.
7536 return false;
7537
7538 case ImplicitConversionSequence::Indistinguishable:
7539 // Do nothing.
7540 break;
7541 }
7542 }
7543
Mike Stump1eb44332009-09-09 15:08:12 +00007544 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007545 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007546 if (HasBetterConversion)
7547 return true;
7548
Mike Stump1eb44332009-09-09 15:08:12 +00007549 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007550 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007551 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007552 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7553 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007554
7555 // -- F1 and F2 are function template specializations, and the function
7556 // template for F1 is more specialized than the template for F2
7557 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007558 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007559 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007560 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007561 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007562 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7563 Cand2.Function->getPrimaryTemplate(),
7564 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007565 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007566 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007567 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007568 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007570
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007571 // -- the context is an initialization by user-defined conversion
7572 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7573 // from the return type of F1 to the destination type (i.e.,
7574 // the type of the entity being initialized) is a better
7575 // conversion sequence than the standard conversion sequence
7576 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007577 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007578 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007579 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007580 // First check whether we prefer one of the conversion functions over the
7581 // other. This only distinguishes the results in non-standard, extension
7582 // cases such as the conversion from a lambda closure type to a function
7583 // pointer or block.
7584 ImplicitConversionSequence::CompareKind FuncResult
7585 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7586 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7587 return FuncResult;
7588
John McCall120d63c2010-08-24 20:38:10 +00007589 switch (CompareStandardConversionSequences(S,
7590 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007591 Cand2.FinalConversion)) {
7592 case ImplicitConversionSequence::Better:
7593 // Cand1 has a better conversion sequence.
7594 return true;
7595
7596 case ImplicitConversionSequence::Worse:
7597 // Cand1 can't be better than Cand2.
7598 return false;
7599
7600 case ImplicitConversionSequence::Indistinguishable:
7601 // Do nothing
7602 break;
7603 }
7604 }
7605
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007606 return false;
7607}
7608
Mike Stump1eb44332009-09-09 15:08:12 +00007609/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007610/// within an overload candidate set.
7611///
7612/// \param CandidateSet the set of candidate functions.
7613///
7614/// \param Loc the location of the function name (or operator symbol) for
7615/// which overload resolution occurs.
7616///
Mike Stump1eb44332009-09-09 15:08:12 +00007617/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007618/// function, Best points to the candidate function found.
7619///
7620/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007621OverloadingResult
7622OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007623 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007624 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007625 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007626 Best = end();
7627 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7628 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007629 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007630 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007631 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007632 }
7633
7634 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007635 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007636 return OR_No_Viable_Function;
7637
7638 // Make sure that this function is better than every other viable
7639 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007640 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007641 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007642 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007643 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007644 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007645 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007646 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007647 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007648 }
Mike Stump1eb44332009-09-09 15:08:12 +00007649
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007650 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007651 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007652 (Best->Function->isDeleted() ||
7653 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007654 return OR_Deleted;
7655
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007656 return OR_Success;
7657}
7658
John McCall3c80f572010-01-12 02:15:36 +00007659namespace {
7660
7661enum OverloadCandidateKind {
7662 oc_function,
7663 oc_method,
7664 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007665 oc_function_template,
7666 oc_method_template,
7667 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007668 oc_implicit_default_constructor,
7669 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007670 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007671 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007672 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007673 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007674};
7675
John McCall220ccbf2010-01-13 00:25:19 +00007676OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7677 FunctionDecl *Fn,
7678 std::string &Description) {
7679 bool isTemplate = false;
7680
7681 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7682 isTemplate = true;
7683 Description = S.getTemplateArgumentBindingsText(
7684 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7685 }
John McCallb1622a12010-01-06 09:43:14 +00007686
7687 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007688 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007689 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007690
Sebastian Redlf677ea32011-02-05 19:23:19 +00007691 if (Ctor->getInheritedConstructor())
7692 return oc_implicit_inherited_constructor;
7693
Sean Hunt82713172011-05-25 23:16:36 +00007694 if (Ctor->isDefaultConstructor())
7695 return oc_implicit_default_constructor;
7696
7697 if (Ctor->isMoveConstructor())
7698 return oc_implicit_move_constructor;
7699
7700 assert(Ctor->isCopyConstructor() &&
7701 "unexpected sort of implicit constructor");
7702 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007703 }
7704
7705 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7706 // This actually gets spelled 'candidate function' for now, but
7707 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007708 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007709 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007710
Sean Hunt82713172011-05-25 23:16:36 +00007711 if (Meth->isMoveAssignmentOperator())
7712 return oc_implicit_move_assignment;
7713
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007714 if (Meth->isCopyAssignmentOperator())
7715 return oc_implicit_copy_assignment;
7716
7717 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7718 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007719 }
7720
John McCall220ccbf2010-01-13 00:25:19 +00007721 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007722}
7723
Sebastian Redlf677ea32011-02-05 19:23:19 +00007724void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7725 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7726 if (!Ctor) return;
7727
7728 Ctor = Ctor->getInheritedConstructor();
7729 if (!Ctor) return;
7730
7731 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7732}
7733
John McCall3c80f572010-01-12 02:15:36 +00007734} // end anonymous namespace
7735
7736// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007737void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007738 std::string FnDesc;
7739 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007740 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7741 << (unsigned) K << FnDesc;
7742 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7743 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007744 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007745}
7746
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007747//Notes the location of all overload candidates designated through
7748// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007749void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007750 assert(OverloadedExpr->getType() == Context.OverloadTy);
7751
7752 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7753 OverloadExpr *OvlExpr = Ovl.Expression;
7754
7755 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7756 IEnd = OvlExpr->decls_end();
7757 I != IEnd; ++I) {
7758 if (FunctionTemplateDecl *FunTmpl =
7759 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007760 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007761 } else if (FunctionDecl *Fun
7762 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007763 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007764 }
7765 }
7766}
7767
John McCall1d318332010-01-12 00:44:57 +00007768/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7769/// "lead" diagnostic; it will be given two arguments, the source and
7770/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007771void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7772 Sema &S,
7773 SourceLocation CaretLoc,
7774 const PartialDiagnostic &PDiag) const {
7775 S.Diag(CaretLoc, PDiag)
7776 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007777 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007778 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7779 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007780 }
John McCall81201622010-01-08 04:41:39 +00007781}
7782
John McCall1d318332010-01-12 00:44:57 +00007783namespace {
7784
John McCalladbb8f82010-01-13 09:16:55 +00007785void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7786 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7787 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007788 assert(Cand->Function && "for now, candidate must be a function");
7789 FunctionDecl *Fn = Cand->Function;
7790
7791 // There's a conversion slot for the object argument if this is a
7792 // non-constructor method. Note that 'I' corresponds the
7793 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007794 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007795 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007796 if (I == 0)
7797 isObjectArgument = true;
7798 else
7799 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007800 }
7801
John McCall220ccbf2010-01-13 00:25:19 +00007802 std::string FnDesc;
7803 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7804
John McCalladbb8f82010-01-13 09:16:55 +00007805 Expr *FromExpr = Conv.Bad.FromExpr;
7806 QualType FromTy = Conv.Bad.getFromType();
7807 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007808
John McCall5920dbb2010-02-02 02:42:52 +00007809 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007810 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007811 Expr *E = FromExpr->IgnoreParens();
7812 if (isa<UnaryOperator>(E))
7813 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007814 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007815
7816 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7817 << (unsigned) FnKind << FnDesc
7818 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7819 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007820 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007821 return;
7822 }
7823
John McCall258b2032010-01-23 08:10:49 +00007824 // Do some hand-waving analysis to see if the non-viability is due
7825 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007826 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7827 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7828 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7829 CToTy = RT->getPointeeType();
7830 else {
7831 // TODO: detect and diagnose the full richness of const mismatches.
7832 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7833 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7834 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7835 }
7836
7837 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7838 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7839 // It is dumb that we have to do this here.
7840 while (isa<ArrayType>(CFromTy))
7841 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7842 while (isa<ArrayType>(CToTy))
7843 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7844
7845 Qualifiers FromQs = CFromTy.getQualifiers();
7846 Qualifiers ToQs = CToTy.getQualifiers();
7847
7848 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7850 << (unsigned) FnKind << FnDesc
7851 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7852 << FromTy
7853 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7854 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007855 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007856 return;
7857 }
7858
John McCallf85e1932011-06-15 23:02:42 +00007859 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007860 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007861 << (unsigned) FnKind << FnDesc
7862 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7863 << FromTy
7864 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7865 << (unsigned) isObjectArgument << I+1;
7866 MaybeEmitInheritedConstructorNote(S, Fn);
7867 return;
7868 }
7869
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007870 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7871 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7872 << (unsigned) FnKind << FnDesc
7873 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7874 << FromTy
7875 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7876 << (unsigned) isObjectArgument << I+1;
7877 MaybeEmitInheritedConstructorNote(S, Fn);
7878 return;
7879 }
7880
John McCall651f3ee2010-01-14 03:28:57 +00007881 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7882 assert(CVR && "unexpected qualifiers mismatch");
7883
7884 if (isObjectArgument) {
7885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7886 << (unsigned) FnKind << FnDesc
7887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7888 << FromTy << (CVR - 1);
7889 } else {
7890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7891 << (unsigned) FnKind << FnDesc
7892 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7893 << FromTy << (CVR - 1) << I+1;
7894 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007895 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007896 return;
7897 }
7898
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007899 // Special diagnostic for failure to convert an initializer list, since
7900 // telling the user that it has type void is not useful.
7901 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7902 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7903 << (unsigned) FnKind << FnDesc
7904 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7905 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7906 MaybeEmitInheritedConstructorNote(S, Fn);
7907 return;
7908 }
7909
John McCall258b2032010-01-23 08:10:49 +00007910 // Diagnose references or pointers to incomplete types differently,
7911 // since it's far from impossible that the incompleteness triggered
7912 // the failure.
7913 QualType TempFromTy = FromTy.getNonReferenceType();
7914 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7915 TempFromTy = PTy->getPointeeType();
7916 if (TempFromTy->isIncompleteType()) {
7917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7918 << (unsigned) FnKind << FnDesc
7919 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7920 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007921 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00007922 return;
7923 }
7924
Douglas Gregor85789812010-06-30 23:01:39 +00007925 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007926 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007927 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7928 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7929 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7930 FromPtrTy->getPointeeType()) &&
7931 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7932 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007933 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007934 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007935 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007936 }
7937 } else if (const ObjCObjectPointerType *FromPtrTy
7938 = FromTy->getAs<ObjCObjectPointerType>()) {
7939 if (const ObjCObjectPointerType *ToPtrTy
7940 = ToTy->getAs<ObjCObjectPointerType>())
7941 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7942 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7943 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7944 FromPtrTy->getPointeeType()) &&
7945 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007946 BaseToDerivedConversion = 2;
7947 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7948 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7949 !FromTy->isIncompleteType() &&
7950 !ToRefTy->getPointeeType()->isIncompleteType() &&
7951 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7952 BaseToDerivedConversion = 3;
7953 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007954
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007955 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007956 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007957 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00007958 << (unsigned) FnKind << FnDesc
7959 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007960 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007961 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007962 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00007963 return;
7964 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007965
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00007966 if (isa<ObjCObjectPointerType>(CFromTy) &&
7967 isa<PointerType>(CToTy)) {
7968 Qualifiers FromQs = CFromTy.getQualifiers();
7969 Qualifiers ToQs = CToTy.getQualifiers();
7970 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7972 << (unsigned) FnKind << FnDesc
7973 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7974 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7975 MaybeEmitInheritedConstructorNote(S, Fn);
7976 return;
7977 }
7978 }
7979
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007980 // Emit the generic diagnostic and, optionally, add the hints to it.
7981 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7982 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00007983 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007984 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7985 << (unsigned) (Cand->Fix.Kind);
7986
7987 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00007988 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7989 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007990 FDiag << *HI;
7991 S.Diag(Fn->getLocation(), FDiag);
7992
Sebastian Redlf677ea32011-02-05 19:23:19 +00007993 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00007994}
7995
7996void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7997 unsigned NumFormalArgs) {
7998 // TODO: treat calls to a missing default constructor as a special case
7999
8000 FunctionDecl *Fn = Cand->Function;
8001 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8002
8003 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008004
Douglas Gregor439d3c32011-05-05 00:13:13 +00008005 // With invalid overloaded operators, it's possible that we think we
8006 // have an arity mismatch when it fact it looks like we have the
8007 // right number of arguments, because only overloaded operators have
8008 // the weird behavior of overloading member and non-member functions.
8009 // Just don't report anything.
8010 if (Fn->isInvalidDecl() &&
8011 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8012 return;
8013
John McCalladbb8f82010-01-13 09:16:55 +00008014 // at least / at most / exactly
8015 unsigned mode, modeCount;
8016 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008017 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8018 (Cand->FailureKind == ovl_fail_bad_deduction &&
8019 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008020 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008021 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008022 mode = 0; // "at least"
8023 else
8024 mode = 2; // "exactly"
8025 modeCount = MinParams;
8026 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008027 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8028 (Cand->FailureKind == ovl_fail_bad_deduction &&
8029 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008030 if (MinParams != FnTy->getNumArgs())
8031 mode = 1; // "at most"
8032 else
8033 mode = 2; // "exactly"
8034 modeCount = FnTy->getNumArgs();
8035 }
8036
8037 std::string Description;
8038 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8039
8040 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008041 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00008042 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008043 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008044}
8045
John McCall342fec42010-02-01 18:53:26 +00008046/// Diagnose a failed template-argument deduction.
8047void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8048 Expr **Args, unsigned NumArgs) {
8049 FunctionDecl *Fn = Cand->Function; // pattern
8050
Douglas Gregora9333192010-05-08 17:41:32 +00008051 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008052 NamedDecl *ParamD;
8053 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8054 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8055 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008056 switch (Cand->DeductionFailure.Result) {
8057 case Sema::TDK_Success:
8058 llvm_unreachable("TDK_success while diagnosing bad deduction");
8059
8060 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008061 assert(ParamD && "no parameter found for incomplete deduction result");
8062 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8063 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008064 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008065 return;
8066 }
8067
John McCall57e97782010-08-05 09:05:08 +00008068 case Sema::TDK_Underqualified: {
8069 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8070 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8071
8072 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8073
8074 // Param will have been canonicalized, but it should just be a
8075 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008076 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008077 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008078 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008079 assert(S.Context.hasSameType(Param, NonCanonParam));
8080
8081 // Arg has also been canonicalized, but there's nothing we can do
8082 // about that. It also doesn't matter as much, because it won't
8083 // have any template parameters in it (because deduction isn't
8084 // done on dependent types).
8085 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8086
8087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8088 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008089 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008090 return;
8091 }
8092
8093 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008094 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008095 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008096 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008097 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008098 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008099 which = 1;
8100 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008101 which = 2;
8102 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008103
Douglas Gregora9333192010-05-08 17:41:32 +00008104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008105 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008106 << *Cand->DeductionFailure.getFirstArg()
8107 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008108 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008109 return;
8110 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008111
Douglas Gregorf1a84452010-05-08 19:15:54 +00008112 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008113 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008114 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008115 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008116 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8117 << ParamD->getDeclName();
8118 else {
8119 int index = 0;
8120 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8121 index = TTP->getIndex();
8122 else if (NonTypeTemplateParmDecl *NTTP
8123 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8124 index = NTTP->getIndex();
8125 else
8126 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008127 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008128 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8129 << (index + 1);
8130 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008131 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008132 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008133
Douglas Gregora18592e2010-05-08 18:13:28 +00008134 case Sema::TDK_TooManyArguments:
8135 case Sema::TDK_TooFewArguments:
8136 DiagnoseArityMismatch(S, Cand, NumArgs);
8137 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008138
8139 case Sema::TDK_InstantiationDepth:
8140 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008141 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008142 return;
8143
8144 case Sema::TDK_SubstitutionFailure: {
8145 std::string ArgString;
8146 if (TemplateArgumentList *Args
8147 = Cand->DeductionFailure.getTemplateArgumentList())
8148 ArgString = S.getTemplateArgumentBindingsText(
8149 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8150 *Args);
8151 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8152 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008153 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008154 return;
8155 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008156
John McCall342fec42010-02-01 18:53:26 +00008157 // TODO: diagnose these individually, then kill off
8158 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008159 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008160 case Sema::TDK_FailedOverloadResolution:
8161 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008162 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008163 return;
8164 }
8165}
8166
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008167/// CUDA: diagnose an invalid call across targets.
8168void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8169 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8170 FunctionDecl *Callee = Cand->Function;
8171
8172 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8173 CalleeTarget = S.IdentifyCUDATarget(Callee);
8174
8175 std::string FnDesc;
8176 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8177
8178 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8179 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8180}
8181
John McCall342fec42010-02-01 18:53:26 +00008182/// Generates a 'note' diagnostic for an overload candidate. We've
8183/// already generated a primary error at the call site.
8184///
8185/// It really does need to be a single diagnostic with its caret
8186/// pointed at the candidate declaration. Yes, this creates some
8187/// major challenges of technical writing. Yes, this makes pointing
8188/// out problems with specific arguments quite awkward. It's still
8189/// better than generating twenty screens of text for every failed
8190/// overload.
8191///
8192/// It would be great to be able to express per-candidate problems
8193/// more richly for those diagnostic clients that cared, but we'd
8194/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008195void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8196 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008197 FunctionDecl *Fn = Cand->Function;
8198
John McCall81201622010-01-08 04:41:39 +00008199 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008200 if (Cand->Viable && (Fn->isDeleted() ||
8201 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008202 std::string FnDesc;
8203 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008204
8205 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00008206 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008207 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008208 return;
John McCall81201622010-01-08 04:41:39 +00008209 }
8210
John McCall220ccbf2010-01-13 00:25:19 +00008211 // We don't really have anything else to say about viable candidates.
8212 if (Cand->Viable) {
8213 S.NoteOverloadCandidate(Fn);
8214 return;
8215 }
John McCall1d318332010-01-12 00:44:57 +00008216
John McCalladbb8f82010-01-13 09:16:55 +00008217 switch (Cand->FailureKind) {
8218 case ovl_fail_too_many_arguments:
8219 case ovl_fail_too_few_arguments:
8220 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008221
John McCalladbb8f82010-01-13 09:16:55 +00008222 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00008223 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
8224
John McCall717e8912010-01-23 05:17:32 +00008225 case ovl_fail_trivial_conversion:
8226 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008227 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008228 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008229
John McCallb1bdc622010-02-25 01:37:24 +00008230 case ovl_fail_bad_conversion: {
8231 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008232 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008233 if (Cand->Conversions[I].isBad())
8234 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008235
John McCalladbb8f82010-01-13 09:16:55 +00008236 // FIXME: this currently happens when we're called from SemaInit
8237 // when user-conversion overload fails. Figure out how to handle
8238 // those conditions and diagnose them well.
8239 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008240 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008241
8242 case ovl_fail_bad_target:
8243 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008244 }
John McCalla1d7d622010-01-08 00:58:21 +00008245}
8246
8247void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8248 // Desugar the type of the surrogate down to a function type,
8249 // retaining as many typedefs as possible while still showing
8250 // the function type (and, therefore, its parameter types).
8251 QualType FnType = Cand->Surrogate->getConversionType();
8252 bool isLValueReference = false;
8253 bool isRValueReference = false;
8254 bool isPointer = false;
8255 if (const LValueReferenceType *FnTypeRef =
8256 FnType->getAs<LValueReferenceType>()) {
8257 FnType = FnTypeRef->getPointeeType();
8258 isLValueReference = true;
8259 } else if (const RValueReferenceType *FnTypeRef =
8260 FnType->getAs<RValueReferenceType>()) {
8261 FnType = FnTypeRef->getPointeeType();
8262 isRValueReference = true;
8263 }
8264 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8265 FnType = FnTypePtr->getPointeeType();
8266 isPointer = true;
8267 }
8268 // Desugar down to a function type.
8269 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8270 // Reconstruct the pointer/reference as appropriate.
8271 if (isPointer) FnType = S.Context.getPointerType(FnType);
8272 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8273 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8274
8275 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8276 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008277 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008278}
8279
8280void NoteBuiltinOperatorCandidate(Sema &S,
8281 const char *Opc,
8282 SourceLocation OpLoc,
8283 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008284 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008285 std::string TypeStr("operator");
8286 TypeStr += Opc;
8287 TypeStr += "(";
8288 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008289 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008290 TypeStr += ")";
8291 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8292 } else {
8293 TypeStr += ", ";
8294 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8295 TypeStr += ")";
8296 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8297 }
8298}
8299
8300void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8301 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008302 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008303 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8304 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008305 if (ICS.isBad()) break; // all meaningless after first invalid
8306 if (!ICS.isAmbiguous()) continue;
8307
John McCall120d63c2010-08-24 20:38:10 +00008308 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008309 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008310 }
8311}
8312
John McCall1b77e732010-01-15 23:32:50 +00008313SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8314 if (Cand->Function)
8315 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008316 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008317 return Cand->Surrogate->getLocation();
8318 return SourceLocation();
8319}
8320
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008321static unsigned
8322RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008323 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008324 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008325 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008326
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008327 case Sema::TDK_Incomplete:
8328 return 1;
8329
8330 case Sema::TDK_Underqualified:
8331 case Sema::TDK_Inconsistent:
8332 return 2;
8333
8334 case Sema::TDK_SubstitutionFailure:
8335 case Sema::TDK_NonDeducedMismatch:
8336 return 3;
8337
8338 case Sema::TDK_InstantiationDepth:
8339 case Sema::TDK_FailedOverloadResolution:
8340 return 4;
8341
8342 case Sema::TDK_InvalidExplicitArguments:
8343 return 5;
8344
8345 case Sema::TDK_TooManyArguments:
8346 case Sema::TDK_TooFewArguments:
8347 return 6;
8348 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008349 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008350}
8351
John McCallbf65c0b2010-01-12 00:48:53 +00008352struct CompareOverloadCandidatesForDisplay {
8353 Sema &S;
8354 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008355
8356 bool operator()(const OverloadCandidate *L,
8357 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008358 // Fast-path this check.
8359 if (L == R) return false;
8360
John McCall81201622010-01-08 04:41:39 +00008361 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008362 if (L->Viable) {
8363 if (!R->Viable) return true;
8364
8365 // TODO: introduce a tri-valued comparison for overload
8366 // candidates. Would be more worthwhile if we had a sort
8367 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008368 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8369 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008370 } else if (R->Viable)
8371 return false;
John McCall81201622010-01-08 04:41:39 +00008372
John McCall1b77e732010-01-15 23:32:50 +00008373 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008374
John McCall1b77e732010-01-15 23:32:50 +00008375 // Criteria by which we can sort non-viable candidates:
8376 if (!L->Viable) {
8377 // 1. Arity mismatches come after other candidates.
8378 if (L->FailureKind == ovl_fail_too_many_arguments ||
8379 L->FailureKind == ovl_fail_too_few_arguments)
8380 return false;
8381 if (R->FailureKind == ovl_fail_too_many_arguments ||
8382 R->FailureKind == ovl_fail_too_few_arguments)
8383 return true;
John McCall81201622010-01-08 04:41:39 +00008384
John McCall717e8912010-01-23 05:17:32 +00008385 // 2. Bad conversions come first and are ordered by the number
8386 // of bad conversions and quality of good conversions.
8387 if (L->FailureKind == ovl_fail_bad_conversion) {
8388 if (R->FailureKind != ovl_fail_bad_conversion)
8389 return true;
8390
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008391 // The conversion that can be fixed with a smaller number of changes,
8392 // comes first.
8393 unsigned numLFixes = L->Fix.NumConversionsFixed;
8394 unsigned numRFixes = R->Fix.NumConversionsFixed;
8395 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8396 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008397 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008398 if (numLFixes < numRFixes)
8399 return true;
8400 else
8401 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008402 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008403
John McCall717e8912010-01-23 05:17:32 +00008404 // If there's any ordering between the defined conversions...
8405 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008406 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008407
8408 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008409 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008410 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008411 switch (CompareImplicitConversionSequences(S,
8412 L->Conversions[I],
8413 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008414 case ImplicitConversionSequence::Better:
8415 leftBetter++;
8416 break;
8417
8418 case ImplicitConversionSequence::Worse:
8419 leftBetter--;
8420 break;
8421
8422 case ImplicitConversionSequence::Indistinguishable:
8423 break;
8424 }
8425 }
8426 if (leftBetter > 0) return true;
8427 if (leftBetter < 0) return false;
8428
8429 } else if (R->FailureKind == ovl_fail_bad_conversion)
8430 return false;
8431
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008432 if (L->FailureKind == ovl_fail_bad_deduction) {
8433 if (R->FailureKind != ovl_fail_bad_deduction)
8434 return true;
8435
8436 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8437 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008438 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008439 } else if (R->FailureKind == ovl_fail_bad_deduction)
8440 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008441
John McCall1b77e732010-01-15 23:32:50 +00008442 // TODO: others?
8443 }
8444
8445 // Sort everything else by location.
8446 SourceLocation LLoc = GetLocationForCandidate(L);
8447 SourceLocation RLoc = GetLocationForCandidate(R);
8448
8449 // Put candidates without locations (e.g. builtins) at the end.
8450 if (LLoc.isInvalid()) return false;
8451 if (RLoc.isInvalid()) return true;
8452
8453 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008454 }
8455};
8456
John McCall717e8912010-01-23 05:17:32 +00008457/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008458/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008459void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8460 Expr **Args, unsigned NumArgs) {
8461 assert(!Cand->Viable);
8462
8463 // Don't do anything on failures other than bad conversion.
8464 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8465
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008466 // We only want the FixIts if all the arguments can be corrected.
8467 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008468 // Use a implicit copy initialization to check conversion fixes.
8469 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008470
John McCall717e8912010-01-23 05:17:32 +00008471 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008472 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008473 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008474 while (true) {
8475 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8476 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008477 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008478 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008479 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008480 }
John McCall717e8912010-01-23 05:17:32 +00008481 }
8482
8483 if (ConvIdx == ConvCount)
8484 return;
8485
John McCallb1bdc622010-02-25 01:37:24 +00008486 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8487 "remaining conversion is initialized?");
8488
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008489 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008490 // operation somehow.
8491 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008492
8493 const FunctionProtoType* Proto;
8494 unsigned ArgIdx = ConvIdx;
8495
8496 if (Cand->IsSurrogate) {
8497 QualType ConvType
8498 = Cand->Surrogate->getConversionType().getNonReferenceType();
8499 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8500 ConvType = ConvPtrType->getPointeeType();
8501 Proto = ConvType->getAs<FunctionProtoType>();
8502 ArgIdx--;
8503 } else if (Cand->Function) {
8504 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8505 if (isa<CXXMethodDecl>(Cand->Function) &&
8506 !isa<CXXConstructorDecl>(Cand->Function))
8507 ArgIdx--;
8508 } else {
8509 // Builtin binary operator with a bad first conversion.
8510 assert(ConvCount <= 3);
8511 for (; ConvIdx != ConvCount; ++ConvIdx)
8512 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008513 = TryCopyInitialization(S, Args[ConvIdx],
8514 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008515 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008516 /*InOverloadResolution*/ true,
8517 /*AllowObjCWritebackConversion=*/
8518 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008519 return;
8520 }
8521
8522 // Fill in the rest of the conversions.
8523 unsigned NumArgsInProto = Proto->getNumArgs();
8524 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008525 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008526 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008527 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008528 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008529 /*InOverloadResolution=*/true,
8530 /*AllowObjCWritebackConversion=*/
8531 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008532 // Store the FixIt in the candidate if it exists.
8533 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008534 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008535 }
John McCall717e8912010-01-23 05:17:32 +00008536 else
8537 Cand->Conversions[ConvIdx].setEllipsis();
8538 }
8539}
8540
John McCalla1d7d622010-01-08 00:58:21 +00008541} // end anonymous namespace
8542
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008543/// PrintOverloadCandidates - When overload resolution fails, prints
8544/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008545/// set.
John McCall120d63c2010-08-24 20:38:10 +00008546void OverloadCandidateSet::NoteCandidates(Sema &S,
8547 OverloadCandidateDisplayKind OCD,
8548 Expr **Args, unsigned NumArgs,
8549 const char *Opc,
8550 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008551 // Sort the candidates by viability and position. Sorting directly would
8552 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008553 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008554 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8555 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008556 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008557 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008558 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00008559 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008560 if (Cand->Function || Cand->IsSurrogate)
8561 Cands.push_back(Cand);
8562 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8563 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008564 }
8565 }
8566
John McCallbf65c0b2010-01-12 00:48:53 +00008567 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008568 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008569
John McCall1d318332010-01-12 00:44:57 +00008570 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008571
Chris Lattner5f9e2722011-07-23 10:55:15 +00008572 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008573 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8574 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008575 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008576 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8577 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008578
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008579 // Set an arbitrary limit on the number of candidate functions we'll spam
8580 // the user with. FIXME: This limit should depend on details of the
8581 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008582 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008583 break;
8584 }
8585 ++CandsShown;
8586
John McCalla1d7d622010-01-08 00:58:21 +00008587 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00008588 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00008589 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008590 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008591 else {
8592 assert(Cand->Viable &&
8593 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008594 // Generally we only see ambiguities including viable builtin
8595 // operators if overload resolution got screwed up by an
8596 // ambiguous user-defined conversion.
8597 //
8598 // FIXME: It's quite possible for different conversions to see
8599 // different ambiguities, though.
8600 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008601 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008602 ReportedAmbiguousConversions = true;
8603 }
John McCalla1d7d622010-01-08 00:58:21 +00008604
John McCall1d318332010-01-12 00:44:57 +00008605 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008606 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008607 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008608 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008609
8610 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008611 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008612}
8613
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008614// [PossiblyAFunctionType] --> [Return]
8615// NonFunctionType --> NonFunctionType
8616// R (A) --> R(A)
8617// R (*)(A) --> R (A)
8618// R (&)(A) --> R (A)
8619// R (S::*)(A) --> R (A)
8620QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8621 QualType Ret = PossiblyAFunctionType;
8622 if (const PointerType *ToTypePtr =
8623 PossiblyAFunctionType->getAs<PointerType>())
8624 Ret = ToTypePtr->getPointeeType();
8625 else if (const ReferenceType *ToTypeRef =
8626 PossiblyAFunctionType->getAs<ReferenceType>())
8627 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008628 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008629 PossiblyAFunctionType->getAs<MemberPointerType>())
8630 Ret = MemTypePtr->getPointeeType();
8631 Ret =
8632 Context.getCanonicalType(Ret).getUnqualifiedType();
8633 return Ret;
8634}
Douglas Gregor904eed32008-11-10 20:40:00 +00008635
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008636// A helper class to help with address of function resolution
8637// - allows us to avoid passing around all those ugly parameters
8638class AddressOfFunctionResolver
8639{
8640 Sema& S;
8641 Expr* SourceExpr;
8642 const QualType& TargetType;
8643 QualType TargetFunctionType; // Extracted function type from target type
8644
8645 bool Complain;
8646 //DeclAccessPair& ResultFunctionAccessPair;
8647 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008648
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008649 bool TargetTypeIsNonStaticMemberFunction;
8650 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008651
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008652 OverloadExpr::FindResult OvlExprInfo;
8653 OverloadExpr *OvlExpr;
8654 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008655 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008656
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008657public:
8658 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8659 const QualType& TargetType, bool Complain)
8660 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8661 Complain(Complain), Context(S.getASTContext()),
8662 TargetTypeIsNonStaticMemberFunction(
8663 !!TargetType->getAs<MemberPointerType>()),
8664 FoundNonTemplateFunction(false),
8665 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8666 OvlExpr(OvlExprInfo.Expression)
8667 {
8668 ExtractUnqualifiedFunctionTypeFromTargetType();
8669
8670 if (!TargetFunctionType->isFunctionType()) {
8671 if (OvlExpr->hasExplicitTemplateArgs()) {
8672 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008673 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008674 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008675
8676 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8677 if (!Method->isStatic()) {
8678 // If the target type is a non-function type and the function
8679 // found is a non-static member function, pretend as if that was
8680 // the target, it's the only possible type to end up with.
8681 TargetTypeIsNonStaticMemberFunction = true;
8682
8683 // And skip adding the function if its not in the proper form.
8684 // We'll diagnose this due to an empty set of functions.
8685 if (!OvlExprInfo.HasFormOfMemberPointer)
8686 return;
8687 }
8688 }
8689
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008690 Matches.push_back(std::make_pair(dap,Fn));
8691 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008692 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008693 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008694 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008695
8696 if (OvlExpr->hasExplicitTemplateArgs())
8697 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008698
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008699 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8700 // C++ [over.over]p4:
8701 // If more than one function is selected, [...]
8702 if (Matches.size() > 1) {
8703 if (FoundNonTemplateFunction)
8704 EliminateAllTemplateMatches();
8705 else
8706 EliminateAllExceptMostSpecializedTemplate();
8707 }
8708 }
8709 }
8710
8711private:
8712 bool isTargetTypeAFunction() const {
8713 return TargetFunctionType->isFunctionType();
8714 }
8715
8716 // [ToType] [Return]
8717
8718 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8719 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8720 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8721 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8722 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8723 }
8724
8725 // return true if any matching specializations were found
8726 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8727 const DeclAccessPair& CurAccessFunPair) {
8728 if (CXXMethodDecl *Method
8729 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8730 // Skip non-static function templates when converting to pointer, and
8731 // static when converting to member pointer.
8732 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8733 return false;
8734 }
8735 else if (TargetTypeIsNonStaticMemberFunction)
8736 return false;
8737
8738 // C++ [over.over]p2:
8739 // If the name is a function template, template argument deduction is
8740 // done (14.8.2.2), and if the argument deduction succeeds, the
8741 // resulting template argument list is used to generate a single
8742 // function template specialization, which is added to the set of
8743 // overloaded functions considered.
8744 FunctionDecl *Specialization = 0;
8745 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8746 if (Sema::TemplateDeductionResult Result
8747 = S.DeduceTemplateArguments(FunctionTemplate,
8748 &OvlExplicitTemplateArgs,
8749 TargetFunctionType, Specialization,
8750 Info)) {
8751 // FIXME: make a note of the failed deduction for diagnostics.
8752 (void)Result;
8753 return false;
8754 }
8755
8756 // Template argument deduction ensures that we have an exact match.
8757 // This function template specicalization works.
8758 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8759 assert(TargetFunctionType
8760 == Context.getCanonicalType(Specialization->getType()));
8761 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8762 return true;
8763 }
8764
8765 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8766 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008768 // Skip non-static functions when converting to pointer, and static
8769 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008770 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8771 return false;
8772 }
8773 else if (TargetTypeIsNonStaticMemberFunction)
8774 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008775
Chandler Carruthbd647292009-12-29 06:17:27 +00008776 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008777 if (S.getLangOptions().CUDA)
8778 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8779 if (S.CheckCUDATarget(Caller, FunDecl))
8780 return false;
8781
Douglas Gregor43c79c22009-12-09 00:47:37 +00008782 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008783 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8784 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008785 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8786 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008787 Matches.push_back(std::make_pair(CurAccessFunPair,
8788 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008789 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008790 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008791 }
Mike Stump1eb44332009-09-09 15:08:12 +00008792 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008793
8794 return false;
8795 }
8796
8797 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8798 bool Ret = false;
8799
8800 // If the overload expression doesn't have the form of a pointer to
8801 // member, don't try to convert it to a pointer-to-member type.
8802 if (IsInvalidFormOfPointerToMemberFunction())
8803 return false;
8804
8805 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8806 E = OvlExpr->decls_end();
8807 I != E; ++I) {
8808 // Look through any using declarations to find the underlying function.
8809 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8810
8811 // C++ [over.over]p3:
8812 // Non-member functions and static member functions match
8813 // targets of type "pointer-to-function" or "reference-to-function."
8814 // Nonstatic member functions match targets of
8815 // type "pointer-to-member-function."
8816 // Note that according to DR 247, the containing class does not matter.
8817 if (FunctionTemplateDecl *FunctionTemplate
8818 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8819 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8820 Ret = true;
8821 }
8822 // If we have explicit template arguments supplied, skip non-templates.
8823 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8824 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8825 Ret = true;
8826 }
8827 assert(Ret || Matches.empty());
8828 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008829 }
8830
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008831 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008832 // [...] and any given function template specialization F1 is
8833 // eliminated if the set contains a second function template
8834 // specialization whose function template is more specialized
8835 // than the function template of F1 according to the partial
8836 // ordering rules of 14.5.5.2.
8837
8838 // The algorithm specified above is quadratic. We instead use a
8839 // two-pass algorithm (similar to the one used to identify the
8840 // best viable function in an overload set) that identifies the
8841 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008842
8843 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8844 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8845 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008846
John McCallc373d482010-01-27 01:50:18 +00008847 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008848 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8849 TPOC_Other, 0, SourceExpr->getLocStart(),
8850 S.PDiag(),
8851 S.PDiag(diag::err_addr_ovl_ambiguous)
8852 << Matches[0].second->getDeclName(),
8853 S.PDiag(diag::note_ovl_candidate)
8854 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008855 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008856
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008857 if (Result != MatchesCopy.end()) {
8858 // Make it the first and only element
8859 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8860 Matches[0].second = cast<FunctionDecl>(*Result);
8861 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008862 }
8863 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008864
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008865 void EliminateAllTemplateMatches() {
8866 // [...] any function template specializations in the set are
8867 // eliminated if the set also contains a non-template function, [...]
8868 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8869 if (Matches[I].second->getPrimaryTemplate() == 0)
8870 ++I;
8871 else {
8872 Matches[I] = Matches[--N];
8873 Matches.set_size(N);
8874 }
8875 }
8876 }
8877
8878public:
8879 void ComplainNoMatchesFound() const {
8880 assert(Matches.empty());
8881 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8882 << OvlExpr->getName() << TargetFunctionType
8883 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008884 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008885 }
8886
8887 bool IsInvalidFormOfPointerToMemberFunction() const {
8888 return TargetTypeIsNonStaticMemberFunction &&
8889 !OvlExprInfo.HasFormOfMemberPointer;
8890 }
8891
8892 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8893 // TODO: Should we condition this on whether any functions might
8894 // have matched, or is it more appropriate to do that in callers?
8895 // TODO: a fixit wouldn't hurt.
8896 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8897 << TargetType << OvlExpr->getSourceRange();
8898 }
8899
8900 void ComplainOfInvalidConversion() const {
8901 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8902 << OvlExpr->getName() << TargetType;
8903 }
8904
8905 void ComplainMultipleMatchesFound() const {
8906 assert(Matches.size() > 1);
8907 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8908 << OvlExpr->getName()
8909 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008910 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008911 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008912
8913 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8914
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008915 int getNumMatches() const { return Matches.size(); }
8916
8917 FunctionDecl* getMatchingFunctionDecl() const {
8918 if (Matches.size() != 1) return 0;
8919 return Matches[0].second;
8920 }
8921
8922 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8923 if (Matches.size() != 1) return 0;
8924 return &Matches[0].first;
8925 }
8926};
8927
8928/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8929/// an overloaded function (C++ [over.over]), where @p From is an
8930/// expression with overloaded function type and @p ToType is the type
8931/// we're trying to resolve to. For example:
8932///
8933/// @code
8934/// int f(double);
8935/// int f(int);
8936///
8937/// int (*pfd)(double) = f; // selects f(double)
8938/// @endcode
8939///
8940/// This routine returns the resulting FunctionDecl if it could be
8941/// resolved, and NULL otherwise. When @p Complain is true, this
8942/// routine will emit diagnostics if there is an error.
8943FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008944Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8945 QualType TargetType,
8946 bool Complain,
8947 DeclAccessPair &FoundResult,
8948 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008949 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008950
8951 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8952 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008953 int NumMatches = Resolver.getNumMatches();
8954 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008955 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008956 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8957 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8958 else
8959 Resolver.ComplainNoMatchesFound();
8960 }
8961 else if (NumMatches > 1 && Complain)
8962 Resolver.ComplainMultipleMatchesFound();
8963 else if (NumMatches == 1) {
8964 Fn = Resolver.getMatchingFunctionDecl();
8965 assert(Fn);
8966 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00008967 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00008968 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008969 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00008970 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008971
8972 if (pHadMultipleCandidates)
8973 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008974 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00008975}
8976
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008977/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00008978/// resolve that overloaded function expression down to a single function.
8979///
8980/// This routine can only resolve template-ids that refer to a single function
8981/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008982/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00008983/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00008984FunctionDecl *
8985Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8986 bool Complain,
8987 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008988 // C++ [over.over]p1:
8989 // [...] [Note: any redundant set of parentheses surrounding the
8990 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00008991 // C++ [over.over]p1:
8992 // [...] The overloaded function name can be preceded by the &
8993 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008994
Douglas Gregor4b52e252009-12-21 23:17:24 +00008995 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00008996 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00008997 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00008998
8999 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009000 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009001
Douglas Gregor4b52e252009-12-21 23:17:24 +00009002 // Look through all of the overloaded functions, searching for one
9003 // whose type matches exactly.
9004 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009005 for (UnresolvedSetIterator I = ovl->decls_begin(),
9006 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009007 // C++0x [temp.arg.explicit]p3:
9008 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009009 // where deduction is not done, if a template argument list is
9010 // specified and it, along with any default template arguments,
9011 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009012 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009013 FunctionTemplateDecl *FunctionTemplate
9014 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009015
Douglas Gregor4b52e252009-12-21 23:17:24 +00009016 // C++ [over.over]p2:
9017 // If the name is a function template, template argument deduction is
9018 // done (14.8.2.2), and if the argument deduction succeeds, the
9019 // resulting template argument list is used to generate a single
9020 // function template specialization, which is added to the set of
9021 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009022 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009023 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009024 if (TemplateDeductionResult Result
9025 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9026 Specialization, Info)) {
9027 // FIXME: make a note of the failed deduction for diagnostics.
9028 (void)Result;
9029 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009030 }
9031
John McCall864c0412011-04-26 20:42:42 +00009032 assert(Specialization && "no specialization and no error?");
9033
Douglas Gregor4b52e252009-12-21 23:17:24 +00009034 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009035 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009036 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009037 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9038 << ovl->getName();
9039 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009040 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009041 return 0;
John McCall864c0412011-04-26 20:42:42 +00009042 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009043
John McCall864c0412011-04-26 20:42:42 +00009044 Matched = Specialization;
9045 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009046 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009047
Douglas Gregor4b52e252009-12-21 23:17:24 +00009048 return Matched;
9049}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009050
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009051
9052
9053
John McCall6dbba4f2011-10-11 23:14:30 +00009054// Resolve and fix an overloaded expression that can be resolved
9055// because it identifies a single function template specialization.
9056//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009057// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009058//
9059// Return true if it was logically possible to so resolve the
9060// expression, regardless of whether or not it succeeded. Always
9061// returns true if 'complain' is set.
9062bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9063 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9064 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009065 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009066 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009067 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009068
John McCall6dbba4f2011-10-11 23:14:30 +00009069 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009070
John McCall864c0412011-04-26 20:42:42 +00009071 DeclAccessPair found;
9072 ExprResult SingleFunctionExpression;
9073 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9074 ovl.Expression, /*complain*/ false, &found)) {
John McCall6dbba4f2011-10-11 23:14:30 +00009075 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
9076 SrcExpr = ExprError();
9077 return true;
9078 }
John McCall864c0412011-04-26 20:42:42 +00009079
9080 // It is only correct to resolve to an instance method if we're
9081 // resolving a form that's permitted to be a pointer to member.
9082 // Otherwise we'll end up making a bound member expression, which
9083 // is illegal in all the contexts we resolve like this.
9084 if (!ovl.HasFormOfMemberPointer &&
9085 isa<CXXMethodDecl>(fn) &&
9086 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009087 if (!complain) return false;
9088
9089 Diag(ovl.Expression->getExprLoc(),
9090 diag::err_bound_member_function)
9091 << 0 << ovl.Expression->getSourceRange();
9092
9093 // TODO: I believe we only end up here if there's a mix of
9094 // static and non-static candidates (otherwise the expression
9095 // would have 'bound member' type, not 'overload' type).
9096 // Ideally we would note which candidate was chosen and why
9097 // the static candidates were rejected.
9098 SrcExpr = ExprError();
9099 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009100 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009101
John McCall864c0412011-04-26 20:42:42 +00009102 // Fix the expresion to refer to 'fn'.
9103 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009104 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009105
9106 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009107 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009108 SingleFunctionExpression =
9109 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009110 if (SingleFunctionExpression.isInvalid()) {
9111 SrcExpr = ExprError();
9112 return true;
9113 }
9114 }
John McCall864c0412011-04-26 20:42:42 +00009115 }
9116
9117 if (!SingleFunctionExpression.isUsable()) {
9118 if (complain) {
9119 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9120 << ovl.Expression->getName()
9121 << DestTypeForComplaining
9122 << OpRangeForComplaining
9123 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009124 NoteAllOverloadCandidates(SrcExpr.get());
9125
9126 SrcExpr = ExprError();
9127 return true;
9128 }
9129
9130 return false;
John McCall864c0412011-04-26 20:42:42 +00009131 }
9132
John McCall6dbba4f2011-10-11 23:14:30 +00009133 SrcExpr = SingleFunctionExpression;
9134 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009135}
9136
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009137/// \brief Add a single candidate to the overload set.
9138static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009139 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009140 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009141 Expr **Args, unsigned NumArgs,
9142 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009143 bool PartialOverloading,
9144 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009145 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009146 if (isa<UsingShadowDecl>(Callee))
9147 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9148
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009149 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009150 if (ExplicitTemplateArgs) {
9151 assert(!KnownValid && "Explicit template arguments?");
9152 return;
9153 }
John McCall9aa472c2010-03-19 07:35:19 +00009154 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00009155 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009156 return;
John McCallba135432009-11-21 08:51:07 +00009157 }
9158
9159 if (FunctionTemplateDecl *FuncTemplate
9160 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009161 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9162 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00009163 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009164 return;
9165 }
9166
Richard Smith2ced0442011-06-26 22:19:54 +00009167 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009168}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009169
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009170/// \brief Add the overload candidates named by callee and/or found by argument
9171/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009172void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009173 Expr **Args, unsigned NumArgs,
9174 OverloadCandidateSet &CandidateSet,
9175 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009176
9177#ifndef NDEBUG
9178 // Verify that ArgumentDependentLookup is consistent with the rules
9179 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009180 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009181 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9182 // and let Y be the lookup set produced by argument dependent
9183 // lookup (defined as follows). If X contains
9184 //
9185 // -- a declaration of a class member, or
9186 //
9187 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009188 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009189 //
9190 // -- a declaration that is neither a function or a function
9191 // template
9192 //
9193 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009194
John McCall3b4294e2009-12-16 12:17:52 +00009195 if (ULE->requiresADL()) {
9196 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9197 E = ULE->decls_end(); I != E; ++I) {
9198 assert(!(*I)->getDeclContext()->isRecord());
9199 assert(isa<UsingShadowDecl>(*I) ||
9200 !(*I)->getDeclContext()->isFunctionOrMethod());
9201 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009202 }
9203 }
9204#endif
9205
John McCall3b4294e2009-12-16 12:17:52 +00009206 // It would be nice to avoid this copy.
9207 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009208 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009209 if (ULE->hasExplicitTemplateArgs()) {
9210 ULE->copyTemplateArgumentsInto(TABuffer);
9211 ExplicitTemplateArgs = &TABuffer;
9212 }
9213
9214 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9215 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00009216 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009217 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009218 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009219
John McCall3b4294e2009-12-16 12:17:52 +00009220 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009221 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9222 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009223 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009224 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00009225 PartialOverloading,
9226 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009227}
John McCall578b69b2009-12-16 08:11:27 +00009228
Richard Smithf50e88a2011-06-05 22:42:48 +00009229/// Attempt to recover from an ill-formed use of a non-dependent name in a
9230/// template, where the non-dependent name was declared after the template
9231/// was defined. This is common in code written for a compilers which do not
9232/// correctly implement two-stage name lookup.
9233///
9234/// Returns true if a viable candidate was found and a diagnostic was issued.
9235static bool
9236DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9237 const CXXScopeSpec &SS, LookupResult &R,
9238 TemplateArgumentListInfo *ExplicitTemplateArgs,
9239 Expr **Args, unsigned NumArgs) {
9240 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9241 return false;
9242
9243 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9244 SemaRef.LookupQualifiedName(R, DC);
9245
9246 if (!R.empty()) {
9247 R.suppressDiagnostics();
9248
9249 if (isa<CXXRecordDecl>(DC)) {
9250 // Don't diagnose names we find in classes; we get much better
9251 // diagnostics for these from DiagnoseEmptyLookup.
9252 R.clear();
9253 return false;
9254 }
9255
9256 OverloadCandidateSet Candidates(FnLoc);
9257 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9258 AddOverloadedCallCandidate(SemaRef, I.getPair(),
9259 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00009260 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009261
9262 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009263 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009264 // No viable functions. Don't bother the user with notes for functions
9265 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009266 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009267 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009268 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009269
9270 // Find the namespaces where ADL would have looked, and suggest
9271 // declaring the function there instead.
9272 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9273 Sema::AssociatedClassSet AssociatedClasses;
9274 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
9275 AssociatedNamespaces,
9276 AssociatedClasses);
9277 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009278 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009279 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009280 for (Sema::AssociatedNamespaceSet::iterator
9281 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009282 end = AssociatedNamespaces.end(); it != end; ++it) {
9283 if (!Std->Encloses(*it))
9284 SuggestedNamespaces.insert(*it);
9285 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009286 } else {
9287 // Lacking the 'std::' namespace, use all of the associated namespaces.
9288 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009289 }
9290
9291 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9292 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009293 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009294 SemaRef.Diag(Best->Function->getLocation(),
9295 diag::note_not_found_by_two_phase_lookup)
9296 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009297 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009298 SemaRef.Diag(Best->Function->getLocation(),
9299 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009300 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009301 } else {
9302 // FIXME: It would be useful to list the associated namespaces here,
9303 // but the diagnostics infrastructure doesn't provide a way to produce
9304 // a localized representation of a list of items.
9305 SemaRef.Diag(Best->Function->getLocation(),
9306 diag::note_not_found_by_two_phase_lookup)
9307 << R.getLookupName() << 2;
9308 }
9309
9310 // Try to recover by calling this function.
9311 return true;
9312 }
9313
9314 R.clear();
9315 }
9316
9317 return false;
9318}
9319
9320/// Attempt to recover from ill-formed use of a non-dependent operator in a
9321/// template, where the non-dependent operator was declared after the template
9322/// was defined.
9323///
9324/// Returns true if a viable candidate was found and a diagnostic was issued.
9325static bool
9326DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9327 SourceLocation OpLoc,
9328 Expr **Args, unsigned NumArgs) {
9329 DeclarationName OpName =
9330 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9331 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9332 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9333 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
9334}
9335
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009336namespace {
9337// Callback to limit the allowed keywords and to only accept typo corrections
9338// that are keywords or whose decls refer to functions (or template functions)
9339// that accept the given number of arguments.
9340class RecoveryCallCCC : public CorrectionCandidateCallback {
9341 public:
9342 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9343 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9344 WantTypeSpecifiers = SemaRef.getLangOptions().CPlusPlus;
9345 WantRemainingKeywords = false;
9346 }
9347
9348 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9349 if (!candidate.getCorrectionDecl())
9350 return candidate.isKeyword();
9351
9352 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9353 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9354 FunctionDecl *FD = 0;
9355 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9356 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9357 FD = FTD->getTemplatedDecl();
9358 if (!HasExplicitTemplateArgs && !FD) {
9359 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9360 // If the Decl is neither a function nor a template function,
9361 // determine if it is a pointer or reference to a function. If so,
9362 // check against the number of arguments expected for the pointee.
9363 QualType ValType = cast<ValueDecl>(ND)->getType();
9364 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9365 ValType = ValType->getPointeeType();
9366 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9367 if (FPT->getNumArgs() == NumArgs)
9368 return true;
9369 }
9370 }
9371 if (FD && FD->getNumParams() >= NumArgs &&
9372 FD->getMinRequiredArguments() <= NumArgs)
9373 return true;
9374 }
9375 return false;
9376 }
9377
9378 private:
9379 unsigned NumArgs;
9380 bool HasExplicitTemplateArgs;
9381};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009382
9383// Callback that effectively disabled typo correction
9384class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9385 public:
9386 NoTypoCorrectionCCC() {
9387 WantTypeSpecifiers = false;
9388 WantExpressionKeywords = false;
9389 WantCXXNamedCasts = false;
9390 WantRemainingKeywords = false;
9391 }
9392
9393 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9394 return false;
9395 }
9396};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009397}
9398
John McCall578b69b2009-12-16 08:11:27 +00009399/// Attempts to recover from a call where no functions were found.
9400///
9401/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009402static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009403BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009404 UnresolvedLookupExpr *ULE,
9405 SourceLocation LParenLoc,
9406 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00009407 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009408 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009409
9410 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009411 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009412 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009413
John McCall3b4294e2009-12-16 12:17:52 +00009414 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009415 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009416 if (ULE->hasExplicitTemplateArgs()) {
9417 ULE->copyTemplateArgumentsInto(TABuffer);
9418 ExplicitTemplateArgs = &TABuffer;
9419 }
9420
John McCall578b69b2009-12-16 08:11:27 +00009421 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9422 Sema::LookupOrdinaryName);
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009423 RecoveryCallCCC Validator(SemaRef, NumArgs, ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009424 NoTypoCorrectionCCC RejectAll;
9425 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9426 (CorrectionCandidateCallback*)&Validator :
9427 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009428 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9429 ExplicitTemplateArgs, Args, NumArgs) &&
9430 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009431 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00009432 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00009433 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009434
John McCall3b4294e2009-12-16 12:17:52 +00009435 assert(!R.empty() && "lookup results empty despite recovery");
9436
9437 // Build an implicit member call if appropriate. Just drop the
9438 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009439 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009440 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009441 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9442 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009443 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009444 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009445 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009446 else
9447 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9448
9449 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009450 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009451
9452 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009453 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009454 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009455 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00009456 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009457}
Douglas Gregord7a95972010-06-08 17:35:15 +00009458
Douglas Gregorf6b89692008-11-26 05:54:23 +00009459/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009460/// (which eventually refers to the declaration Func) and the call
9461/// arguments Args/NumArgs, attempt to resolve the function call down
9462/// to a specific function. If overload resolution succeeds, returns
9463/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009464/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009465/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009466ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009467Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009468 SourceLocation LParenLoc,
9469 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009470 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009471 Expr *ExecConfig,
9472 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009473#ifndef NDEBUG
9474 if (ULE->requiresADL()) {
9475 // To do ADL, we must have found an unqualified name.
9476 assert(!ULE->getQualifier() && "qualified name with ADL");
9477
9478 // We don't perform ADL for implicit declarations of builtins.
9479 // Verify that this was correctly set up.
9480 FunctionDecl *F;
9481 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9482 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9483 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009484 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009485
John McCall3b4294e2009-12-16 12:17:52 +00009486 // We don't perform ADL in C.
9487 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009488 } else
9489 assert(!ULE->isStdAssociatedNamespace() &&
9490 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009491#endif
9492
John McCall5acb0c92011-10-17 18:40:02 +00009493 UnbridgedCastsSet UnbridgedCasts;
9494 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9495 return ExprError();
9496
John McCall5769d612010-02-08 23:07:23 +00009497 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009498
John McCall3b4294e2009-12-16 12:17:52 +00009499 // Add the functions denoted by the callee to the set of candidate
9500 // functions, including those from argument-dependent lookup.
9501 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009502
9503 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009504 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9505 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009506 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009507 // In Microsoft mode, if we are inside a template class member function then
9508 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009509 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009510 // classes.
Francois Pichetef04ecf2011-11-11 00:12:11 +00009511 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009512 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009513 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9514 Context.DependentTy, VK_RValue,
9515 RParenLoc);
9516 CE->setTypeDependent(true);
9517 return Owned(CE);
9518 }
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009519 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009520 RParenLoc, /*EmptyLookup=*/true,
9521 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009522 }
John McCall578b69b2009-12-16 08:11:27 +00009523
John McCall5acb0c92011-10-17 18:40:02 +00009524 UnbridgedCasts.restore();
9525
Douglas Gregorf6b89692008-11-26 05:54:23 +00009526 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009527 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009528 case OR_Success: {
9529 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009530 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009531 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009532 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009533 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009534 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9535 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009536 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009537
Richard Smithf50e88a2011-06-05 22:42:48 +00009538 case OR_No_Viable_Function: {
9539 // Try to recover by looking for viable functions which the user might
9540 // have meant to call.
9541 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9542 Args, NumArgs, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009543 /*EmptyLookup=*/false,
9544 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009545 if (!Recovery.isInvalid())
9546 return Recovery;
9547
Chris Lattner4330d652009-02-17 07:29:20 +00009548 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009549 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009550 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009551 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009552 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009553 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009554
9555 case OR_Ambiguous:
9556 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009557 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009558 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009559 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009560
9561 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009562 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009563 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
9564 << Best->Function->isDeleted()
9565 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009566 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009567 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009568 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009569
9570 // We emitted an error for the unvailable/deleted function call but keep
9571 // the call in the AST.
9572 FunctionDecl *FDecl = Best->Function;
9573 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9574 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9575 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009576 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009577 }
9578
Douglas Gregorff331c12010-07-25 18:17:45 +00009579 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009580 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009581}
9582
John McCall6e266892010-01-26 03:27:55 +00009583static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009584 return Functions.size() > 1 ||
9585 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9586}
9587
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009588/// \brief Create a unary operation that may resolve to an overloaded
9589/// operator.
9590///
9591/// \param OpLoc The location of the operator itself (e.g., '*').
9592///
9593/// \param OpcIn The UnaryOperator::Opcode that describes this
9594/// operator.
9595///
9596/// \param Functions The set of non-member functions that will be
9597/// considered by overload resolution. The caller needs to build this
9598/// set based on the context using, e.g.,
9599/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9600/// set should not contain any member functions; those will be added
9601/// by CreateOverloadedUnaryOp().
9602///
9603/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009604ExprResult
John McCall6e266892010-01-26 03:27:55 +00009605Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9606 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009607 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009608 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009609
9610 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9611 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9612 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009613 // TODO: provide better source location info.
9614 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009615
John McCall5acb0c92011-10-17 18:40:02 +00009616 if (checkPlaceholderForOverload(*this, Input))
9617 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009618
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009619 Expr *Args[2] = { Input, 0 };
9620 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009621
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009622 // For post-increment and post-decrement, add the implicit '0' as
9623 // the second argument, so that we know this is a post-increment or
9624 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009625 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009626 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009627 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9628 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009629 NumArgs = 2;
9630 }
9631
9632 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009633 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009634 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009635 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009636 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009637 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009638 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009639
John McCallc373d482010-01-27 01:50:18 +00009640 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009641 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009642 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009643 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009644 /*ADL*/ true, IsOverloaded(Fns),
9645 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009646 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009647 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009648 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009649 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009650 OpLoc));
9651 }
9652
9653 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009654 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009655
9656 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009657 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009658
9659 // Add operator candidates that are member functions.
9660 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9661
John McCall6e266892010-01-26 03:27:55 +00009662 // Add candidates from ADL.
9663 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00009664 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00009665 /*ExplicitTemplateArgs*/ 0,
9666 CandidateSet);
9667
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009668 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009669 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009670
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009671 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9672
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009673 // Perform overload resolution.
9674 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009675 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009676 case OR_Success: {
9677 // We found a built-in operator or an overloaded operator.
9678 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009679
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009680 if (FnDecl) {
9681 // We matched an overloaded operator. Build a call to that
9682 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009683
Eli Friedman5f2987c2012-02-02 03:46:19 +00009684 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009685
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009686 // Convert the arguments.
9687 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009688 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009689
John Wiegley429bb272011-04-08 18:41:53 +00009690 ExprResult InputRes =
9691 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9692 Best->FoundDecl, Method);
9693 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009694 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009695 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009696 } else {
9697 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009698 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009699 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009700 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009701 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009702 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009703 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009704 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009705 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009706 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009707 }
9708
John McCallb697e082010-05-06 18:15:07 +00009709 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9710
John McCallf89e55a2010-11-18 06:31:45 +00009711 // Determine the result type.
9712 QualType ResultTy = FnDecl->getResultType();
9713 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9714 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009715
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009716 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009717 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009718 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009719 if (FnExpr.isInvalid())
9720 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009721
Eli Friedman4c3b8962009-11-18 03:58:17 +00009722 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009723 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009724 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009725 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009726
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009727 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009728 FnDecl))
9729 return ExprError();
9730
John McCall9ae2f072010-08-23 23:25:46 +00009731 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009732 } else {
9733 // We matched a built-in operator. Convert the arguments, then
9734 // break out so that we will build the appropriate built-in
9735 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009736 ExprResult InputRes =
9737 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9738 Best->Conversions[0], AA_Passing);
9739 if (InputRes.isInvalid())
9740 return ExprError();
9741 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009742 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009743 }
John Wiegley429bb272011-04-08 18:41:53 +00009744 }
9745
9746 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009747 // This is an erroneous use of an operator which can be overloaded by
9748 // a non-member function. Check for non-member operators which were
9749 // defined too late to be candidates.
9750 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9751 // FIXME: Recover by calling the found function.
9752 return ExprError();
9753
John Wiegley429bb272011-04-08 18:41:53 +00009754 // No viable function; fall through to handling this as a
9755 // built-in operator, which will produce an error message for us.
9756 break;
9757
9758 case OR_Ambiguous:
9759 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9760 << UnaryOperator::getOpcodeStr(Opc)
9761 << Input->getType()
9762 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009763 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley429bb272011-04-08 18:41:53 +00009764 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9765 return ExprError();
9766
9767 case OR_Deleted:
9768 Diag(OpLoc, diag::err_ovl_deleted_oper)
9769 << Best->Function->isDeleted()
9770 << UnaryOperator::getOpcodeStr(Opc)
9771 << getDeletedOrUnavailableSuffix(Best->Function)
9772 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009773 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9774 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009775 return ExprError();
9776 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009777
9778 // Either we found no viable overloaded operator or we matched a
9779 // built-in operator. In either case, fall through to trying to
9780 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009781 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009782}
9783
Douglas Gregor063daf62009-03-13 18:40:31 +00009784/// \brief Create a binary operation that may resolve to an overloaded
9785/// operator.
9786///
9787/// \param OpLoc The location of the operator itself (e.g., '+').
9788///
9789/// \param OpcIn The BinaryOperator::Opcode that describes this
9790/// operator.
9791///
9792/// \param Functions The set of non-member functions that will be
9793/// considered by overload resolution. The caller needs to build this
9794/// set based on the context using, e.g.,
9795/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9796/// set should not contain any member functions; those will be added
9797/// by CreateOverloadedBinOp().
9798///
9799/// \param LHS Left-hand argument.
9800/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009801ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009802Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009803 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009804 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009805 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009806 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009807 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009808
9809 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9810 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9811 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9812
9813 // If either side is type-dependent, create an appropriate dependent
9814 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009815 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009816 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009817 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009818 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009819 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009820 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009821 Context.DependentTy,
9822 VK_RValue, OK_Ordinary,
9823 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009824
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009825 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9826 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009827 VK_LValue,
9828 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009829 Context.DependentTy,
9830 Context.DependentTy,
9831 OpLoc));
9832 }
John McCall6e266892010-01-26 03:27:55 +00009833
9834 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009835 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009836 // TODO: provide better source location info in DNLoc component.
9837 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009838 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009839 = UnresolvedLookupExpr::Create(Context, NamingClass,
9840 NestedNameSpecifierLoc(), OpNameInfo,
9841 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009842 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009843 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009844 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009845 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009846 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009847 OpLoc));
9848 }
9849
John McCall5acb0c92011-10-17 18:40:02 +00009850 // Always do placeholder-like conversions on the RHS.
9851 if (checkPlaceholderForOverload(*this, Args[1]))
9852 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009853
John McCall3c3b7f92011-10-25 17:37:35 +00009854 // Do placeholder-like conversion on the LHS; note that we should
9855 // not get here with a PseudoObject LHS.
9856 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009857 if (checkPlaceholderForOverload(*this, Args[0]))
9858 return ExprError();
9859
Sebastian Redl275c2b42009-11-18 23:10:33 +00009860 // If this is the assignment operator, we only perform overload resolution
9861 // if the left-hand side is a class or enumeration type. This is actually
9862 // a hack. The standard requires that we do overload resolution between the
9863 // various built-in candidates, but as DR507 points out, this can lead to
9864 // problems. So we do it this way, which pretty much follows what GCC does.
9865 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009866 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009867 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009868
John McCall0e800c92010-12-04 08:14:53 +00009869 // If this is the .* operator, which is not overloadable, just
9870 // create a built-in binary operator.
9871 if (Opc == BO_PtrMemD)
9872 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9873
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009874 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009875 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009876
9877 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009878 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009879
9880 // Add operator candidates that are member functions.
9881 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9882
John McCall6e266892010-01-26 03:27:55 +00009883 // Add candidates from ADL.
9884 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9885 Args, 2,
9886 /*ExplicitTemplateArgs*/ 0,
9887 CandidateSet);
9888
Douglas Gregor063daf62009-03-13 18:40:31 +00009889 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009890 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009891
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009892 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9893
Douglas Gregor063daf62009-03-13 18:40:31 +00009894 // Perform overload resolution.
9895 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009896 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00009897 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00009898 // We found a built-in operator or an overloaded operator.
9899 FunctionDecl *FnDecl = Best->Function;
9900
9901 if (FnDecl) {
9902 // We matched an overloaded operator. Build a call to that
9903 // operator.
9904
Eli Friedman5f2987c2012-02-02 03:46:19 +00009905 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009906
Douglas Gregor063daf62009-03-13 18:40:31 +00009907 // Convert the arguments.
9908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00009909 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00009910 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009911
Chandler Carruth6df868e2010-12-12 08:17:55 +00009912 ExprResult Arg1 =
9913 PerformCopyInitialization(
9914 InitializedEntity::InitializeParameter(Context,
9915 FnDecl->getParamDecl(0)),
9916 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009917 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009918 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009919
John Wiegley429bb272011-04-08 18:41:53 +00009920 ExprResult Arg0 =
9921 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9922 Best->FoundDecl, Method);
9923 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009924 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009925 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009926 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009927 } else {
9928 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00009929 ExprResult Arg0 = PerformCopyInitialization(
9930 InitializedEntity::InitializeParameter(Context,
9931 FnDecl->getParamDecl(0)),
9932 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009933 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009934 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009935
Chandler Carruth6df868e2010-12-12 08:17:55 +00009936 ExprResult Arg1 =
9937 PerformCopyInitialization(
9938 InitializedEntity::InitializeParameter(Context,
9939 FnDecl->getParamDecl(1)),
9940 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009941 if (Arg1.isInvalid())
9942 return ExprError();
9943 Args[0] = LHS = Arg0.takeAs<Expr>();
9944 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009945 }
9946
John McCallb697e082010-05-06 18:15:07 +00009947 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9948
John McCallf89e55a2010-11-18 06:31:45 +00009949 // Determine the result type.
9950 QualType ResultTy = FnDecl->getResultType();
9951 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9952 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00009953
9954 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009955 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9956 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009957 if (FnExpr.isInvalid())
9958 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00009959
John McCall9ae2f072010-08-23 23:25:46 +00009960 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009961 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009962 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009963
9964 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009965 FnDecl))
9966 return ExprError();
9967
John McCall9ae2f072010-08-23 23:25:46 +00009968 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00009969 } else {
9970 // We matched a built-in operator. Convert the arguments, then
9971 // break out so that we will build the appropriate built-in
9972 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009973 ExprResult ArgsRes0 =
9974 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9975 Best->Conversions[0], AA_Passing);
9976 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009977 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009978 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009979
John Wiegley429bb272011-04-08 18:41:53 +00009980 ExprResult ArgsRes1 =
9981 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9982 Best->Conversions[1], AA_Passing);
9983 if (ArgsRes1.isInvalid())
9984 return ExprError();
9985 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009986 break;
9987 }
9988 }
9989
Douglas Gregor33074752009-09-30 21:46:01 +00009990 case OR_No_Viable_Function: {
9991 // C++ [over.match.oper]p9:
9992 // If the operator is the operator , [...] and there are no
9993 // viable functions, then the operator is assumed to be the
9994 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00009995 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00009996 break;
9997
Chandler Carruth6df868e2010-12-12 08:17:55 +00009998 // For class as left operand for assignment or compound assigment
9999 // operator do not fall through to handling in built-in, but report that
10000 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010001 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010002 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010003 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010004 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10005 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010006 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010007 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010008 // This is an erroneous use of an operator which can be overloaded by
10009 // a non-member function. Check for non-member operators which were
10010 // defined too late to be candidates.
10011 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
10012 // FIXME: Recover by calling the found function.
10013 return ExprError();
10014
Douglas Gregor33074752009-09-30 21:46:01 +000010015 // No viable function; try to create a built-in operation, which will
10016 // produce an error. Then, show the non-viable candidates.
10017 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010018 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010019 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010020 "C++ binary operator overloading is missing candidates!");
10021 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +000010022 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10023 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010024 return move(Result);
10025 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010026
10027 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010028 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010029 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010030 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010031 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010032 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10033 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010034 return ExprError();
10035
10036 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010037 if (isImplicitlyDeleted(Best->Function)) {
10038 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10039 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10040 << getSpecialMember(Method)
10041 << BinaryOperator::getOpcodeStr(Opc)
10042 << getDeletedOrUnavailableSuffix(Best->Function);
10043
10044 if (Method->getParent()->isLambda()) {
10045 Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
10046 return ExprError();
10047 }
10048 } else {
10049 Diag(OpLoc, diag::err_ovl_deleted_oper)
10050 << Best->Function->isDeleted()
10051 << BinaryOperator::getOpcodeStr(Opc)
10052 << getDeletedOrUnavailableSuffix(Best->Function)
10053 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10054 }
Eli Friedman1795d372011-08-26 19:46:22 +000010055 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10056 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010057 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010058 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010059
Douglas Gregor33074752009-09-30 21:46:01 +000010060 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010061 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010062}
10063
John McCall60d7b3a2010-08-24 06:29:42 +000010064ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010065Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10066 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010067 Expr *Base, Expr *Idx) {
10068 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010069 DeclarationName OpName =
10070 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10071
10072 // If either side is type-dependent, create an appropriate dependent
10073 // expression.
10074 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10075
John McCallc373d482010-01-27 01:50:18 +000010076 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010077 // CHECKME: no 'operator' keyword?
10078 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10079 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010080 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010081 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010082 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010083 /*ADL*/ true, /*Overloaded*/ false,
10084 UnresolvedSetIterator(),
10085 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010086 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010087
Sebastian Redlf322ed62009-10-29 20:17:01 +000010088 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10089 Args, 2,
10090 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010091 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010092 RLoc));
10093 }
10094
John McCall5acb0c92011-10-17 18:40:02 +000010095 // Handle placeholders on both operands.
10096 if (checkPlaceholderForOverload(*this, Args[0]))
10097 return ExprError();
10098 if (checkPlaceholderForOverload(*this, Args[1]))
10099 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010100
Sebastian Redlf322ed62009-10-29 20:17:01 +000010101 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010102 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010103
10104 // Subscript can only be overloaded as a member function.
10105
10106 // Add operator candidates that are member functions.
10107 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10108
10109 // Add builtin operator candidates.
10110 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10111
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010112 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10113
Sebastian Redlf322ed62009-10-29 20:17:01 +000010114 // Perform overload resolution.
10115 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010116 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010117 case OR_Success: {
10118 // We found a built-in operator or an overloaded operator.
10119 FunctionDecl *FnDecl = Best->Function;
10120
10121 if (FnDecl) {
10122 // We matched an overloaded operator. Build a call to that
10123 // operator.
10124
Eli Friedman5f2987c2012-02-02 03:46:19 +000010125 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010126
John McCall9aa472c2010-03-19 07:35:19 +000010127 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010128 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010129
Sebastian Redlf322ed62009-10-29 20:17:01 +000010130 // Convert the arguments.
10131 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010132 ExprResult Arg0 =
10133 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10134 Best->FoundDecl, Method);
10135 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010136 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010137 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010138
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010139 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010140 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010141 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010142 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010143 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010144 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010145 Owned(Args[1]));
10146 if (InputInit.isInvalid())
10147 return ExprError();
10148
10149 Args[1] = InputInit.takeAs<Expr>();
10150
Sebastian Redlf322ed62009-10-29 20:17:01 +000010151 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010152 QualType ResultTy = FnDecl->getResultType();
10153 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10154 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010155
10156 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010157 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10158 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010159 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10160 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010161 OpLocInfo.getLoc(),
10162 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010163 if (FnExpr.isInvalid())
10164 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010165
John McCall9ae2f072010-08-23 23:25:46 +000010166 CXXOperatorCallExpr *TheCall =
10167 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010168 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010169 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010170
John McCall9ae2f072010-08-23 23:25:46 +000010171 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010172 FnDecl))
10173 return ExprError();
10174
John McCall9ae2f072010-08-23 23:25:46 +000010175 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010176 } else {
10177 // We matched a built-in operator. Convert the arguments, then
10178 // break out so that we will build the appropriate built-in
10179 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010180 ExprResult ArgsRes0 =
10181 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10182 Best->Conversions[0], AA_Passing);
10183 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010184 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010185 Args[0] = ArgsRes0.take();
10186
10187 ExprResult ArgsRes1 =
10188 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10189 Best->Conversions[1], AA_Passing);
10190 if (ArgsRes1.isInvalid())
10191 return ExprError();
10192 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010193
10194 break;
10195 }
10196 }
10197
10198 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010199 if (CandidateSet.empty())
10200 Diag(LLoc, diag::err_ovl_no_oper)
10201 << Args[0]->getType() << /*subscript*/ 0
10202 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10203 else
10204 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10205 << Args[0]->getType()
10206 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010207 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10208 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010209 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010210 }
10211
10212 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010213 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010214 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010215 << Args[0]->getType() << Args[1]->getType()
10216 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010217 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10218 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010219 return ExprError();
10220
10221 case OR_Deleted:
10222 Diag(LLoc, diag::err_ovl_deleted_oper)
10223 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010224 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010225 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010226 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10227 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010228 return ExprError();
10229 }
10230
10231 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010232 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010233}
10234
Douglas Gregor88a35142008-12-22 05:46:06 +000010235/// BuildCallToMemberFunction - Build a call to a member
10236/// function. MemExpr is the expression that refers to the member
10237/// function (and includes the object parameter), Args/NumArgs are the
10238/// arguments to the function call (not including the object
10239/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010240/// expression refers to a non-static member function or an overloaded
10241/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010242ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010243Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10244 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010245 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010246 assert(MemExprE->getType() == Context.BoundMemberTy ||
10247 MemExprE->getType() == Context.OverloadTy);
10248
Douglas Gregor88a35142008-12-22 05:46:06 +000010249 // Dig out the member expression. This holds both the object
10250 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010251 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010252
John McCall864c0412011-04-26 20:42:42 +000010253 // Determine whether this is a call to a pointer-to-member function.
10254 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10255 assert(op->getType() == Context.BoundMemberTy);
10256 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10257
10258 QualType fnType =
10259 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10260
10261 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10262 QualType resultType = proto->getCallResultType(Context);
10263 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10264
10265 // Check that the object type isn't more qualified than the
10266 // member function we're calling.
10267 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10268
10269 QualType objectType = op->getLHS()->getType();
10270 if (op->getOpcode() == BO_PtrMemI)
10271 objectType = objectType->castAs<PointerType>()->getPointeeType();
10272 Qualifiers objectQuals = objectType.getQualifiers();
10273
10274 Qualifiers difference = objectQuals - funcQuals;
10275 difference.removeObjCGCAttr();
10276 difference.removeAddressSpace();
10277 if (difference) {
10278 std::string qualsString = difference.getAsString();
10279 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10280 << fnType.getUnqualifiedType()
10281 << qualsString
10282 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10283 }
10284
10285 CXXMemberCallExpr *call
10286 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10287 resultType, valueKind, RParenLoc);
10288
10289 if (CheckCallReturnType(proto->getResultType(),
10290 op->getRHS()->getSourceRange().getBegin(),
10291 call, 0))
10292 return ExprError();
10293
10294 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10295 return ExprError();
10296
10297 return MaybeBindToTemporary(call);
10298 }
10299
John McCall5acb0c92011-10-17 18:40:02 +000010300 UnbridgedCastsSet UnbridgedCasts;
10301 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10302 return ExprError();
10303
John McCall129e2df2009-11-30 22:42:35 +000010304 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010305 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010306 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010307 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010308 if (isa<MemberExpr>(NakedMemExpr)) {
10309 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010310 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010311 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010312 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010313 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010314 } else {
10315 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010316 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010317
John McCall701c89e2009-12-03 04:06:58 +000010318 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010319 Expr::Classification ObjectClassification
10320 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10321 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010322
Douglas Gregor88a35142008-12-22 05:46:06 +000010323 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010324 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010325
John McCallaa81e162009-12-01 22:10:20 +000010326 // FIXME: avoid copy.
10327 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10328 if (UnresExpr->hasExplicitTemplateArgs()) {
10329 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10330 TemplateArgs = &TemplateArgsBuffer;
10331 }
10332
John McCall129e2df2009-11-30 22:42:35 +000010333 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10334 E = UnresExpr->decls_end(); I != E; ++I) {
10335
John McCall701c89e2009-12-03 04:06:58 +000010336 NamedDecl *Func = *I;
10337 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10338 if (isa<UsingShadowDecl>(Func))
10339 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10340
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010341
Francois Pichetdbee3412011-01-18 05:04:39 +000010342 // Microsoft supports direct constructor calls.
Francois Pichet62ec1f22011-09-17 17:15:52 +000010343 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichetdbee3412011-01-18 05:04:39 +000010344 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
10345 CandidateSet);
10346 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010347 // If explicit template arguments were provided, we can't call a
10348 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010349 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010350 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010351
John McCall9aa472c2010-03-19 07:35:19 +000010352 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010353 ObjectClassification,
10354 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010355 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010356 } else {
John McCall129e2df2009-11-30 22:42:35 +000010357 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010358 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010359 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010360 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010361 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010362 }
Douglas Gregordec06662009-08-21 18:42:58 +000010363 }
Mike Stump1eb44332009-09-09 15:08:12 +000010364
John McCall129e2df2009-11-30 22:42:35 +000010365 DeclarationName DeclName = UnresExpr->getMemberName();
10366
John McCall5acb0c92011-10-17 18:40:02 +000010367 UnbridgedCasts.restore();
10368
Douglas Gregor88a35142008-12-22 05:46:06 +000010369 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010370 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010371 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010372 case OR_Success:
10373 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010374 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010375 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010376 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010377 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010378 break;
10379
10380 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010381 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010382 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010383 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010384 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +000010385 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010386 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010387
10388 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010389 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010390 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010391 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +000010392 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010393 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010394
10395 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010396 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010397 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010398 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010399 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010400 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010401 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010402 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010403 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010404 }
10405
John McCall6bb80172010-03-30 21:47:33 +000010406 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010407
John McCallaa81e162009-12-01 22:10:20 +000010408 // If overload resolution picked a static member, build a
10409 // non-member call based on that function.
10410 if (Method->isStatic()) {
10411 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10412 Args, NumArgs, RParenLoc);
10413 }
10414
John McCall129e2df2009-11-30 22:42:35 +000010415 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010416 }
10417
John McCallf89e55a2010-11-18 06:31:45 +000010418 QualType ResultType = Method->getResultType();
10419 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10420 ResultType = ResultType.getNonLValueExprType(Context);
10421
Douglas Gregor88a35142008-12-22 05:46:06 +000010422 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010423 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010424 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010425 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010426
Anders Carlssoneed3e692009-10-10 00:06:20 +000010427 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010428 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010429 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010430 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010431
Douglas Gregor88a35142008-12-22 05:46:06 +000010432 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010433 // We only need to do this if there was actually an overload; otherwise
10434 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010435 if (!Method->isStatic()) {
10436 ExprResult ObjectArg =
10437 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10438 FoundDecl, Method);
10439 if (ObjectArg.isInvalid())
10440 return ExprError();
10441 MemExpr->setBase(ObjectArg.take());
10442 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010443
10444 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010445 const FunctionProtoType *Proto =
10446 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010447 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010448 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010449 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010450
Eli Friedmane61eb042012-02-18 04:48:30 +000010451 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10452
John McCall9ae2f072010-08-23 23:25:46 +000010453 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +000010454 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010455
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010456 if ((isa<CXXConstructorDecl>(CurContext) ||
10457 isa<CXXDestructorDecl>(CurContext)) &&
10458 TheCall->getMethodDecl()->isPure()) {
10459 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10460
Chandler Carruthae198062011-06-27 08:31:58 +000010461 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010462 Diag(MemExpr->getLocStart(),
10463 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10464 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10465 << MD->getParent()->getDeclName();
10466
10467 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010468 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010469 }
John McCall9ae2f072010-08-23 23:25:46 +000010470 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010471}
10472
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010473/// BuildCallToObjectOfClassType - Build a call to an object of class
10474/// type (C++ [over.call.object]), which can end up invoking an
10475/// overloaded function call operator (@c operator()) or performing a
10476/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010477ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010478Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010479 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010480 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010481 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010482 if (checkPlaceholderForOverload(*this, Obj))
10483 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010484 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010485
10486 UnbridgedCastsSet UnbridgedCasts;
10487 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10488 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010489
John Wiegley429bb272011-04-08 18:41:53 +000010490 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10491 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010492
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010493 // C++ [over.call.object]p1:
10494 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010495 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010496 // candidate functions includes at least the function call
10497 // operators of T. The function call operators of T are obtained by
10498 // ordinary lookup of the name operator() in the context of
10499 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010500 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010501 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010502
John Wiegley429bb272011-04-08 18:41:53 +000010503 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +000010504 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010505 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010506 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010507
John McCalla24dc2e2009-11-17 02:14:36 +000010508 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10509 LookupQualifiedName(R, Record->getDecl());
10510 R.suppressDiagnostics();
10511
Douglas Gregor593564b2009-11-15 07:48:03 +000010512 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010513 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010514 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10515 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010516 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010517 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010518
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010519 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010520 // In addition, for each (non-explicit in C++0x) conversion function
10521 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010522 //
10523 // operator conversion-type-id () cv-qualifier;
10524 //
10525 // where cv-qualifier is the same cv-qualification as, or a
10526 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010527 // denotes the type "pointer to function of (P1,...,Pn) returning
10528 // R", or the type "reference to pointer to function of
10529 // (P1,...,Pn) returning R", or the type "reference to function
10530 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010531 // is also considered as a candidate function. Similarly,
10532 // surrogate call functions are added to the set of candidate
10533 // functions for each conversion function declared in an
10534 // accessible base class provided the function is not hidden
10535 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010536 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010537 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010538 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010539 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010540 NamedDecl *D = *I;
10541 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10542 if (isa<UsingShadowDecl>(D))
10543 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010544
Douglas Gregor4a27d702009-10-21 06:18:39 +000010545 // Skip over templated conversion functions; they aren't
10546 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010547 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010548 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010549
John McCall701c89e2009-12-03 04:06:58 +000010550 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010551 if (!Conv->isExplicit()) {
10552 // Strip the reference type (if any) and then the pointer type (if
10553 // any) to get down to what might be a function type.
10554 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10555 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10556 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010557
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010558 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10559 {
10560 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10561 Object.get(), Args, NumArgs, CandidateSet);
10562 }
10563 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010564 }
Mike Stump1eb44332009-09-09 15:08:12 +000010565
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010566 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10567
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010568 // Perform overload resolution.
10569 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010570 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010571 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010572 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010573 // Overload resolution succeeded; we'll build the appropriate call
10574 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010575 break;
10576
10577 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010578 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +000010579 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
10580 << Object.get()->getType() << /*call*/ 1
10581 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010582 else
John Wiegley429bb272011-04-08 18:41:53 +000010583 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +000010584 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010585 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010586 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010587 break;
10588
10589 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +000010590 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010591 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010592 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010593 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010594 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010595
10596 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +000010597 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010598 diag::err_ovl_deleted_object_call)
10599 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010600 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010601 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010602 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010603 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010604 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010605 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010606
Douglas Gregorff331c12010-07-25 18:17:45 +000010607 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010608 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010609
John McCall5acb0c92011-10-17 18:40:02 +000010610 UnbridgedCasts.restore();
10611
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010612 if (Best->Function == 0) {
10613 // Since there is no function declaration, this is one of the
10614 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010615 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010616 = cast<CXXConversionDecl>(
10617 Best->Conversions[0].UserDefined.ConversionFunction);
10618
John Wiegley429bb272011-04-08 18:41:53 +000010619 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010620 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010621
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010622 // We selected one of the surrogate functions that converts the
10623 // object parameter to a function pointer. Perform the conversion
10624 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010625
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010626 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010627 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010628 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10629 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010630 if (Call.isInvalid())
10631 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010632 // Record usage of conversion in an implicit cast.
10633 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10634 CK_UserDefinedConversion,
10635 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010636
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010637 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010638 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010639 }
10640
Eli Friedman5f2987c2012-02-02 03:46:19 +000010641 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010642 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010643 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010644
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010645 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10646 // that calls this method, using Object for the implicit object
10647 // parameter and passing along the remaining arguments.
10648 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010649 const FunctionProtoType *Proto =
10650 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010651
10652 unsigned NumArgsInProto = Proto->getNumArgs();
10653 unsigned NumArgsToCheck = NumArgs;
10654
10655 // Build the full argument list for the method call (the
10656 // implicit object parameter is placed at the beginning of the
10657 // list).
10658 Expr **MethodArgs;
10659 if (NumArgs < NumArgsInProto) {
10660 NumArgsToCheck = NumArgsInProto;
10661 MethodArgs = new Expr*[NumArgsInProto + 1];
10662 } else {
10663 MethodArgs = new Expr*[NumArgs + 1];
10664 }
John Wiegley429bb272011-04-08 18:41:53 +000010665 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010666 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10667 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010668
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010669 DeclarationNameInfo OpLocInfo(
10670 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10671 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010672 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010673 HadMultipleCandidates,
10674 OpLocInfo.getLoc(),
10675 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010676 if (NewFn.isInvalid())
10677 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010678
10679 // Once we've built TheCall, all of the expressions are properly
10680 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010681 QualType ResultTy = Method->getResultType();
10682 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10683 ResultTy = ResultTy.getNonLValueExprType(Context);
10684
John McCall9ae2f072010-08-23 23:25:46 +000010685 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010686 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010687 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010688 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010689 delete [] MethodArgs;
10690
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010691 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010692 Method))
10693 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010694
Douglas Gregor518fda12009-01-13 05:10:00 +000010695 // We may have default arguments. If so, we need to allocate more
10696 // slots in the call for them.
10697 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010698 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010699 else if (NumArgs > NumArgsInProto)
10700 NumArgsToCheck = NumArgsInProto;
10701
Chris Lattner312531a2009-04-12 08:11:20 +000010702 bool IsError = false;
10703
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010704 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010705 ExprResult ObjRes =
10706 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10707 Best->FoundDecl, Method);
10708 if (ObjRes.isInvalid())
10709 IsError = true;
10710 else
10711 Object = move(ObjRes);
10712 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010713
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010714 // Check the argument types.
10715 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010716 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010717 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010718 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010719
Douglas Gregor518fda12009-01-13 05:10:00 +000010720 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010721
John McCall60d7b3a2010-08-24 06:29:42 +000010722 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010723 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010724 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010725 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010726 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010727
Anders Carlsson3faa4862010-01-29 18:43:53 +000010728 IsError |= InputInit.isInvalid();
10729 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010730 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010731 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010732 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10733 if (DefArg.isInvalid()) {
10734 IsError = true;
10735 break;
10736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010737
Douglas Gregord47c47d2009-11-09 19:27:57 +000010738 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010739 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010740
10741 TheCall->setArg(i + 1, Arg);
10742 }
10743
10744 // If this is a variadic call, handle args passed through "...".
10745 if (Proto->isVariadic()) {
10746 // Promote the arguments (C99 6.5.2.2p7).
10747 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010748 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10749 IsError |= Arg.isInvalid();
10750 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010751 }
10752 }
10753
Chris Lattner312531a2009-04-12 08:11:20 +000010754 if (IsError) return true;
10755
Eli Friedmane61eb042012-02-18 04:48:30 +000010756 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10757
John McCall9ae2f072010-08-23 23:25:46 +000010758 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010759 return true;
10760
John McCall182f7092010-08-24 06:09:16 +000010761 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010762}
10763
Douglas Gregor8ba10742008-11-20 16:27:02 +000010764/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010765/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010766/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010767ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010768Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010769 assert(Base->getType()->isRecordType() &&
10770 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010771
John McCall5acb0c92011-10-17 18:40:02 +000010772 if (checkPlaceholderForOverload(*this, Base))
10773 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010774
John McCall5769d612010-02-08 23:07:23 +000010775 SourceLocation Loc = Base->getExprLoc();
10776
Douglas Gregor8ba10742008-11-20 16:27:02 +000010777 // C++ [over.ref]p1:
10778 //
10779 // [...] An expression x->m is interpreted as (x.operator->())->m
10780 // for a class object x of type T if T::operator->() exists and if
10781 // the operator is selected as the best match function by the
10782 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010783 DeclarationName OpName =
10784 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010785 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010786 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010787
John McCall5769d612010-02-08 23:07:23 +000010788 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +000010789 PDiag(diag::err_typecheck_incomplete_tag)
10790 << Base->getSourceRange()))
10791 return ExprError();
10792
John McCalla24dc2e2009-11-17 02:14:36 +000010793 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10794 LookupQualifiedName(R, BaseRecord->getDecl());
10795 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010796
10797 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010798 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010799 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10800 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010801 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010802
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010803 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10804
Douglas Gregor8ba10742008-11-20 16:27:02 +000010805 // Perform overload resolution.
10806 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010807 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010808 case OR_Success:
10809 // Overload resolution succeeded; we'll build the call below.
10810 break;
10811
10812 case OR_No_Viable_Function:
10813 if (CandidateSet.empty())
10814 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010815 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010816 else
10817 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010818 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010819 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010820 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010821
10822 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010823 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10824 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010825 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010826 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010827
10828 case OR_Deleted:
10829 Diag(OpLoc, diag::err_ovl_deleted_oper)
10830 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010831 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010832 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010833 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010834 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010835 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010836 }
10837
Eli Friedman5f2987c2012-02-02 03:46:19 +000010838 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010839 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010840 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010841
Douglas Gregor8ba10742008-11-20 16:27:02 +000010842 // Convert the object parameter.
10843 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010844 ExprResult BaseResult =
10845 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10846 Best->FoundDecl, Method);
10847 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010848 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010849 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010850
Douglas Gregor8ba10742008-11-20 16:27:02 +000010851 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010852 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010853 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010854 if (FnExpr.isInvalid())
10855 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010856
John McCallf89e55a2010-11-18 06:31:45 +000010857 QualType ResultTy = Method->getResultType();
10858 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10859 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010860 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010861 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010862 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010863
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010864 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010865 Method))
10866 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010867
10868 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010869}
10870
Douglas Gregor904eed32008-11-10 20:40:00 +000010871/// FixOverloadedFunctionReference - E is an expression that refers to
10872/// a C++ overloaded function (possibly with some parentheses and
10873/// perhaps a '&' around it). We have resolved the overloaded function
10874/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000010875/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000010876Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000010877 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000010878 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010879 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10880 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010881 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010882 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010883
Douglas Gregor699ee522009-11-20 19:42:02 +000010884 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010885 }
10886
Douglas Gregor699ee522009-11-20 19:42:02 +000010887 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010888 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10889 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010890 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000010891 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000010892 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000010893 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000010894 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010895 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010896
10897 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000010898 ICE->getCastKind(),
10899 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000010900 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010901 }
10902
Douglas Gregor699ee522009-11-20 19:42:02 +000010903 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000010904 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000010905 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000010906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10907 if (Method->isStatic()) {
10908 // Do nothing: static member functions aren't any different
10909 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000010910 } else {
John McCallf7a1a742009-11-24 19:00:30 +000010911 // Fix the sub expression, which really has to be an
10912 // UnresolvedLookupExpr holding an overloaded member function
10913 // or template.
John McCall6bb80172010-03-30 21:47:33 +000010914 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10915 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000010916 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010917 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000010918
John McCallba135432009-11-21 08:51:07 +000010919 assert(isa<DeclRefExpr>(SubExpr)
10920 && "fixed to something other than a decl ref");
10921 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10922 && "fixed to a member ref with no nested name qualifier");
10923
10924 // We have taken the address of a pointer to member
10925 // function. Perform the computation here so that we get the
10926 // appropriate pointer to member type.
10927 QualType ClassType
10928 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10929 QualType MemPtrType
10930 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10931
John McCallf89e55a2010-11-18 06:31:45 +000010932 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10933 VK_RValue, OK_Ordinary,
10934 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000010935 }
10936 }
John McCall6bb80172010-03-30 21:47:33 +000010937 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10938 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010939 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010940 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010941
John McCall2de56d12010-08-25 11:45:40 +000010942 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000010943 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000010944 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000010945 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010946 }
John McCallba135432009-11-21 08:51:07 +000010947
10948 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000010949 // FIXME: avoid copy.
10950 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000010951 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000010952 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10953 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000010954 }
10955
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010956 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10957 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010958 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010959 Fn,
10960 ULE->getNameLoc(),
10961 Fn->getType(),
10962 VK_LValue,
10963 Found.getDecl(),
10964 TemplateArgs);
10965 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10966 return DRE;
John McCallba135432009-11-21 08:51:07 +000010967 }
10968
John McCall129e2df2009-11-30 22:42:35 +000010969 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000010970 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000010971 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10972 if (MemExpr->hasExplicitTemplateArgs()) {
10973 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10974 TemplateArgs = &TemplateArgsBuffer;
10975 }
John McCalld5532b62009-11-23 01:53:49 +000010976
John McCallaa81e162009-12-01 22:10:20 +000010977 Expr *Base;
10978
John McCallf89e55a2010-11-18 06:31:45 +000010979 // If we're filling in a static method where we used to have an
10980 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000010981 if (MemExpr->isImplicitAccess()) {
10982 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010983 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10984 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010985 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010986 Fn,
10987 MemExpr->getMemberLoc(),
10988 Fn->getType(),
10989 VK_LValue,
10990 Found.getDecl(),
10991 TemplateArgs);
10992 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10993 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000010994 } else {
10995 SourceLocation Loc = MemExpr->getMemberLoc();
10996 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000010997 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000010998 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000010999 Base = new (Context) CXXThisExpr(Loc,
11000 MemExpr->getBaseType(),
11001 /*isImplicit=*/true);
11002 }
John McCallaa81e162009-12-01 22:10:20 +000011003 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011004 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011005
John McCallf5307512011-04-27 00:36:17 +000011006 ExprValueKind valueKind;
11007 QualType type;
11008 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11009 valueKind = VK_LValue;
11010 type = Fn->getType();
11011 } else {
11012 valueKind = VK_RValue;
11013 type = Context.BoundMemberTy;
11014 }
11015
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011016 MemberExpr *ME = MemberExpr::Create(Context, Base,
11017 MemExpr->isArrow(),
11018 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011019 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011020 Fn,
11021 Found,
11022 MemExpr->getMemberNameInfo(),
11023 TemplateArgs,
11024 type, valueKind, OK_Ordinary);
11025 ME->setHadMultipleCandidates(true);
11026 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011027 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011028
John McCall3fa5cae2010-10-26 07:05:15 +000011029 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011030}
11031
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011032ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011033 DeclAccessPair Found,
11034 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011035 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011036}
11037
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011038} // end namespace clang