blob: bdc25ba39c2c9b33704c020da6f6979846957c86 [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"
Richard Smithb8590f32012-05-07 09:03:25 +000031#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000033#include <algorithm>
34
35namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000036using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000037
John McCallf89e55a2010-11-18 06:31:45 +000038/// A convenience routine for creating a decayed reference to a
39/// function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000042 SourceLocation Loc = SourceLocation(),
43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000044 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000045 VK_LValue, Loc, LocInfo);
46 if (HadMultipleCandidates)
47 DRE->setHadMultipleCandidates(true);
48 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000049 E = S.DefaultFunctionArrayConversion(E.take());
50 if (E.isInvalid())
51 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000052 return E;
John McCallf89e55a2010-11-18 06:31:45 +000053}
54
John McCall120d63c2010-08-24 20:38:10 +000055static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000057 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000058 bool CStyle,
59 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000060
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000061static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
62 QualType &ToType,
63 bool InOverloadResolution,
64 StandardConversionSequence &SCS,
65 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000066static OverloadingResult
67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
68 UserDefinedConversionSequence& User,
69 OverloadCandidateSet& Conversions,
70 bool AllowExplicit);
71
72
73static ImplicitConversionSequence::CompareKind
74CompareStandardConversionSequences(Sema &S,
75 const StandardConversionSequence& SCS1,
76 const StandardConversionSequence& SCS2);
77
78static ImplicitConversionSequence::CompareKind
79CompareQualificationConversions(Sema &S,
80 const StandardConversionSequence& SCS1,
81 const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareDerivedToBaseConversions(Sema &S,
85 const StandardConversionSequence& SCS1,
86 const StandardConversionSequence& SCS2);
87
88
89
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000090/// GetConversionCategory - Retrieve the implicit conversion
91/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000092ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000093GetConversionCategory(ImplicitConversionKind Kind) {
94 static const ImplicitConversionCategory
95 Category[(int)ICK_Num_Conversion_Kinds] = {
96 ICC_Identity,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000100 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 ICC_Qualification_Adjustment,
102 ICC_Promotion,
103 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 ICC_Promotion,
105 ICC_Conversion,
106 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000112 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000113 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000114 ICC_Conversion,
115 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000116 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 ICC_Conversion
118 };
119 return Category[(int)Kind];
120}
121
122/// GetConversionRank - Retrieve the implicit conversion rank
123/// corresponding to the given implicit conversion kind.
124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
125 static const ImplicitConversionRank
126 Rank[(int)ICK_Num_Conversion_Kinds] = {
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000132 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 ICR_Promotion,
134 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000135 ICR_Promotion,
136 ICR_Conversion,
137 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 ICR_Conversion,
146 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000147 ICR_Complex_Real_Conversion,
148 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000149 ICR_Conversion,
150 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000163 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000167 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000168 "Integral conversion",
169 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000170 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000174 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000175 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000176 "Derived-to-base conversion",
177 "Vector conversion",
178 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000182 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183 };
184 return Name[Kind];
185}
186
Douglas Gregor60d62c22008-10-31 16:23:19 +0000187/// StandardConversionSequence - Set the standard conversion
188/// sequence to the identity conversion.
189void StandardConversionSequence::setAsIdentityConversion() {
190 First = ICK_Identity;
191 Second = ICK_Identity;
192 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000193 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000194 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000195 ReferenceBinding = false;
196 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000197 IsLvalueReference = true;
198 BindsToFunctionLvalue = false;
199 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000200 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000201 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000203}
204
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205/// getRank - Retrieve the rank of this standard conversion sequence
206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207/// implicit conversions.
208ImplicitConversionRank StandardConversionSequence::getRank() const {
209 ImplicitConversionRank Rank = ICR_Exact_Match;
210 if (GetConversionRank(First) > Rank)
211 Rank = GetConversionRank(First);
212 if (GetConversionRank(Second) > Rank)
213 Rank = GetConversionRank(Second);
214 if (GetConversionRank(Third) > Rank)
215 Rank = GetConversionRank(Third);
216 return Rank;
217}
218
219/// isPointerConversionToBool - Determines whether this conversion is
220/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000221/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000222/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000223bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000224 // Note that FromType has not necessarily been transformed by the
225 // array-to-pointer or function-to-pointer implicit conversions, so
226 // check for their presence as well as checking whether FromType is
227 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000228 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000229 (getFromType()->isPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000232 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000243bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000244StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000245isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000246 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000247 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
Douglas Gregorf9af5242011-04-15 20:45:44 +0000255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
266 switch (ICE->getCastKind()) {
267 case CK_NoOp:
268 case CK_IntegralCast:
269 case CK_IntegralToBoolean:
270 case CK_IntegralToFloating:
271 case CK_FloatingToIntegral:
272 case CK_FloatingToBoolean:
273 case CK_FloatingCast:
274 Converted = ICE->getSubExpr();
275 continue;
276
277 default:
278 return Converted;
279 }
280 }
281
282 return Converted;
283}
284
285/// Check if this standard conversion sequence represents a narrowing
286/// conversion, according to C++11 [dcl.init.list]p7.
287///
288/// \param Ctx The AST context.
289/// \param Converted The result of applying this standard conversion sequence.
290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
291/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
293/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000294NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000297 APValue &ConstantValue,
298 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000300
301 // C++11 [dcl.init.list]p7:
302 // A narrowing conversion is an implicit conversion ...
303 QualType FromType = getToType(0);
304 QualType ToType = getToType(1);
305 switch (Second) {
306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314 return NK_Type_Narrowing;
315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316 llvm::APSInt IntConstantValue;
317 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318 if (Initializer &&
319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320 // Convert the integer to the floating type.
321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323 llvm::APFloat::rmNearestTiesToEven);
324 // And back.
325 llvm::APSInt ConvertedValue = IntConstantValue;
326 bool ignored;
327 Result.convertToInteger(ConvertedValue,
328 llvm::APFloat::rmTowardZero, &ignored);
329 // If the resulting value is different, this was a narrowing conversion.
330 if (IntConstantValue != ConvertedValue) {
331 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000332 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000333 return NK_Constant_Narrowing;
334 }
335 } else {
336 // Variables are always narrowings.
337 return NK_Variable_Narrowing;
338 }
339 }
340 return NK_Not_Narrowing;
341
342 // -- from long double to double or float, or from double to float, except
343 // where the source is a constant expression and the actual value after
344 // conversion is within the range of values that can be represented (even
345 // if it cannot be represented exactly), or
346 case ICK_Floating_Conversion:
347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349 // FromType is larger than ToType.
350 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352 // Constant!
353 assert(ConstantValue.isFloat());
354 llvm::APFloat FloatVal = ConstantValue.getFloat();
355 // Convert the source value into the target type.
356 bool ignored;
357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358 Ctx.getFloatTypeSemantics(ToType),
359 llvm::APFloat::rmNearestTiesToEven, &ignored);
360 // If there was no overflow, the source value is within the range of
361 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000362 if (ConvertStatus & llvm::APFloat::opOverflow) {
363 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000364 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000365 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000366 } else {
367 return NK_Variable_Narrowing;
368 }
369 }
370 return NK_Not_Narrowing;
371
372 // -- from an integer type or unscoped enumeration type to an integer type
373 // that cannot represent all the values of the original type, except where
374 // the source is a constant expression and the actual value after
375 // conversion will fit into the target type and will produce the original
376 // value when converted back to the original type.
377 case ICK_Boolean_Conversion: // Bools are integers too.
378 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379 // Boolean conversions can be from pointers and pointers to members
380 // [conv.bool], and those aren't considered narrowing conversions.
381 return NK_Not_Narrowing;
382 } // Otherwise, fall through to the integral case.
383 case ICK_Integral_Conversion: {
384 assert(FromType->isIntegralOrUnscopedEnumerationType());
385 assert(ToType->isIntegralOrUnscopedEnumerationType());
386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387 const unsigned FromWidth = Ctx.getIntWidth(FromType);
388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389 const unsigned ToWidth = Ctx.getIntWidth(ToType);
390
391 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000392 (FromWidth == ToWidth && FromSigned != ToSigned) ||
393 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000394 // Not all values of FromType can be represented in ToType.
395 llvm::APSInt InitializerValue;
396 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
398 // Such conversions on variables are always narrowing.
399 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000400 }
401 bool Narrowing = false;
402 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000403 // Negative -> unsigned is narrowing. Otherwise, more bits is never
404 // narrowing.
405 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000406 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000407 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000408 // Add a bit to the InitializerValue so we don't have to worry about
409 // signed vs. unsigned comparisons.
410 InitializerValue = InitializerValue.extend(
411 InitializerValue.getBitWidth() + 1);
412 // Convert the initializer to and from the target width and signed-ness.
413 llvm::APSInt ConvertedValue = InitializerValue;
414 ConvertedValue = ConvertedValue.trunc(ToWidth);
415 ConvertedValue.setIsSigned(ToSigned);
416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
417 ConvertedValue.setIsSigned(InitializerValue.isSigned());
418 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000419 if (ConvertedValue != InitializerValue)
420 Narrowing = true;
421 }
422 if (Narrowing) {
423 ConstantType = Initializer->getType();
424 ConstantValue = APValue(InitializerValue);
425 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000426 }
427 }
428 return NK_Not_Narrowing;
429 }
430
431 default:
432 // Other kinds of conversions are not narrowings.
433 return NK_Not_Narrowing;
434 }
435}
436
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000437/// DebugPrint - Print this standard conversion sequence to standard
438/// error. Useful for debugging overloading issues.
439void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000440 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000441 bool PrintedSomething = false;
442 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000443 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000444 PrintedSomething = true;
445 }
446
447 if (Second != ICK_Identity) {
448 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000449 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000451 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000452
453 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000455 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000457 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000458 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000459 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Third != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
474}
475
476/// DebugPrint - Print this user-defined conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 if (Before.First || Before.Second || Before.Third) {
481 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000482 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000484 if (ConversionFunction)
485 OS << '\'' << *ConversionFunction << '\'';
486 else
487 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 After.DebugPrint();
491 }
492}
493
494/// DebugPrint - Print this implicit conversion sequence to standard
495/// error. Useful for debugging overloading issues.
496void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000497 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498 switch (ConversionKind) {
499 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000500 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501 Standard.DebugPrint();
502 break;
503 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000504 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 UserDefined.DebugPrint();
506 break;
507 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000508 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509 break;
John McCall1d318332010-01-12 00:44:57 +0000510 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000511 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000512 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000514 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 break;
516 }
517
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519}
520
John McCall1d318332010-01-12 00:44:57 +0000521void AmbiguousConversionSequence::construct() {
522 new (&conversions()) ConversionSet();
523}
524
525void AmbiguousConversionSequence::destruct() {
526 conversions().~ConversionSet();
527}
528
529void
530AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
531 FromTypePtr = O.FromTypePtr;
532 ToTypePtr = O.ToTypePtr;
533 new (&conversions()) ConversionSet(O.conversions());
534}
535
Douglas Gregora9333192010-05-08 17:41:32 +0000536namespace {
537 // Structure used by OverloadCandidate::DeductionFailureInfo to store
538 // template parameter and template argument information.
539 struct DFIParamWithArguments {
540 TemplateParameter Param;
541 TemplateArgument FirstArg;
542 TemplateArgument SecondArg;
543 };
544}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000545
Douglas Gregora9333192010-05-08 17:41:32 +0000546/// \brief Convert from Sema's representation of template deduction information
547/// to the form used in overload-candidate information.
548OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000549static MakeDeductionFailureInfo(ASTContext &Context,
550 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000551 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000552 OverloadCandidate::DeductionFailureInfo Result;
553 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000554 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000555 Result.Data = 0;
556 switch (TDK) {
557 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000558 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000559 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000560 case Sema::TDK_TooManyArguments:
561 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000562 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000565 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000566 Result.Data = Info.Param.getOpaqueValue();
567 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora9333192010-05-08 17:41:32 +0000569 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000570 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000571 // FIXME: Should allocate from normal heap so that we can free this later.
572 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000573 Saved->Param = Info.Param;
574 Saved->FirstArg = Info.FirstArg;
575 Saved->SecondArg = Info.SecondArg;
576 Result.Data = Saved;
577 break;
578 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579
Douglas Gregora9333192010-05-08 17:41:32 +0000580 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000581 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000582 if (Info.hasSFINAEDiagnostic()) {
583 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
584 SourceLocation(), PartialDiagnostic::NullDiagnostic());
585 Info.takeSFINAEDiagnostic(*Diag);
586 Result.HasDiagnostic = true;
587 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589
Douglas Gregora9333192010-05-08 17:41:32 +0000590 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000591 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000592 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000593 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594
Douglas Gregora9333192010-05-08 17:41:32 +0000595 return Result;
596}
John McCall1d318332010-01-12 00:44:57 +0000597
Douglas Gregora9333192010-05-08 17:41:32 +0000598void OverloadCandidate::DeductionFailureInfo::Destroy() {
599 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
600 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000601 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000602 case Sema::TDK_InstantiationDepth:
603 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000604 case Sema::TDK_TooManyArguments:
605 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000606 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000607 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000608
Douglas Gregora9333192010-05-08 17:41:32 +0000609 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000610 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000611 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000612 Data = 0;
613 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000614
615 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000616 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000617 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000618 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
619 Diag->~PartialDiagnosticAt();
620 HasDiagnostic = false;
621 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000622 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000624 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000625 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000626 case Sema::TDK_FailedOverloadResolution:
627 break;
628 }
629}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000630
Richard Smithb8590f32012-05-07 09:03:25 +0000631PartialDiagnosticAt *
632OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
633 if (HasDiagnostic)
634 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
635 return 0;
636}
637
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000638TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000639OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000642 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000643 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000646 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000647 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648
Douglas Gregora9333192010-05-08 17:41:32 +0000649 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000650 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000651 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000652
653 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000654 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000655 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000656
Douglas Gregora9333192010-05-08 17:41:32 +0000657 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000658 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000659 case Sema::TDK_FailedOverloadResolution:
660 break;
661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000662
Douglas Gregora9333192010-05-08 17:41:32 +0000663 return TemplateParameter();
664}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665
Douglas Gregorec20f462010-05-08 20:07:26 +0000666TemplateArgumentList *
667OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000670 case Sema::TDK_Invalid:
Douglas Gregorec20f462010-05-08 20:07:26 +0000671 case Sema::TDK_InstantiationDepth:
672 case Sema::TDK_TooManyArguments:
673 case Sema::TDK_TooFewArguments:
674 case Sema::TDK_Incomplete:
675 case Sema::TDK_InvalidExplicitArguments:
676 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000677 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000678 return 0;
679
680 case Sema::TDK_SubstitutionFailure:
681 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682
Douglas Gregorec20f462010-05-08 20:07:26 +0000683 // Unhandled
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
686 break;
687 }
688
689 return 0;
690}
691
Douglas Gregora9333192010-05-08 17:41:32 +0000692const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
694 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000695 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000696 case Sema::TDK_InstantiationDepth:
697 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000698 case Sema::TDK_TooManyArguments:
699 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000700 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000701 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000702 return 0;
703
Douglas Gregora9333192010-05-08 17:41:32 +0000704 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000705 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000706 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000707
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000708 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000709 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000710 case Sema::TDK_FailedOverloadResolution:
711 break;
712 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713
Douglas Gregora9333192010-05-08 17:41:32 +0000714 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715}
Douglas Gregora9333192010-05-08 17:41:32 +0000716
717const TemplateArgument *
718OverloadCandidate::DeductionFailureInfo::getSecondArg() {
719 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
720 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000721 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000722 case Sema::TDK_InstantiationDepth:
723 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000724 case Sema::TDK_TooManyArguments:
725 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000726 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000727 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000728 return 0;
729
Douglas Gregora9333192010-05-08 17:41:32 +0000730 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000731 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000732 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
733
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000734 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000735 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 case Sema::TDK_FailedOverloadResolution:
737 break;
738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000739
Douglas Gregora9333192010-05-08 17:41:32 +0000740 return 0;
741}
742
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000743void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000744 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000745 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
746 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000747 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
748 i->DeductionFailure.Destroy();
749 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000750}
751
752void OverloadCandidateSet::clear() {
753 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000754 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000755 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000756 Functions.clear();
757}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000758
John McCall5acb0c92011-10-17 18:40:02 +0000759namespace {
760 class UnbridgedCastsSet {
761 struct Entry {
762 Expr **Addr;
763 Expr *Saved;
764 };
765 SmallVector<Entry, 2> Entries;
766
767 public:
768 void save(Sema &S, Expr *&E) {
769 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
770 Entry entry = { &E, E };
771 Entries.push_back(entry);
772 E = S.stripARCUnbridgedCast(E);
773 }
774
775 void restore() {
776 for (SmallVectorImpl<Entry>::iterator
777 i = Entries.begin(), e = Entries.end(); i != e; ++i)
778 *i->Addr = i->Saved;
779 }
780 };
781}
782
783/// checkPlaceholderForOverload - Do any interesting placeholder-like
784/// preprocessing on the given expression.
785///
786/// \param unbridgedCasts a collection to which to add unbridged casts;
787/// without this, they will be immediately diagnosed as errors
788///
789/// Return true on unrecoverable error.
790static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
791 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000792 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
793 // We can't handle overloaded expressions here because overload
794 // resolution might reasonably tweak them.
795 if (placeholder->getKind() == BuiltinType::Overload) return false;
796
797 // If the context potentially accepts unbridged ARC casts, strip
798 // the unbridged cast and add it to the collection for later restoration.
799 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
800 unbridgedCasts) {
801 unbridgedCasts->save(S, E);
802 return false;
803 }
804
805 // Go ahead and check everything else.
806 ExprResult result = S.CheckPlaceholderExpr(E);
807 if (result.isInvalid())
808 return true;
809
810 E = result.take();
811 return false;
812 }
813
814 // Nothing to do.
815 return false;
816}
817
818/// checkArgPlaceholdersForOverload - Check a set of call operands for
819/// placeholders.
820static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
821 unsigned numArgs,
822 UnbridgedCastsSet &unbridged) {
823 for (unsigned i = 0; i != numArgs; ++i)
824 if (checkPlaceholderForOverload(S, args[i], &unbridged))
825 return true;
826
827 return false;
828}
829
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000830// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000831// overload of the declarations in Old. This routine returns false if
832// New and Old cannot be overloaded, e.g., if New has the same
833// signature as some function in Old (C++ 1.3.10) or if the Old
834// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000835// it does return false, MatchedDecl will point to the decl that New
836// cannot be overloaded with. This decl may be a UsingShadowDecl on
837// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000838//
839// Example: Given the following input:
840//
841// void f(int, float); // #1
842// void f(int, int); // #2
843// int f(int, int); // #3
844//
845// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000846// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000847//
John McCall51fa86f2009-12-02 08:47:38 +0000848// When we process #2, Old contains only the FunctionDecl for #1. By
849// comparing the parameter types, we see that #1 and #2 are overloaded
850// (since they have different signatures), so this routine returns
851// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000852//
John McCall51fa86f2009-12-02 08:47:38 +0000853// When we process #3, Old is an overload set containing #1 and #2. We
854// compare the signatures of #3 to #1 (they're overloaded, so we do
855// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
856// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000857// signature), IsOverload returns false and MatchedDecl will be set to
858// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000859//
860// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
861// into a class by a using declaration. The rules for whether to hide
862// shadow declarations ignore some properties which otherwise figure
863// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000864Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000865Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
866 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000867 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000868 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000869 NamedDecl *OldD = *I;
870
871 bool OldIsUsingDecl = false;
872 if (isa<UsingShadowDecl>(OldD)) {
873 OldIsUsingDecl = true;
874
875 // We can always introduce two using declarations into the same
876 // context, even if they have identical signatures.
877 if (NewIsUsingDecl) continue;
878
879 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
880 }
881
882 // If either declaration was introduced by a using declaration,
883 // we'll need to use slightly different rules for matching.
884 // Essentially, these rules are the normal rules, except that
885 // function templates hide function templates with different
886 // return types or template parameter lists.
887 bool UseMemberUsingDeclRules =
888 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
889
John McCall51fa86f2009-12-02 08:47:38 +0000890 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000891 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
892 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
893 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
894 continue;
895 }
896
John McCall871b2e72009-12-09 03:35:25 +0000897 Match = *I;
898 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000899 }
John McCall51fa86f2009-12-02 08:47:38 +0000900 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000901 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
902 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
903 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
904 continue;
905 }
906
John McCall871b2e72009-12-09 03:35:25 +0000907 Match = *I;
908 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000909 }
John McCalld7945c62010-11-10 03:01:53 +0000910 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000911 // We can overload with these, which can show up when doing
912 // redeclaration checks for UsingDecls.
913 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000914 } else if (isa<TagDecl>(OldD)) {
915 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000916 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
917 // Optimistically assume that an unresolved using decl will
918 // overload; if it doesn't, we'll have to diagnose during
919 // template instantiation.
920 } else {
John McCall68263142009-11-18 22:49:29 +0000921 // (C++ 13p1):
922 // Only function declarations can be overloaded; object and type
923 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000924 Match = *I;
925 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000926 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000927 }
John McCall68263142009-11-18 22:49:29 +0000928
John McCall871b2e72009-12-09 03:35:25 +0000929 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000930}
931
John McCallad00b772010-06-16 08:42:20 +0000932bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
933 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000934 // If both of the functions are extern "C", then they are not
935 // overloads.
936 if (Old->isExternC() && New->isExternC())
937 return false;
938
John McCall68263142009-11-18 22:49:29 +0000939 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
940 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
941
942 // C++ [temp.fct]p2:
943 // A function template can be overloaded with other function templates
944 // and with normal (non-template) functions.
945 if ((OldTemplate == 0) != (NewTemplate == 0))
946 return true;
947
948 // Is the function New an overload of the function Old?
949 QualType OldQType = Context.getCanonicalType(Old->getType());
950 QualType NewQType = Context.getCanonicalType(New->getType());
951
952 // Compare the signatures (C++ 1.3.10) of the two functions to
953 // determine whether they are overloads. If we find any mismatch
954 // in the signature, they are overloads.
955
956 // If either of these functions is a K&R-style function (no
957 // prototype), then we consider them to have matching signatures.
958 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
959 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
960 return false;
961
John McCallf4c73712011-01-19 06:33:43 +0000962 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
963 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000964
965 // The signature of a function includes the types of its
966 // parameters (C++ 1.3.10), which includes the presence or absence
967 // of the ellipsis; see C++ DR 357).
968 if (OldQType != NewQType &&
969 (OldType->getNumArgs() != NewType->getNumArgs() ||
970 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000971 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000972 return true;
973
974 // C++ [temp.over.link]p4:
975 // The signature of a function template consists of its function
976 // signature, its return type and its template parameter list. The names
977 // of the template parameters are significant only for establishing the
978 // relationship between the template parameters and the rest of the
979 // signature.
980 //
981 // We check the return type and template parameter lists for function
982 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000983 //
984 // However, we don't consider either of these when deciding whether
985 // a member introduced by a shadow declaration is hidden.
986 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000987 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
988 OldTemplate->getTemplateParameters(),
989 false, TPL_TemplateMatch) ||
990 OldType->getResultType() != NewType->getResultType()))
991 return true;
992
993 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000994 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000995 //
996 // As part of this, also check whether one of the member functions
997 // is static, in which case they are not overloads (C++
998 // 13.1p2). While not part of the definition of the signature,
999 // this check is important to determine whether these functions
1000 // can be overloaded.
1001 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1002 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1003 if (OldMethod && NewMethod &&
1004 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001005 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +00001006 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1007 if (!UseUsingDeclRules &&
1008 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1009 (OldMethod->getRefQualifier() == RQ_None ||
1010 NewMethod->getRefQualifier() == RQ_None)) {
1011 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001012 // - Member function declarations with the same name and the same
1013 // parameter-type-list as well as member function template
1014 // declarations with the same name, the same parameter-type-list, and
1015 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +00001016 // them, but not all, have a ref-qualifier (8.3.5).
1017 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1018 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1019 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1020 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001021
John McCall68263142009-11-18 22:49:29 +00001022 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001023 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001024
John McCall68263142009-11-18 22:49:29 +00001025 // The signatures match; this is not an overload.
1026 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001027}
1028
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001029/// \brief Checks availability of the function depending on the current
1030/// function context. Inside an unavailable function, unavailability is ignored.
1031///
1032/// \returns true if \arg FD is unavailable and current context is inside
1033/// an available function, false otherwise.
1034bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1035 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1036}
1037
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001038/// \brief Tries a user-defined conversion from From to ToType.
1039///
1040/// Produces an implicit conversion sequence for when a standard conversion
1041/// is not an option. See TryImplicitConversion for more information.
1042static ImplicitConversionSequence
1043TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1044 bool SuppressUserConversions,
1045 bool AllowExplicit,
1046 bool InOverloadResolution,
1047 bool CStyle,
1048 bool AllowObjCWritebackConversion) {
1049 ImplicitConversionSequence ICS;
1050
1051 if (SuppressUserConversions) {
1052 // We're not in the case above, so there is no conversion that
1053 // we can perform.
1054 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1055 return ICS;
1056 }
1057
1058 // Attempt user-defined conversion.
1059 OverloadCandidateSet Conversions(From->getExprLoc());
1060 OverloadingResult UserDefResult
1061 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1062 AllowExplicit);
1063
1064 if (UserDefResult == OR_Success) {
1065 ICS.setUserDefined();
1066 // C++ [over.ics.user]p4:
1067 // A conversion of an expression of class type to the same class
1068 // type is given Exact Match rank, and a conversion of an
1069 // expression of class type to a base class of that type is
1070 // given Conversion rank, in spite of the fact that a copy
1071 // constructor (i.e., a user-defined conversion function) is
1072 // called for those cases.
1073 if (CXXConstructorDecl *Constructor
1074 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1075 QualType FromCanon
1076 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1077 QualType ToCanon
1078 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1079 if (Constructor->isCopyConstructor() &&
1080 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1081 // Turn this into a "standard" conversion sequence, so that it
1082 // gets ranked with standard conversion sequences.
1083 ICS.setStandard();
1084 ICS.Standard.setAsIdentityConversion();
1085 ICS.Standard.setFromType(From->getType());
1086 ICS.Standard.setAllToTypes(ToType);
1087 ICS.Standard.CopyConstructor = Constructor;
1088 if (ToCanon != FromCanon)
1089 ICS.Standard.Second = ICK_Derived_To_Base;
1090 }
1091 }
1092
1093 // C++ [over.best.ics]p4:
1094 // However, when considering the argument of a user-defined
1095 // conversion function that is a candidate by 13.3.1.3 when
1096 // invoked for the copying of the temporary in the second step
1097 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1098 // 13.3.1.6 in all cases, only standard conversion sequences and
1099 // ellipsis conversion sequences are allowed.
1100 if (SuppressUserConversions && ICS.isUserDefined()) {
1101 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1102 }
1103 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1104 ICS.setAmbiguous();
1105 ICS.Ambiguous.setFromType(From->getType());
1106 ICS.Ambiguous.setToType(ToType);
1107 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1108 Cand != Conversions.end(); ++Cand)
1109 if (Cand->Viable)
1110 ICS.Ambiguous.addConversion(Cand->Function);
1111 } else {
1112 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1113 }
1114
1115 return ICS;
1116}
1117
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001118/// TryImplicitConversion - Attempt to perform an implicit conversion
1119/// from the given expression (Expr) to the given type (ToType). This
1120/// function returns an implicit conversion sequence that can be used
1121/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001122///
1123/// void f(float f);
1124/// void g(int i) { f(i); }
1125///
1126/// this routine would produce an implicit conversion sequence to
1127/// describe the initialization of f from i, which will be a standard
1128/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1129/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1130//
1131/// Note that this routine only determines how the conversion can be
1132/// performed; it does not actually perform the conversion. As such,
1133/// it will not produce any diagnostics if no conversion is available,
1134/// but will instead return an implicit conversion sequence of kind
1135/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001136///
1137/// If @p SuppressUserConversions, then user-defined conversions are
1138/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001139/// If @p AllowExplicit, then explicit user-defined conversions are
1140/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001141///
1142/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1143/// writeback conversion, which allows __autoreleasing id* parameters to
1144/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001145static ImplicitConversionSequence
1146TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1147 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001148 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001149 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001150 bool CStyle,
1151 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001153 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001154 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001155 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001156 return ICS;
1157 }
1158
David Blaikie4e4d0842012-03-11 07:00:24 +00001159 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001160 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001161 return ICS;
1162 }
1163
Douglas Gregor604eb652010-08-11 02:15:33 +00001164 // C++ [over.ics.user]p4:
1165 // A conversion of an expression of class type to the same class
1166 // type is given Exact Match rank, and a conversion of an
1167 // expression of class type to a base class of that type is
1168 // given Conversion rank, in spite of the fact that a copy/move
1169 // constructor (i.e., a user-defined conversion function) is
1170 // called for those cases.
1171 QualType FromType = From->getType();
1172 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001173 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1174 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001175 ICS.setStandard();
1176 ICS.Standard.setAsIdentityConversion();
1177 ICS.Standard.setFromType(FromType);
1178 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001179
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001180 // We don't actually check at this point whether there is a valid
1181 // copy/move constructor, since overloading just assumes that it
1182 // exists. When we actually perform initialization, we'll find the
1183 // appropriate constructor to copy the returned object, if needed.
1184 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001185
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001186 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001187 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001188 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001189
Douglas Gregor604eb652010-08-11 02:15:33 +00001190 return ICS;
1191 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001192
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001193 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1194 AllowExplicit, InOverloadResolution, CStyle,
1195 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001196}
1197
John McCallf85e1932011-06-15 23:02:42 +00001198ImplicitConversionSequence
1199Sema::TryImplicitConversion(Expr *From, QualType ToType,
1200 bool SuppressUserConversions,
1201 bool AllowExplicit,
1202 bool InOverloadResolution,
1203 bool CStyle,
1204 bool AllowObjCWritebackConversion) {
1205 return clang::TryImplicitConversion(*this, From, ToType,
1206 SuppressUserConversions, AllowExplicit,
1207 InOverloadResolution, CStyle,
1208 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001209}
1210
Douglas Gregor575c63a2010-04-16 22:27:05 +00001211/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001212/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001213/// converted expression. Flavor is the kind of conversion we're
1214/// performing, used in the error message. If @p AllowExplicit,
1215/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001216ExprResult
1217Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001218 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001219 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001220 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001221}
1222
John Wiegley429bb272011-04-08 18:41:53 +00001223ExprResult
1224Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001225 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001226 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001227 if (checkPlaceholderForOverload(*this, From))
1228 return ExprError();
1229
John McCallf85e1932011-06-15 23:02:42 +00001230 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1231 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001232 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001233 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001234
John McCall120d63c2010-08-24 20:38:10 +00001235 ICS = clang::TryImplicitConversion(*this, From, ToType,
1236 /*SuppressUserConversions=*/false,
1237 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001238 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001239 /*CStyle=*/false,
1240 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001241 return PerformImplicitConversion(From, ToType, ICS, Action);
1242}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001243
1244/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001245/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001246bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1247 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001248 if (Context.hasSameUnqualifiedType(FromType, ToType))
1249 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250
John McCall00ccbef2010-12-21 00:44:39 +00001251 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1252 // where F adds one of the following at most once:
1253 // - a pointer
1254 // - a member pointer
1255 // - a block pointer
1256 CanQualType CanTo = Context.getCanonicalType(ToType);
1257 CanQualType CanFrom = Context.getCanonicalType(FromType);
1258 Type::TypeClass TyClass = CanTo->getTypeClass();
1259 if (TyClass != CanFrom->getTypeClass()) return false;
1260 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1261 if (TyClass == Type::Pointer) {
1262 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1263 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1264 } else if (TyClass == Type::BlockPointer) {
1265 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1266 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1267 } else if (TyClass == Type::MemberPointer) {
1268 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1269 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1270 } else {
1271 return false;
1272 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001273
John McCall00ccbef2010-12-21 00:44:39 +00001274 TyClass = CanTo->getTypeClass();
1275 if (TyClass != CanFrom->getTypeClass()) return false;
1276 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1277 return false;
1278 }
1279
1280 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1281 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1282 if (!EInfo.getNoReturn()) return false;
1283
1284 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1285 assert(QualType(FromFn, 0).isCanonical());
1286 if (QualType(FromFn, 0) != CanTo) return false;
1287
1288 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001289 return true;
1290}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001291
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001292/// \brief Determine whether the conversion from FromType to ToType is a valid
1293/// vector conversion.
1294///
1295/// \param ICK Will be set to the vector conversion kind, if this is a vector
1296/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001297static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1298 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001299 // We need at least one of these types to be a vector type to have a vector
1300 // conversion.
1301 if (!ToType->isVectorType() && !FromType->isVectorType())
1302 return false;
1303
1304 // Identical types require no conversions.
1305 if (Context.hasSameUnqualifiedType(FromType, ToType))
1306 return false;
1307
1308 // There are no conversions between extended vector types, only identity.
1309 if (ToType->isExtVectorType()) {
1310 // There are no conversions between extended vector types other than the
1311 // identity conversion.
1312 if (FromType->isExtVectorType())
1313 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001314
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001315 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001316 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001317 ICK = ICK_Vector_Splat;
1318 return true;
1319 }
1320 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001321
1322 // We can perform the conversion between vector types in the following cases:
1323 // 1)vector types are equivalent AltiVec and GCC vector types
1324 // 2)lax vector conversions are permitted and the vector types are of the
1325 // same size
1326 if (ToType->isVectorType() && FromType->isVectorType()) {
1327 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001328 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001329 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001330 ICK = ICK_Vector_Conversion;
1331 return true;
1332 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001333 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001334
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001335 return false;
1336}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001337
Douglas Gregor7d000652012-04-12 20:48:09 +00001338static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1339 bool InOverloadResolution,
1340 StandardConversionSequence &SCS,
1341 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001342
Douglas Gregor60d62c22008-10-31 16:23:19 +00001343/// IsStandardConversion - Determines whether there is a standard
1344/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1345/// expression From to the type ToType. Standard conversion sequences
1346/// only consider non-class types; for conversions that involve class
1347/// types, use TryImplicitConversion. If a conversion exists, SCS will
1348/// contain the standard conversion sequence required to perform this
1349/// conversion and this routine will return true. Otherwise, this
1350/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001351static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1352 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001353 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001354 bool CStyle,
1355 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001356 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001357
Douglas Gregor60d62c22008-10-31 16:23:19 +00001358 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001359 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001360 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001361 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001362 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001363 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001364
Douglas Gregorf9201e02009-02-11 23:02:49 +00001365 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001366 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001367 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001368 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001369 return false;
1370
Mike Stump1eb44332009-09-09 15:08:12 +00001371 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001372 }
1373
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001374 // The first conversion can be an lvalue-to-rvalue conversion,
1375 // array-to-pointer conversion, or function-to-pointer conversion
1376 // (C++ 4p1).
1377
John McCall120d63c2010-08-24 20:38:10 +00001378 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001379 DeclAccessPair AccessPair;
1380 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001381 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001382 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001383 // We were able to resolve the address of the overloaded function,
1384 // so we can convert to the type of that function.
1385 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001386
1387 // we can sometimes resolve &foo<int> regardless of ToType, so check
1388 // if the type matches (identity) or we are converting to bool
1389 if (!S.Context.hasSameUnqualifiedType(
1390 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1391 QualType resultTy;
1392 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001393 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001394 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1395 // otherwise, only a boolean conversion is standard
1396 if (!ToType->isBooleanType())
1397 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001399
Chandler Carruth90434232011-03-29 08:08:18 +00001400 // Check if the "from" expression is taking the address of an overloaded
1401 // function and recompute the FromType accordingly. Take advantage of the
1402 // fact that non-static member functions *must* have such an address-of
1403 // expression.
1404 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1405 if (Method && !Method->isStatic()) {
1406 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1407 "Non-unary operator on non-static member address");
1408 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1409 == UO_AddrOf &&
1410 "Non-address-of operator on non-static member address");
1411 const Type *ClassType
1412 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1413 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001414 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1415 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1416 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001417 "Non-address-of operator for overloaded function expression");
1418 FromType = S.Context.getPointerType(FromType);
1419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001420
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001421 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001422 assert(S.Context.hasSameType(
1423 FromType,
1424 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001425 } else {
1426 return false;
1427 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001428 }
John McCall21480112011-08-30 00:57:29 +00001429 // Lvalue-to-rvalue conversion (C++11 4.1):
1430 // A glvalue (3.10) of a non-function, non-array type T can
1431 // be converted to a prvalue.
1432 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001433 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001434 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001435 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001436 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001437
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001438 // C11 6.3.2.1p2:
1439 // ... if the lvalue has atomic type, the value has the non-atomic version
1440 // of the type of the lvalue ...
1441 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1442 FromType = Atomic->getValueType();
1443
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001444 // If T is a non-class type, the type of the rvalue is the
1445 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001446 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1447 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001448 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001449 } else if (FromType->isArrayType()) {
1450 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001451 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001452
1453 // An lvalue or rvalue of type "array of N T" or "array of unknown
1454 // bound of T" can be converted to an rvalue of type "pointer to
1455 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001456 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001457
John McCall120d63c2010-08-24 20:38:10 +00001458 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001459 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001460 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001461
1462 // For the purpose of ranking in overload resolution
1463 // (13.3.3.1.1), this conversion is considered an
1464 // array-to-pointer conversion followed by a qualification
1465 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001466 SCS.Second = ICK_Identity;
1467 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001468 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001469 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001470 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001471 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001472 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001473 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001474 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001475
1476 // An lvalue of function type T can be converted to an rvalue of
1477 // type "pointer to T." The result is a pointer to the
1478 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001479 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001480 } else {
1481 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001482 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001483 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001484 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001485
1486 // The second conversion can be an integral promotion, floating
1487 // point promotion, integral conversion, floating point conversion,
1488 // floating-integral conversion, pointer conversion,
1489 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001490 // For overloading in C, this can also be a "compatible-type"
1491 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001492 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001493 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001494 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001495 // The unqualified versions of the types are the same: there's no
1496 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001497 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001498 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001499 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001502 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001503 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001504 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001506 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001507 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001508 SCS.Second = ICK_Complex_Promotion;
1509 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001510 } else if (ToType->isBooleanType() &&
1511 (FromType->isArithmeticType() ||
1512 FromType->isAnyPointerType() ||
1513 FromType->isBlockPointerType() ||
1514 FromType->isMemberPointerType() ||
1515 FromType->isNullPtrType())) {
1516 // Boolean conversions (C++ 4.12).
1517 SCS.Second = ICK_Boolean_Conversion;
1518 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001519 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001520 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001521 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001523 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001524 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001525 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001526 SCS.Second = ICK_Complex_Conversion;
1527 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001528 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1529 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001530 // Complex-real conversions (C99 6.3.1.7)
1531 SCS.Second = ICK_Complex_Real;
1532 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001533 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001534 // Floating point conversions (C++ 4.8).
1535 SCS.Second = ICK_Floating_Conversion;
1536 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001537 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001538 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001539 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001540 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001541 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001542 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001543 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001544 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001545 SCS.Second = ICK_Block_Pointer_Conversion;
1546 } else if (AllowObjCWritebackConversion &&
1547 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1548 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001549 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1550 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001551 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001552 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001553 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001554 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001556 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001557 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001558 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001559 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001560 SCS.Second = SecondICK;
1561 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001562 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001563 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001564 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001565 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001566 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001567 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001568 // Treat a conversion that strips "noreturn" as an identity conversion.
1569 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001570 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1571 InOverloadResolution,
1572 SCS, CStyle)) {
1573 SCS.Second = ICK_TransparentUnionConversion;
1574 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001575 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1576 CStyle)) {
1577 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001578 // appropriately.
1579 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001580 } else {
1581 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001582 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001583 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001584 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001585
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001586 QualType CanonFrom;
1587 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001588 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001589 bool ObjCLifetimeConversion;
1590 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1591 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001592 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001593 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001594 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001595 CanonFrom = S.Context.getCanonicalType(FromType);
1596 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001597 } else {
1598 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001599 SCS.Third = ICK_Identity;
1600
Mike Stump1eb44332009-09-09 15:08:12 +00001601 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001602 // [...] Any difference in top-level cv-qualification is
1603 // subsumed by the initialization itself and does not constitute
1604 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001605 CanonFrom = S.Context.getCanonicalType(FromType);
1606 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001607 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001608 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001609 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001610 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1611 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001612 FromType = ToType;
1613 CanonFrom = CanonTo;
1614 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001615 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001616 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001617
1618 // If we have not converted the argument type to the parameter type,
1619 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001620 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001621 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001622
Douglas Gregor60d62c22008-10-31 16:23:19 +00001623 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001624}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001625
1626static bool
1627IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1628 QualType &ToType,
1629 bool InOverloadResolution,
1630 StandardConversionSequence &SCS,
1631 bool CStyle) {
1632
1633 const RecordType *UT = ToType->getAsUnionType();
1634 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1635 return false;
1636 // The field to initialize within the transparent union.
1637 RecordDecl *UD = UT->getDecl();
1638 // It's compatible if the expression matches any of the fields.
1639 for (RecordDecl::field_iterator it = UD->field_begin(),
1640 itend = UD->field_end();
1641 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001642 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1643 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001644 ToType = it->getType();
1645 return true;
1646 }
1647 }
1648 return false;
1649}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001650
1651/// IsIntegralPromotion - Determines whether the conversion from the
1652/// expression From (whose potentially-adjusted type is FromType) to
1653/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1654/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001655bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001656 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001657 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001658 if (!To) {
1659 return false;
1660 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001661
1662 // An rvalue of type char, signed char, unsigned char, short int, or
1663 // unsigned short int can be converted to an rvalue of type int if
1664 // int can represent all the values of the source type; otherwise,
1665 // the source rvalue can be converted to an rvalue of type unsigned
1666 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001667 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1668 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001669 if (// We can promote any signed, promotable integer type to an int
1670 (FromType->isSignedIntegerType() ||
1671 // We can promote any unsigned integer type whose size is
1672 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001673 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001674 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001675 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001676 }
1677
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001678 return To->getKind() == BuiltinType::UInt;
1679 }
1680
Richard Smithe7ff9192012-09-13 21:18:54 +00001681 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001682 // A prvalue of an unscoped enumeration type whose underlying type is not
1683 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1684 // following types that can represent all the values of the enumeration
1685 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1686 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001687 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001688 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001689 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690 // with lowest integer conversion rank (4.13) greater than the rank of long
1691 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001692 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001693 // C++11 [conv.prom]p4:
1694 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1695 // can be converted to a prvalue of its underlying type. Moreover, if
1696 // integral promotion can be applied to its underlying type, a prvalue of an
1697 // unscoped enumeration type whose underlying type is fixed can also be
1698 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001699 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1700 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1701 // provided for a scoped enumeration.
1702 if (FromEnumType->getDecl()->isScoped())
1703 return false;
1704
Richard Smithe7ff9192012-09-13 21:18:54 +00001705 // We can perform an integral promotion to the underlying type of the enum,
1706 // even if that's not the promoted type.
1707 if (FromEnumType->getDecl()->isFixed()) {
1708 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1709 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1710 IsIntegralPromotion(From, Underlying, ToType);
1711 }
1712
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001713 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001714 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001715 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001716 return Context.hasSameUnqualifiedType(ToType,
1717 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001718 }
John McCall842aef82009-12-09 09:09:27 +00001719
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001720 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001721 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1722 // to an rvalue a prvalue of the first of the following types that can
1723 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001724 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001725 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001726 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001727 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001728 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001729 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001730 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001731 // Determine whether the type we're converting from is signed or
1732 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001733 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001734 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001736 // The types we'll try to promote to, in the appropriate
1737 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001738 QualType PromoteTypes[6] = {
1739 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001740 Context.LongTy, Context.UnsignedLongTy ,
1741 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001742 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001743 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001744 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1745 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001746 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001747 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1748 // We found the type that we can promote to. If this is the
1749 // type we wanted, we have a promotion. Otherwise, no
1750 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001751 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001752 }
1753 }
1754 }
1755
1756 // An rvalue for an integral bit-field (9.6) can be converted to an
1757 // rvalue of type int if int can represent all the values of the
1758 // bit-field; otherwise, it can be converted to unsigned int if
1759 // unsigned int can represent all the values of the bit-field. If
1760 // the bit-field is larger yet, no integral promotion applies to
1761 // it. If the bit-field has an enumerated type, it is treated as any
1762 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001763 // FIXME: We should delay checking of bit-fields until we actually perform the
1764 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001765 using llvm::APSInt;
1766 if (From)
1767 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001768 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001769 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001770 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1771 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1772 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Douglas Gregor86f19402008-12-20 23:49:58 +00001774 // Are we promoting to an int from a bitfield that fits in an int?
1775 if (BitWidth < ToSize ||
1776 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1777 return To->getKind() == BuiltinType::Int;
1778 }
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Douglas Gregor86f19402008-12-20 23:49:58 +00001780 // Are we promoting to an unsigned int from an unsigned bitfield
1781 // that fits into an unsigned int?
1782 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1783 return To->getKind() == BuiltinType::UInt;
1784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Douglas Gregor86f19402008-12-20 23:49:58 +00001786 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001787 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001790 // An rvalue of type bool can be converted to an rvalue of type int,
1791 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001792 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001793 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001794 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001795
1796 return false;
1797}
1798
1799/// IsFloatingPointPromotion - Determines whether the conversion from
1800/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1801/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001802bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001803 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1804 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001805 /// An rvalue of type float can be converted to an rvalue of type
1806 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807 if (FromBuiltin->getKind() == BuiltinType::Float &&
1808 ToBuiltin->getKind() == BuiltinType::Double)
1809 return true;
1810
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001811 // C99 6.3.1.5p1:
1812 // When a float is promoted to double or long double, or a
1813 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001814 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001815 (FromBuiltin->getKind() == BuiltinType::Float ||
1816 FromBuiltin->getKind() == BuiltinType::Double) &&
1817 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1818 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001819
1820 // Half can be promoted to float.
1821 if (FromBuiltin->getKind() == BuiltinType::Half &&
1822 ToBuiltin->getKind() == BuiltinType::Float)
1823 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001824 }
1825
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001826 return false;
1827}
1828
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001829/// \brief Determine if a conversion is a complex promotion.
1830///
1831/// A complex promotion is defined as a complex -> complex conversion
1832/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001833/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001834bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001835 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001836 if (!FromComplex)
1837 return false;
1838
John McCall183700f2009-09-21 23:43:11 +00001839 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001840 if (!ToComplex)
1841 return false;
1842
1843 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001844 ToComplex->getElementType()) ||
1845 IsIntegralPromotion(0, FromComplex->getElementType(),
1846 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001847}
1848
Douglas Gregorcb7de522008-11-26 23:31:11 +00001849/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1850/// the pointer type FromPtr to a pointer to type ToPointee, with the
1851/// same type qualifiers as FromPtr has on its pointee type. ToType,
1852/// if non-empty, will be a pointer to ToType that may or may not have
1853/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001854///
Mike Stump1eb44332009-09-09 15:08:12 +00001855static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001856BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001857 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001858 ASTContext &Context,
1859 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001860 assert((FromPtr->getTypeClass() == Type::Pointer ||
1861 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1862 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863
John McCallf85e1932011-06-15 23:02:42 +00001864 /// Conversions to 'id' subsume cv-qualifier conversions.
1865 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001866 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001867
1868 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001869 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001870 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001871 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001872
John McCallf85e1932011-06-15 23:02:42 +00001873 if (StripObjCLifetime)
1874 Quals.removeObjCLifetime();
1875
Mike Stump1eb44332009-09-09 15:08:12 +00001876 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001877 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001878 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001879 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001880 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001881
1882 // Build a pointer to ToPointee. It has the right qualifiers
1883 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001884 if (isa<ObjCObjectPointerType>(ToType))
1885 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001886 return Context.getPointerType(ToPointee);
1887 }
1888
1889 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001890 QualType QualifiedCanonToPointee
1891 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001892
Douglas Gregorda80f742010-12-01 21:43:58 +00001893 if (isa<ObjCObjectPointerType>(ToType))
1894 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1895 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001896}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001897
Mike Stump1eb44332009-09-09 15:08:12 +00001898static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001899 bool InOverloadResolution,
1900 ASTContext &Context) {
1901 // Handle value-dependent integral null pointer constants correctly.
1902 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1903 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001904 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001905 return !InOverloadResolution;
1906
Douglas Gregorce940492009-09-25 04:25:58 +00001907 return Expr->isNullPointerConstant(Context,
1908 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1909 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001910}
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001912/// IsPointerConversion - Determines whether the conversion of the
1913/// expression From, which has the (possibly adjusted) type FromType,
1914/// can be converted to the type ToType via a pointer conversion (C++
1915/// 4.10). If so, returns true and places the converted type (that
1916/// might differ from ToType in its cv-qualifiers at some level) into
1917/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001918///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001919/// This routine also supports conversions to and from block pointers
1920/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1921/// pointers to interfaces. FIXME: Once we've determined the
1922/// appropriate overloading rules for Objective-C, we may want to
1923/// split the Objective-C checks into a different routine; however,
1924/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001925/// conversions, so for now they live here. IncompatibleObjC will be
1926/// set if the conversion is an allowed Objective-C conversion that
1927/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001928bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001929 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001930 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001931 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001932 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001933 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1934 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001935 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001936
Mike Stump1eb44332009-09-09 15:08:12 +00001937 // Conversion from a null pointer constant to any Objective-C pointer type.
1938 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001939 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001940 ConvertedType = ToType;
1941 return true;
1942 }
1943
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001944 // Blocks: Block pointers can be converted to void*.
1945 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001946 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001947 ConvertedType = ToType;
1948 return true;
1949 }
1950 // Blocks: A null pointer constant can be converted to a block
1951 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001952 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001953 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001954 ConvertedType = ToType;
1955 return true;
1956 }
1957
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001958 // If the left-hand-side is nullptr_t, the right side can be a null
1959 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001960 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001961 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001962 ConvertedType = ToType;
1963 return true;
1964 }
1965
Ted Kremenek6217b802009-07-29 21:53:49 +00001966 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001967 if (!ToTypePtr)
1968 return false;
1969
1970 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001971 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001972 ConvertedType = ToType;
1973 return true;
1974 }
Sebastian Redl07779722008-10-31 14:43:28 +00001975
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001976 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001977 // , including objective-c pointers.
1978 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001979 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001980 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001981 ConvertedType = BuildSimilarlyQualifiedPointerType(
1982 FromType->getAs<ObjCObjectPointerType>(),
1983 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001984 ToType, Context);
1985 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001986 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001987 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001988 if (!FromTypePtr)
1989 return false;
1990
1991 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001992
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001993 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001994 // pointer conversion, so don't do all of the work below.
1995 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1996 return false;
1997
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001998 // An rvalue of type "pointer to cv T," where T is an object type,
1999 // can be converted to an rvalue of type "pointer to cv void" (C++
2000 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002001 if (FromPointeeType->isIncompleteOrObjectType() &&
2002 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002003 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002004 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002005 ToType, Context,
2006 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002007 return true;
2008 }
2009
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002010 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002011 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002012 ToPointeeType->isVoidType()) {
2013 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2014 ToPointeeType,
2015 ToType, Context);
2016 return true;
2017 }
2018
Douglas Gregorf9201e02009-02-11 23:02:49 +00002019 // When we're overloading in C, we allow a special kind of pointer
2020 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002021 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002022 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002023 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002024 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002025 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002026 return true;
2027 }
2028
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002029 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002030 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002031 // An rvalue of type "pointer to cv D," where D is a class type,
2032 // can be converted to an rvalue of type "pointer to cv B," where
2033 // B is a base class (clause 10) of D. If B is an inaccessible
2034 // (clause 11) or ambiguous (10.2) base class of D, a program that
2035 // necessitates this conversion is ill-formed. The result of the
2036 // conversion is a pointer to the base class sub-object of the
2037 // derived class object. The null pointer value is converted to
2038 // the null pointer value of the destination type.
2039 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002040 // Note that we do not check for ambiguity or inaccessibility
2041 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002042 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002043 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002044 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002045 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002046 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002048 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002049 ToType, Context);
2050 return true;
2051 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002052
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002053 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2054 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2056 ToPointeeType,
2057 ToType, Context);
2058 return true;
2059 }
2060
Douglas Gregorc7887512008-12-19 19:13:09 +00002061 return false;
2062}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002063
2064/// \brief Adopt the given qualifiers for the given type.
2065static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2066 Qualifiers TQs = T.getQualifiers();
2067
2068 // Check whether qualifiers already match.
2069 if (TQs == Qs)
2070 return T;
2071
2072 if (Qs.compatiblyIncludes(TQs))
2073 return Context.getQualifiedType(T, Qs);
2074
2075 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2076}
Douglas Gregorc7887512008-12-19 19:13:09 +00002077
2078/// isObjCPointerConversion - Determines whether this is an
2079/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2080/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002081bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002082 QualType& ConvertedType,
2083 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002084 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002085 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002086
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002087 // The set of qualifiers on the type we're converting from.
2088 Qualifiers FromQualifiers = FromType.getQualifiers();
2089
Steve Naroff14108da2009-07-10 23:34:53 +00002090 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002091 const ObjCObjectPointerType* ToObjCPtr =
2092 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002093 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002094 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002095
Steve Naroff14108da2009-07-10 23:34:53 +00002096 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002097 // If the pointee types are the same (ignoring qualifications),
2098 // then this is not a pointer conversion.
2099 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2100 FromObjCPtr->getPointeeType()))
2101 return false;
2102
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002103 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002104 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002105 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002106 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002107 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002108 return true;
2109 }
2110 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002111 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002112 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002113 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002114 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002115 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002116 return true;
2117 }
2118 // Objective C++: We're able to convert from a pointer to an
2119 // interface to a pointer to a different interface.
2120 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002121 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2122 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002123 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002124 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2125 FromObjCPtr->getPointeeType()))
2126 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002128 ToObjCPtr->getPointeeType(),
2129 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002130 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002131 return true;
2132 }
2133
2134 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2135 // Okay: this is some kind of implicit downcast of Objective-C
2136 // interfaces, which is permitted. However, we're going to
2137 // complain about it.
2138 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002139 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002140 ToObjCPtr->getPointeeType(),
2141 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002142 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002143 return true;
2144 }
Mike Stump1eb44332009-09-09 15:08:12 +00002145 }
Steve Naroff14108da2009-07-10 23:34:53 +00002146 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002147 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002148 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002149 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002150 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002151 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002152 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002153 // to a block pointer type.
2154 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002155 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002156 return true;
2157 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002158 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002160 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002161 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002162 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002163 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002164 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002165 return true;
2166 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002167 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002168 return false;
2169
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002170 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002171 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002172 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002173 else if (const BlockPointerType *FromBlockPtr =
2174 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002175 FromPointeeType = FromBlockPtr->getPointeeType();
2176 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002177 return false;
2178
Douglas Gregorc7887512008-12-19 19:13:09 +00002179 // If we have pointers to pointers, recursively check whether this
2180 // is an Objective-C conversion.
2181 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2182 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2183 IncompatibleObjC)) {
2184 // We always complain about this conversion.
2185 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002186 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002187 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002188 return true;
2189 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002190 // Allow conversion of pointee being objective-c pointer to another one;
2191 // as in I* to id.
2192 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2193 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2194 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2195 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002196
Douglas Gregorda80f742010-12-01 21:43:58 +00002197 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002198 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002199 return true;
2200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002202 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002203 // differences in the argument and result types are in Objective-C
2204 // pointer conversions. If so, we permit the conversion (but
2205 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002206 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002207 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002208 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002209 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002210 if (FromFunctionType && ToFunctionType) {
2211 // If the function types are exactly the same, this isn't an
2212 // Objective-C pointer conversion.
2213 if (Context.getCanonicalType(FromPointeeType)
2214 == Context.getCanonicalType(ToPointeeType))
2215 return false;
2216
2217 // Perform the quick checks that will tell us whether these
2218 // function types are obviously different.
2219 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2220 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2221 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2222 return false;
2223
2224 bool HasObjCConversion = false;
2225 if (Context.getCanonicalType(FromFunctionType->getResultType())
2226 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2227 // Okay, the types match exactly. Nothing to do.
2228 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2229 ToFunctionType->getResultType(),
2230 ConvertedType, IncompatibleObjC)) {
2231 // Okay, we have an Objective-C pointer conversion.
2232 HasObjCConversion = true;
2233 } else {
2234 // Function types are too different. Abort.
2235 return false;
2236 }
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Douglas Gregorc7887512008-12-19 19:13:09 +00002238 // Check argument types.
2239 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2240 ArgIdx != NumArgs; ++ArgIdx) {
2241 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2242 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2243 if (Context.getCanonicalType(FromArgType)
2244 == Context.getCanonicalType(ToArgType)) {
2245 // Okay, the types match exactly. Nothing to do.
2246 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2247 ConvertedType, IncompatibleObjC)) {
2248 // Okay, we have an Objective-C pointer conversion.
2249 HasObjCConversion = true;
2250 } else {
2251 // Argument types are too different. Abort.
2252 return false;
2253 }
2254 }
2255
2256 if (HasObjCConversion) {
2257 // We had an Objective-C conversion. Allow this pointer
2258 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002259 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002260 IncompatibleObjC = true;
2261 return true;
2262 }
2263 }
2264
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002265 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002266}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002267
John McCallf85e1932011-06-15 23:02:42 +00002268/// \brief Determine whether this is an Objective-C writeback conversion,
2269/// used for parameter passing when performing automatic reference counting.
2270///
2271/// \param FromType The type we're converting form.
2272///
2273/// \param ToType The type we're converting to.
2274///
2275/// \param ConvertedType The type that will be produced after applying
2276/// this conversion.
2277bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2278 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002279 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002280 Context.hasSameUnqualifiedType(FromType, ToType))
2281 return false;
2282
2283 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2284 QualType ToPointee;
2285 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2286 ToPointee = ToPointer->getPointeeType();
2287 else
2288 return false;
2289
2290 Qualifiers ToQuals = ToPointee.getQualifiers();
2291 if (!ToPointee->isObjCLifetimeType() ||
2292 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002293 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002294 return false;
2295
2296 // Argument must be a pointer to __strong to __weak.
2297 QualType FromPointee;
2298 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2299 FromPointee = FromPointer->getPointeeType();
2300 else
2301 return false;
2302
2303 Qualifiers FromQuals = FromPointee.getQualifiers();
2304 if (!FromPointee->isObjCLifetimeType() ||
2305 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2306 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2307 return false;
2308
2309 // Make sure that we have compatible qualifiers.
2310 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2311 if (!ToQuals.compatiblyIncludes(FromQuals))
2312 return false;
2313
2314 // Remove qualifiers from the pointee type we're converting from; they
2315 // aren't used in the compatibility check belong, and we'll be adding back
2316 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2317 FromPointee = FromPointee.getUnqualifiedType();
2318
2319 // The unqualified form of the pointee types must be compatible.
2320 ToPointee = ToPointee.getUnqualifiedType();
2321 bool IncompatibleObjC;
2322 if (Context.typesAreCompatible(FromPointee, ToPointee))
2323 FromPointee = ToPointee;
2324 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2325 IncompatibleObjC))
2326 return false;
2327
2328 /// \brief Construct the type we're converting to, which is a pointer to
2329 /// __autoreleasing pointee.
2330 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2331 ConvertedType = Context.getPointerType(FromPointee);
2332 return true;
2333}
2334
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002335bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2336 QualType& ConvertedType) {
2337 QualType ToPointeeType;
2338 if (const BlockPointerType *ToBlockPtr =
2339 ToType->getAs<BlockPointerType>())
2340 ToPointeeType = ToBlockPtr->getPointeeType();
2341 else
2342 return false;
2343
2344 QualType FromPointeeType;
2345 if (const BlockPointerType *FromBlockPtr =
2346 FromType->getAs<BlockPointerType>())
2347 FromPointeeType = FromBlockPtr->getPointeeType();
2348 else
2349 return false;
2350 // We have pointer to blocks, check whether the only
2351 // differences in the argument and result types are in Objective-C
2352 // pointer conversions. If so, we permit the conversion.
2353
2354 const FunctionProtoType *FromFunctionType
2355 = FromPointeeType->getAs<FunctionProtoType>();
2356 const FunctionProtoType *ToFunctionType
2357 = ToPointeeType->getAs<FunctionProtoType>();
2358
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002359 if (!FromFunctionType || !ToFunctionType)
2360 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002361
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002362 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002363 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002364
2365 // Perform the quick checks that will tell us whether these
2366 // function types are obviously different.
2367 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2368 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2369 return false;
2370
2371 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2372 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2373 if (FromEInfo != ToEInfo)
2374 return false;
2375
2376 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002377 if (Context.hasSameType(FromFunctionType->getResultType(),
2378 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002379 // Okay, the types match exactly. Nothing to do.
2380 } else {
2381 QualType RHS = FromFunctionType->getResultType();
2382 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002383 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002384 !RHS.hasQualifiers() && LHS.hasQualifiers())
2385 LHS = LHS.getUnqualifiedType();
2386
2387 if (Context.hasSameType(RHS,LHS)) {
2388 // OK exact match.
2389 } else if (isObjCPointerConversion(RHS, LHS,
2390 ConvertedType, IncompatibleObjC)) {
2391 if (IncompatibleObjC)
2392 return false;
2393 // Okay, we have an Objective-C pointer conversion.
2394 }
2395 else
2396 return false;
2397 }
2398
2399 // Check argument types.
2400 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2401 ArgIdx != NumArgs; ++ArgIdx) {
2402 IncompatibleObjC = false;
2403 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2404 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2405 if (Context.hasSameType(FromArgType, ToArgType)) {
2406 // Okay, the types match exactly. Nothing to do.
2407 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2408 ConvertedType, IncompatibleObjC)) {
2409 if (IncompatibleObjC)
2410 return false;
2411 // Okay, we have an Objective-C pointer conversion.
2412 } else
2413 // Argument types are too different. Abort.
2414 return false;
2415 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002416 if (LangOpts.ObjCAutoRefCount &&
2417 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2418 ToFunctionType))
2419 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002420
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002421 ConvertedType = ToType;
2422 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002423}
2424
Richard Trieu6efd4c52011-11-23 22:32:32 +00002425enum {
2426 ft_default,
2427 ft_different_class,
2428 ft_parameter_arity,
2429 ft_parameter_mismatch,
2430 ft_return_type,
2431 ft_qualifer_mismatch
2432};
2433
2434/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2435/// function types. Catches different number of parameter, mismatch in
2436/// parameter types, and different return types.
2437void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2438 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002439 // If either type is not valid, include no extra info.
2440 if (FromType.isNull() || ToType.isNull()) {
2441 PDiag << ft_default;
2442 return;
2443 }
2444
Richard Trieu6efd4c52011-11-23 22:32:32 +00002445 // Get the function type from the pointers.
2446 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2447 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2448 *ToMember = ToType->getAs<MemberPointerType>();
2449 if (FromMember->getClass() != ToMember->getClass()) {
2450 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2451 << QualType(FromMember->getClass(), 0);
2452 return;
2453 }
2454 FromType = FromMember->getPointeeType();
2455 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002456 }
2457
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002458 if (FromType->isPointerType())
2459 FromType = FromType->getPointeeType();
2460 if (ToType->isPointerType())
2461 ToType = ToType->getPointeeType();
2462
2463 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002464 FromType = FromType.getNonReferenceType();
2465 ToType = ToType.getNonReferenceType();
2466
Richard Trieu6efd4c52011-11-23 22:32:32 +00002467 // Don't print extra info for non-specialized template functions.
2468 if (FromType->isInstantiationDependentType() &&
2469 !FromType->getAs<TemplateSpecializationType>()) {
2470 PDiag << ft_default;
2471 return;
2472 }
2473
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002474 // No extra info for same types.
2475 if (Context.hasSameType(FromType, ToType)) {
2476 PDiag << ft_default;
2477 return;
2478 }
2479
Richard Trieu6efd4c52011-11-23 22:32:32 +00002480 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2481 *ToFunction = ToType->getAs<FunctionProtoType>();
2482
2483 // Both types need to be function types.
2484 if (!FromFunction || !ToFunction) {
2485 PDiag << ft_default;
2486 return;
2487 }
2488
2489 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2490 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2491 << FromFunction->getNumArgs();
2492 return;
2493 }
2494
2495 // Handle different parameter types.
2496 unsigned ArgPos;
2497 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2498 PDiag << ft_parameter_mismatch << ArgPos + 1
2499 << ToFunction->getArgType(ArgPos)
2500 << FromFunction->getArgType(ArgPos);
2501 return;
2502 }
2503
2504 // Handle different return type.
2505 if (!Context.hasSameType(FromFunction->getResultType(),
2506 ToFunction->getResultType())) {
2507 PDiag << ft_return_type << ToFunction->getResultType()
2508 << FromFunction->getResultType();
2509 return;
2510 }
2511
2512 unsigned FromQuals = FromFunction->getTypeQuals(),
2513 ToQuals = ToFunction->getTypeQuals();
2514 if (FromQuals != ToQuals) {
2515 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2516 return;
2517 }
2518
2519 // Unable to find a difference, so add no extra info.
2520 PDiag << ft_default;
2521}
2522
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002523/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002524/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002525/// they have same number of arguments. This routine assumes that Objective-C
2526/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002527/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002528/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002529bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002530 const FunctionProtoType *NewType,
2531 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002532 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002533 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2534 N = NewType->arg_type_begin(),
2535 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2536 if (!Context.hasSameType(*O, *N)) {
2537 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2538 return false;
2539 }
2540 }
2541 return true;
2542 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002543
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002544 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2545 N = NewType->arg_type_begin(),
2546 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2547 QualType ToType = (*O);
2548 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002549 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002550 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2551 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002552 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2553 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2554 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2555 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002556 continue;
2557 }
John McCallc12c5bb2010-05-15 11:32:37 +00002558 else if (const ObjCObjectPointerType *PTTo =
2559 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002560 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002561 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002562 if (Context.hasSameUnqualifiedType(
2563 PTTo->getObjectType()->getBaseType(),
2564 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002565 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002566 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002567 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002568 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002569 }
2570 }
2571 return true;
2572}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002573
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002574/// CheckPointerConversion - Check the pointer conversion from the
2575/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002576/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002577/// conversions for which IsPointerConversion has already returned
2578/// true. It returns true and produces a diagnostic if there was an
2579/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002580bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002581 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002582 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002583 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002584 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002585 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002586
John McCalldaa8e4e2010-11-15 09:13:47 +00002587 Kind = CK_BitCast;
2588
David Blaikie50800fc2012-08-08 17:33:31 +00002589 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2590 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2591 Expr::NPCK_ZeroExpression) {
2592 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2593 DiagRuntimeBehavior(From->getExprLoc(), From,
2594 PDiag(diag::warn_impcast_bool_to_null_pointer)
2595 << ToType << From->getSourceRange());
2596 else if (!isUnevaluatedContext())
2597 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2598 << ToType << From->getSourceRange();
2599 }
John McCall1d9b3b22011-09-09 05:25:32 +00002600 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2601 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002602 QualType FromPointeeType = FromPtrType->getPointeeType(),
2603 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002604
Douglas Gregor5fccd362010-03-03 23:55:11 +00002605 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2606 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002607 // We must have a derived-to-base conversion. Check an
2608 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002609 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2610 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002611 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002612 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002613 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002614
Anders Carlsson61faec12009-09-12 04:46:44 +00002615 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002616 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002617 }
2618 }
John McCall1d9b3b22011-09-09 05:25:32 +00002619 } else if (const ObjCObjectPointerType *ToPtrType =
2620 ToType->getAs<ObjCObjectPointerType>()) {
2621 if (const ObjCObjectPointerType *FromPtrType =
2622 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002623 // Objective-C++ conversions are always okay.
2624 // FIXME: We should have a different class of conversions for the
2625 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002626 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002627 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002628 } else if (FromType->isBlockPointerType()) {
2629 Kind = CK_BlockPointerToObjCPointerCast;
2630 } else {
2631 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002632 }
John McCall1d9b3b22011-09-09 05:25:32 +00002633 } else if (ToType->isBlockPointerType()) {
2634 if (!FromType->isBlockPointerType())
2635 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002636 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002637
2638 // We shouldn't fall into this case unless it's valid for other
2639 // reasons.
2640 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2641 Kind = CK_NullToPointer;
2642
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002643 return false;
2644}
2645
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002646/// IsMemberPointerConversion - Determines whether the conversion of the
2647/// expression From, which has the (possibly adjusted) type FromType, can be
2648/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2649/// If so, returns true and places the converted type (that might differ from
2650/// ToType in its cv-qualifiers at some level) into ConvertedType.
2651bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002652 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002653 bool InOverloadResolution,
2654 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002655 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002656 if (!ToTypePtr)
2657 return false;
2658
2659 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002660 if (From->isNullPointerConstant(Context,
2661 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2662 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002663 ConvertedType = ToType;
2664 return true;
2665 }
2666
2667 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002668 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002669 if (!FromTypePtr)
2670 return false;
2671
2672 // A pointer to member of B can be converted to a pointer to member of D,
2673 // where D is derived from B (C++ 4.11p2).
2674 QualType FromClass(FromTypePtr->getClass(), 0);
2675 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002676
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002677 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002678 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002679 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002680 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2681 ToClass.getTypePtr());
2682 return true;
2683 }
2684
2685 return false;
2686}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002687
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002688/// CheckMemberPointerConversion - Check the member pointer conversion from the
2689/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002690/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002691/// for which IsMemberPointerConversion has already returned true. It returns
2692/// true and produces a diagnostic if there was an error, or returns false
2693/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002694bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002695 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002696 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002697 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002698 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002699 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002700 if (!FromPtrType) {
2701 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002703 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002704 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002705 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002706 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002707 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002708
Ted Kremenek6217b802009-07-29 21:53:49 +00002709 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002710 assert(ToPtrType && "No member pointer cast has a target type "
2711 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002712
Sebastian Redl21593ac2009-01-28 18:33:18 +00002713 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2714 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002715
Sebastian Redl21593ac2009-01-28 18:33:18 +00002716 // FIXME: What about dependent types?
2717 assert(FromClass->isRecordType() && "Pointer into non-class.");
2718 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002719
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002720 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002721 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002722 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2723 assert(DerivationOkay &&
2724 "Should not have been called if derivation isn't OK.");
2725 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002726
Sebastian Redl21593ac2009-01-28 18:33:18 +00002727 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2728 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002729 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2730 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2731 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2732 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002733 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002734
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002735 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002736 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2737 << FromClass << ToClass << QualType(VBase, 0)
2738 << From->getSourceRange();
2739 return true;
2740 }
2741
John McCall6b2accb2010-02-10 09:31:12 +00002742 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002743 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2744 Paths.front(),
2745 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002746
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002747 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002748 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002749 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002750 return false;
2751}
2752
Douglas Gregor98cd5992008-10-21 23:43:52 +00002753/// IsQualificationConversion - Determines whether the conversion from
2754/// an rvalue of type FromType to ToType is a qualification conversion
2755/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002756///
2757/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2758/// when the qualification conversion involves a change in the Objective-C
2759/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002760bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002761Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002762 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002763 FromType = Context.getCanonicalType(FromType);
2764 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002765 ObjCLifetimeConversion = false;
2766
Douglas Gregor98cd5992008-10-21 23:43:52 +00002767 // If FromType and ToType are the same type, this is not a
2768 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002769 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002770 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002771
Douglas Gregor98cd5992008-10-21 23:43:52 +00002772 // (C++ 4.4p4):
2773 // A conversion can add cv-qualifiers at levels other than the first
2774 // in multi-level pointers, subject to the following rules: [...]
2775 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002776 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002777 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002778 // Within each iteration of the loop, we check the qualifiers to
2779 // determine if this still looks like a qualification
2780 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002781 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002782 // until there are no more pointers or pointers-to-members left to
2783 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002784 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002785
Douglas Gregor621c92a2011-04-25 18:40:17 +00002786 Qualifiers FromQuals = FromType.getQualifiers();
2787 Qualifiers ToQuals = ToType.getQualifiers();
2788
John McCallf85e1932011-06-15 23:02:42 +00002789 // Objective-C ARC:
2790 // Check Objective-C lifetime conversions.
2791 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2792 UnwrappedAnyPointer) {
2793 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2794 ObjCLifetimeConversion = true;
2795 FromQuals.removeObjCLifetime();
2796 ToQuals.removeObjCLifetime();
2797 } else {
2798 // Qualification conversions cannot cast between different
2799 // Objective-C lifetime qualifiers.
2800 return false;
2801 }
2802 }
2803
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002804 // Allow addition/removal of GC attributes but not changing GC attributes.
2805 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2806 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2807 FromQuals.removeObjCGCAttr();
2808 ToQuals.removeObjCGCAttr();
2809 }
2810
Douglas Gregor98cd5992008-10-21 23:43:52 +00002811 // -- for every j > 0, if const is in cv 1,j then const is in cv
2812 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002813 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002814 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Douglas Gregor98cd5992008-10-21 23:43:52 +00002816 // -- if the cv 1,j and cv 2,j are different, then const is in
2817 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002818 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002819 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002820 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Douglas Gregor98cd5992008-10-21 23:43:52 +00002822 // Keep track of whether all prior cv-qualifiers in the "to" type
2823 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002824 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002825 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002826 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002827
2828 // We are left with FromType and ToType being the pointee types
2829 // after unwrapping the original FromType and ToType the same number
2830 // of types. If we unwrapped any pointers, and if FromType and
2831 // ToType have the same unqualified type (since we checked
2832 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002833 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002834}
2835
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002836/// \brief - Determine whether this is a conversion from a scalar type to an
2837/// atomic type.
2838///
2839/// If successful, updates \c SCS's second and third steps in the conversion
2840/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002841static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2842 bool InOverloadResolution,
2843 StandardConversionSequence &SCS,
2844 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002845 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2846 if (!ToAtomic)
2847 return false;
2848
2849 StandardConversionSequence InnerSCS;
2850 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2851 InOverloadResolution, InnerSCS,
2852 CStyle, /*AllowObjCWritebackConversion=*/false))
2853 return false;
2854
2855 SCS.Second = InnerSCS.Second;
2856 SCS.setToType(1, InnerSCS.getToType(1));
2857 SCS.Third = InnerSCS.Third;
2858 SCS.QualificationIncludesObjCLifetime
2859 = InnerSCS.QualificationIncludesObjCLifetime;
2860 SCS.setToType(2, InnerSCS.getToType(2));
2861 return true;
2862}
2863
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002864static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2865 CXXConstructorDecl *Constructor,
2866 QualType Type) {
2867 const FunctionProtoType *CtorType =
2868 Constructor->getType()->getAs<FunctionProtoType>();
2869 if (CtorType->getNumArgs() > 0) {
2870 QualType FirstArg = CtorType->getArgType(0);
2871 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2872 return true;
2873 }
2874 return false;
2875}
2876
Sebastian Redl56a04282012-02-11 23:51:08 +00002877static OverloadingResult
2878IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2879 CXXRecordDecl *To,
2880 UserDefinedConversionSequence &User,
2881 OverloadCandidateSet &CandidateSet,
2882 bool AllowExplicit) {
2883 DeclContext::lookup_iterator Con, ConEnd;
2884 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2885 Con != ConEnd; ++Con) {
2886 NamedDecl *D = *Con;
2887 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2888
2889 // Find the constructor (which may be a template).
2890 CXXConstructorDecl *Constructor = 0;
2891 FunctionTemplateDecl *ConstructorTmpl
2892 = dyn_cast<FunctionTemplateDecl>(D);
2893 if (ConstructorTmpl)
2894 Constructor
2895 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2896 else
2897 Constructor = cast<CXXConstructorDecl>(D);
2898
2899 bool Usable = !Constructor->isInvalidDecl() &&
2900 S.isInitListConstructor(Constructor) &&
2901 (AllowExplicit || !Constructor->isExplicit());
2902 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002903 // If the first argument is (a reference to) the target type,
2904 // suppress conversions.
2905 bool SuppressUserConversions =
2906 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002907 if (ConstructorTmpl)
2908 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2909 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002910 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002911 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002912 else
2913 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002914 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002915 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002916 }
2917 }
2918
2919 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2920
2921 OverloadCandidateSet::iterator Best;
2922 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2923 case OR_Success: {
2924 // Record the standard conversion we used and the conversion function.
2925 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2926 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2927
2928 QualType ThisType = Constructor->getThisType(S.Context);
2929 // Initializer lists don't have conversions as such.
2930 User.Before.setAsIdentityConversion();
2931 User.HadMultipleCandidates = HadMultipleCandidates;
2932 User.ConversionFunction = Constructor;
2933 User.FoundConversionFunction = Best->FoundDecl;
2934 User.After.setAsIdentityConversion();
2935 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2936 User.After.setAllToTypes(ToType);
2937 return OR_Success;
2938 }
2939
2940 case OR_No_Viable_Function:
2941 return OR_No_Viable_Function;
2942 case OR_Deleted:
2943 return OR_Deleted;
2944 case OR_Ambiguous:
2945 return OR_Ambiguous;
2946 }
2947
2948 llvm_unreachable("Invalid OverloadResult!");
2949}
2950
Douglas Gregor734d9862009-01-30 23:27:23 +00002951/// Determines whether there is a user-defined conversion sequence
2952/// (C++ [over.ics.user]) that converts expression From to the type
2953/// ToType. If such a conversion exists, User will contain the
2954/// user-defined conversion sequence that performs such a conversion
2955/// and this routine will return true. Otherwise, this routine returns
2956/// false and User is unspecified.
2957///
Douglas Gregor734d9862009-01-30 23:27:23 +00002958/// \param AllowExplicit true if the conversion should consider C++0x
2959/// "explicit" conversion functions as well as non-explicit conversion
2960/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002961static OverloadingResult
2962IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002963 UserDefinedConversionSequence &User,
2964 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002965 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002966 // Whether we will only visit constructors.
2967 bool ConstructorsOnly = false;
2968
2969 // If the type we are conversion to is a class type, enumerate its
2970 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002971 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002972 // C++ [over.match.ctor]p1:
2973 // When objects of class type are direct-initialized (8.5), or
2974 // copy-initialized from an expression of the same or a
2975 // derived class type (8.5), overload resolution selects the
2976 // constructor. [...] For copy-initialization, the candidate
2977 // functions are all the converting constructors (12.3.1) of
2978 // that class. The argument list is the expression-list within
2979 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002980 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002981 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002982 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002983 ConstructorsOnly = true;
2984
Douglas Gregord10099e2012-05-04 16:32:21 +00002985 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002986 // RequireCompleteType may have returned true due to some invalid decl
2987 // during template instantiation, but ToType may be complete enough now
2988 // to try to recover.
2989 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002990 // We're not going to find any constructors.
2991 } else if (CXXRecordDecl *ToRecordDecl
2992 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002993
2994 Expr **Args = &From;
2995 unsigned NumArgs = 1;
2996 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002997 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002998 // But first, see if there is an init-list-contructor that will work.
2999 OverloadingResult Result = IsInitializerListConstructorConversion(
3000 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3001 if (Result != OR_No_Viable_Function)
3002 return Result;
3003 // Never mind.
3004 CandidateSet.clear();
3005
3006 // If we're list-initializing, we pass the individual elements as
3007 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003008 Args = InitList->getInits();
3009 NumArgs = InitList->getNumInits();
3010 ListInitializing = true;
3011 }
3012
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003013 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00003014 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003015 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003016 NamedDecl *D = *Con;
3017 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3018
Douglas Gregordec06662009-08-21 18:42:58 +00003019 // Find the constructor (which may be a template).
3020 CXXConstructorDecl *Constructor = 0;
3021 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003022 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003023 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003024 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003025 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3026 else
John McCall9aa472c2010-03-19 07:35:19 +00003027 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003028
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003029 bool Usable = !Constructor->isInvalidDecl();
3030 if (ListInitializing)
3031 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3032 else
3033 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3034 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003035 bool SuppressUserConversions = !ConstructorsOnly;
3036 if (SuppressUserConversions && ListInitializing) {
3037 SuppressUserConversions = false;
3038 if (NumArgs == 1) {
3039 // If the first argument is (a reference to) the target type,
3040 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003041 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3042 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003043 }
3044 }
Douglas Gregordec06662009-08-21 18:42:58 +00003045 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003046 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3047 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003048 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003049 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003050 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003051 // Allow one user-defined conversion when user specifies a
3052 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003053 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003054 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003055 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003056 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003057 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003058 }
3059 }
3060
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003061 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003062 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003063 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003064 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003065 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003066 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003067 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003068 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3069 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003070 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003071 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003072 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003073 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003074 DeclAccessPair FoundDecl = I.getPair();
3075 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003076 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3077 if (isa<UsingShadowDecl>(D))
3078 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3079
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003080 CXXConversionDecl *Conv;
3081 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003082 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3083 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003084 else
John McCall32daa422010-03-31 01:36:47 +00003085 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003086
3087 if (AllowExplicit || !Conv->isExplicit()) {
3088 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003089 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3090 ActingContext, From, ToType,
3091 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003092 else
John McCall120d63c2010-08-24 20:38:10 +00003093 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3094 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003095 }
3096 }
3097 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003098 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003099
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003100 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3101
Douglas Gregor60d62c22008-10-31 16:23:19 +00003102 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003103 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003104 case OR_Success:
3105 // Record the standard conversion we used and the conversion function.
3106 if (CXXConstructorDecl *Constructor
3107 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003108 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003109
John McCall120d63c2010-08-24 20:38:10 +00003110 // C++ [over.ics.user]p1:
3111 // If the user-defined conversion is specified by a
3112 // constructor (12.3.1), the initial standard conversion
3113 // sequence converts the source type to the type required by
3114 // the argument of the constructor.
3115 //
3116 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003117 if (isa<InitListExpr>(From)) {
3118 // Initializer lists don't have conversions as such.
3119 User.Before.setAsIdentityConversion();
3120 } else {
3121 if (Best->Conversions[0].isEllipsis())
3122 User.EllipsisConversion = true;
3123 else {
3124 User.Before = Best->Conversions[0].Standard;
3125 User.EllipsisConversion = false;
3126 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003127 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003128 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003129 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003130 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003131 User.After.setAsIdentityConversion();
3132 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3133 User.After.setAllToTypes(ToType);
3134 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003135 }
3136 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003137 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003138 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003139
John McCall120d63c2010-08-24 20:38:10 +00003140 // C++ [over.ics.user]p1:
3141 //
3142 // [...] If the user-defined conversion is specified by a
3143 // conversion function (12.3.2), the initial standard
3144 // conversion sequence converts the source type to the
3145 // implicit object parameter of the conversion function.
3146 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003147 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003148 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003149 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003150 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003151
John McCall120d63c2010-08-24 20:38:10 +00003152 // C++ [over.ics.user]p2:
3153 // The second standard conversion sequence converts the
3154 // result of the user-defined conversion to the target type
3155 // for the sequence. Since an implicit conversion sequence
3156 // is an initialization, the special rules for
3157 // initialization by user-defined conversion apply when
3158 // selecting the best user-defined conversion for a
3159 // user-defined conversion sequence (see 13.3.3 and
3160 // 13.3.3.1).
3161 User.After = Best->FinalConversion;
3162 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003163 }
David Blaikie7530c032012-01-17 06:56:22 +00003164 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003165
John McCall120d63c2010-08-24 20:38:10 +00003166 case OR_No_Viable_Function:
3167 return OR_No_Viable_Function;
3168 case OR_Deleted:
3169 // No conversion here! We're done.
3170 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003171
John McCall120d63c2010-08-24 20:38:10 +00003172 case OR_Ambiguous:
3173 return OR_Ambiguous;
3174 }
3175
David Blaikie7530c032012-01-17 06:56:22 +00003176 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003177}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003178
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003179bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003180Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003181 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003182 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003184 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003185 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003186 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003187 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003188 diag::err_typecheck_ambiguous_condition)
3189 << From->getType() << ToType << From->getSourceRange();
3190 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003191 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003192 diag::err_typecheck_nonviable_condition)
3193 << From->getType() << ToType << From->getSourceRange();
3194 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003195 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003196 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003198}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003199
Douglas Gregorb734e242012-02-22 17:32:19 +00003200/// \brief Compare the user-defined conversion functions or constructors
3201/// of two user-defined conversion sequences to determine whether any ordering
3202/// is possible.
3203static ImplicitConversionSequence::CompareKind
3204compareConversionFunctions(Sema &S,
3205 FunctionDecl *Function1,
3206 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003207 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003208 return ImplicitConversionSequence::Indistinguishable;
3209
3210 // Objective-C++:
3211 // If both conversion functions are implicitly-declared conversions from
3212 // a lambda closure type to a function pointer and a block pointer,
3213 // respectively, always prefer the conversion to a function pointer,
3214 // because the function pointer is more lightweight and is more likely
3215 // to keep code working.
3216 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3217 if (!Conv1)
3218 return ImplicitConversionSequence::Indistinguishable;
3219
3220 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3221 if (!Conv2)
3222 return ImplicitConversionSequence::Indistinguishable;
3223
3224 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3225 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3226 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3227 if (Block1 != Block2)
3228 return Block1? ImplicitConversionSequence::Worse
3229 : ImplicitConversionSequence::Better;
3230 }
3231
3232 return ImplicitConversionSequence::Indistinguishable;
3233}
3234
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003235/// CompareImplicitConversionSequences - Compare two implicit
3236/// conversion sequences to determine whether one is better than the
3237/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003238static ImplicitConversionSequence::CompareKind
3239CompareImplicitConversionSequences(Sema &S,
3240 const ImplicitConversionSequence& ICS1,
3241 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003242{
3243 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3244 // conversion sequences (as defined in 13.3.3.1)
3245 // -- a standard conversion sequence (13.3.3.1.1) is a better
3246 // conversion sequence than a user-defined conversion sequence or
3247 // an ellipsis conversion sequence, and
3248 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3249 // conversion sequence than an ellipsis conversion sequence
3250 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003251 //
John McCall1d318332010-01-12 00:44:57 +00003252 // C++0x [over.best.ics]p10:
3253 // For the purpose of ranking implicit conversion sequences as
3254 // described in 13.3.3.2, the ambiguous conversion sequence is
3255 // treated as a user-defined sequence that is indistinguishable
3256 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003257 if (ICS1.getKindRank() < ICS2.getKindRank())
3258 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003259 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003260 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003261
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003262 // The following checks require both conversion sequences to be of
3263 // the same kind.
3264 if (ICS1.getKind() != ICS2.getKind())
3265 return ImplicitConversionSequence::Indistinguishable;
3266
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003267 ImplicitConversionSequence::CompareKind Result =
3268 ImplicitConversionSequence::Indistinguishable;
3269
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003270 // Two implicit conversion sequences of the same form are
3271 // indistinguishable conversion sequences unless one of the
3272 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003273 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003274 Result = CompareStandardConversionSequences(S,
3275 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003276 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003277 // User-defined conversion sequence U1 is a better conversion
3278 // sequence than another user-defined conversion sequence U2 if
3279 // they contain the same user-defined conversion function or
3280 // constructor and if the second standard conversion sequence of
3281 // U1 is better than the second standard conversion sequence of
3282 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003283 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003284 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003285 Result = CompareStandardConversionSequences(S,
3286 ICS1.UserDefined.After,
3287 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003288 else
3289 Result = compareConversionFunctions(S,
3290 ICS1.UserDefined.ConversionFunction,
3291 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003292 }
3293
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003294 // List-initialization sequence L1 is a better conversion sequence than
3295 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3296 // for some X and L2 does not.
3297 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003298 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003299 ICS1.isListInitializationSequence() &&
3300 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003301 if (ICS1.isStdInitializerListElement() &&
3302 !ICS2.isStdInitializerListElement())
3303 return ImplicitConversionSequence::Better;
3304 if (!ICS1.isStdInitializerListElement() &&
3305 ICS2.isStdInitializerListElement())
3306 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003307 }
3308
3309 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003310}
3311
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003312static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3313 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3314 Qualifiers Quals;
3315 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003316 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003317 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003318
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003319 return Context.hasSameUnqualifiedType(T1, T2);
3320}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003321
Douglas Gregorad323a82010-01-27 03:51:04 +00003322// Per 13.3.3.2p3, compare the given standard conversion sequences to
3323// determine if one is a proper subset of the other.
3324static ImplicitConversionSequence::CompareKind
3325compareStandardConversionSubsets(ASTContext &Context,
3326 const StandardConversionSequence& SCS1,
3327 const StandardConversionSequence& SCS2) {
3328 ImplicitConversionSequence::CompareKind Result
3329 = ImplicitConversionSequence::Indistinguishable;
3330
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003332 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003333 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3334 return ImplicitConversionSequence::Better;
3335 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3336 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003337
Douglas Gregorad323a82010-01-27 03:51:04 +00003338 if (SCS1.Second != SCS2.Second) {
3339 if (SCS1.Second == ICK_Identity)
3340 Result = ImplicitConversionSequence::Better;
3341 else if (SCS2.Second == ICK_Identity)
3342 Result = ImplicitConversionSequence::Worse;
3343 else
3344 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003345 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003346 return ImplicitConversionSequence::Indistinguishable;
3347
3348 if (SCS1.Third == SCS2.Third) {
3349 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3350 : ImplicitConversionSequence::Indistinguishable;
3351 }
3352
3353 if (SCS1.Third == ICK_Identity)
3354 return Result == ImplicitConversionSequence::Worse
3355 ? ImplicitConversionSequence::Indistinguishable
3356 : ImplicitConversionSequence::Better;
3357
3358 if (SCS2.Third == ICK_Identity)
3359 return Result == ImplicitConversionSequence::Better
3360 ? ImplicitConversionSequence::Indistinguishable
3361 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362
Douglas Gregorad323a82010-01-27 03:51:04 +00003363 return ImplicitConversionSequence::Indistinguishable;
3364}
3365
Douglas Gregor440a4832011-01-26 14:52:12 +00003366/// \brief Determine whether one of the given reference bindings is better
3367/// than the other based on what kind of bindings they are.
3368static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3369 const StandardConversionSequence &SCS2) {
3370 // C++0x [over.ics.rank]p3b4:
3371 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3372 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003374 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003376 // reference*.
3377 //
3378 // FIXME: Rvalue references. We're going rogue with the above edits,
3379 // because the semantics in the current C++0x working paper (N3225 at the
3380 // time of this writing) break the standard definition of std::forward
3381 // and std::reference_wrapper when dealing with references to functions.
3382 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003383 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3384 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3385 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386
Douglas Gregor440a4832011-01-26 14:52:12 +00003387 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3388 SCS2.IsLvalueReference) ||
3389 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3390 !SCS2.IsLvalueReference);
3391}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003393/// CompareStandardConversionSequences - Compare two standard
3394/// conversion sequences to determine whether one is better than the
3395/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003396static ImplicitConversionSequence::CompareKind
3397CompareStandardConversionSequences(Sema &S,
3398 const StandardConversionSequence& SCS1,
3399 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003400{
3401 // Standard conversion sequence S1 is a better conversion sequence
3402 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3403
3404 // -- S1 is a proper subsequence of S2 (comparing the conversion
3405 // sequences in the canonical form defined by 13.3.3.1.1,
3406 // excluding any Lvalue Transformation; the identity conversion
3407 // sequence is considered to be a subsequence of any
3408 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003409 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003410 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003411 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003412
3413 // -- the rank of S1 is better than the rank of S2 (by the rules
3414 // defined below), or, if not that,
3415 ImplicitConversionRank Rank1 = SCS1.getRank();
3416 ImplicitConversionRank Rank2 = SCS2.getRank();
3417 if (Rank1 < Rank2)
3418 return ImplicitConversionSequence::Better;
3419 else if (Rank2 < Rank1)
3420 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003421
Douglas Gregor57373262008-10-22 14:17:15 +00003422 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3423 // are indistinguishable unless one of the following rules
3424 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Douglas Gregor57373262008-10-22 14:17:15 +00003426 // A conversion that is not a conversion of a pointer, or
3427 // pointer to member, to bool is better than another conversion
3428 // that is such a conversion.
3429 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3430 return SCS2.isPointerConversionToBool()
3431 ? ImplicitConversionSequence::Better
3432 : ImplicitConversionSequence::Worse;
3433
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003434 // C++ [over.ics.rank]p4b2:
3435 //
3436 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003437 // conversion of B* to A* is better than conversion of B* to
3438 // void*, and conversion of A* to void* is better than conversion
3439 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003440 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003441 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003442 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003443 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003444 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3445 // Exactly one of the conversion sequences is a conversion to
3446 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003447 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3448 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003449 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3450 // Neither conversion sequence converts to a void pointer; compare
3451 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003452 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003453 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003454 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003455 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3456 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003457 // Both conversion sequences are conversions to void
3458 // pointers. Compare the source types to determine if there's an
3459 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003460 QualType FromType1 = SCS1.getFromType();
3461 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003462
3463 // Adjust the types we're converting from via the array-to-pointer
3464 // conversion, if we need to.
3465 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003466 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003467 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003468 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003469
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003470 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3471 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003472
John McCall120d63c2010-08-24 20:38:10 +00003473 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003474 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003475 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003476 return ImplicitConversionSequence::Worse;
3477
3478 // Objective-C++: If one interface is more specific than the
3479 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003480 const ObjCObjectPointerType* FromObjCPtr1
3481 = FromType1->getAs<ObjCObjectPointerType>();
3482 const ObjCObjectPointerType* FromObjCPtr2
3483 = FromType2->getAs<ObjCObjectPointerType>();
3484 if (FromObjCPtr1 && FromObjCPtr2) {
3485 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3486 FromObjCPtr2);
3487 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3488 FromObjCPtr1);
3489 if (AssignLeft != AssignRight) {
3490 return AssignLeft? ImplicitConversionSequence::Better
3491 : ImplicitConversionSequence::Worse;
3492 }
Douglas Gregor01919692009-12-13 21:37:05 +00003493 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003494 }
Douglas Gregor57373262008-10-22 14:17:15 +00003495
3496 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3497 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003498 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003499 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003500 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003501
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003502 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003503 // Check for a better reference binding based on the kind of bindings.
3504 if (isBetterReferenceBindingKind(SCS1, SCS2))
3505 return ImplicitConversionSequence::Better;
3506 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3507 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003508
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003509 // C++ [over.ics.rank]p3b4:
3510 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3511 // which the references refer are the same type except for
3512 // top-level cv-qualifiers, and the type to which the reference
3513 // initialized by S2 refers is more cv-qualified than the type
3514 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003515 QualType T1 = SCS1.getToType(2);
3516 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003517 T1 = S.Context.getCanonicalType(T1);
3518 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003519 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003520 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3521 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003522 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003523 // Objective-C++ ARC: If the references refer to objects with different
3524 // lifetimes, prefer bindings that don't change lifetime.
3525 if (SCS1.ObjCLifetimeConversionBinding !=
3526 SCS2.ObjCLifetimeConversionBinding) {
3527 return SCS1.ObjCLifetimeConversionBinding
3528 ? ImplicitConversionSequence::Worse
3529 : ImplicitConversionSequence::Better;
3530 }
3531
Chandler Carruth6df868e2010-12-12 08:17:55 +00003532 // If the type is an array type, promote the element qualifiers to the
3533 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003534 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003535 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003536 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003537 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003538 if (T2.isMoreQualifiedThan(T1))
3539 return ImplicitConversionSequence::Better;
3540 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003541 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003542 }
3543 }
Douglas Gregor57373262008-10-22 14:17:15 +00003544
Francois Pichet1c98d622011-09-18 21:37:37 +00003545 // In Microsoft mode, prefer an integral conversion to a
3546 // floating-to-integral conversion if the integral conversion
3547 // is between types of the same size.
3548 // For example:
3549 // void f(float);
3550 // void f(int);
3551 // int main {
3552 // long a;
3553 // f(a);
3554 // }
3555 // Here, MSVC will call f(int) instead of generating a compile error
3556 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003557 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003558 SCS1.Second == ICK_Integral_Conversion &&
3559 SCS2.Second == ICK_Floating_Integral &&
3560 S.Context.getTypeSize(SCS1.getFromType()) ==
3561 S.Context.getTypeSize(SCS1.getToType(2)))
3562 return ImplicitConversionSequence::Better;
3563
Douglas Gregor57373262008-10-22 14:17:15 +00003564 return ImplicitConversionSequence::Indistinguishable;
3565}
3566
3567/// CompareQualificationConversions - Compares two standard conversion
3568/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003569/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3570ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003571CompareQualificationConversions(Sema &S,
3572 const StandardConversionSequence& SCS1,
3573 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003574 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003575 // -- S1 and S2 differ only in their qualification conversion and
3576 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3577 // cv-qualification signature of type T1 is a proper subset of
3578 // the cv-qualification signature of type T2, and S1 is not the
3579 // deprecated string literal array-to-pointer conversion (4.2).
3580 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3581 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3582 return ImplicitConversionSequence::Indistinguishable;
3583
3584 // FIXME: the example in the standard doesn't use a qualification
3585 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003586 QualType T1 = SCS1.getToType(2);
3587 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003588 T1 = S.Context.getCanonicalType(T1);
3589 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003590 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003591 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3592 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003593
3594 // If the types are the same, we won't learn anything by unwrapped
3595 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003596 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003597 return ImplicitConversionSequence::Indistinguishable;
3598
Chandler Carruth28e318c2009-12-29 07:16:59 +00003599 // If the type is an array type, promote the element qualifiers to the type
3600 // for comparison.
3601 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003602 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003603 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003604 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003605
Mike Stump1eb44332009-09-09 15:08:12 +00003606 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003607 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003608
3609 // Objective-C++ ARC:
3610 // Prefer qualification conversions not involving a change in lifetime
3611 // to qualification conversions that do not change lifetime.
3612 if (SCS1.QualificationIncludesObjCLifetime !=
3613 SCS2.QualificationIncludesObjCLifetime) {
3614 Result = SCS1.QualificationIncludesObjCLifetime
3615 ? ImplicitConversionSequence::Worse
3616 : ImplicitConversionSequence::Better;
3617 }
3618
John McCall120d63c2010-08-24 20:38:10 +00003619 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003620 // Within each iteration of the loop, we check the qualifiers to
3621 // determine if this still looks like a qualification
3622 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003623 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003624 // until there are no more pointers or pointers-to-members left
3625 // to unwrap. This essentially mimics what
3626 // IsQualificationConversion does, but here we're checking for a
3627 // strict subset of qualifiers.
3628 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3629 // The qualifiers are the same, so this doesn't tell us anything
3630 // about how the sequences rank.
3631 ;
3632 else if (T2.isMoreQualifiedThan(T1)) {
3633 // T1 has fewer qualifiers, so it could be the better sequence.
3634 if (Result == ImplicitConversionSequence::Worse)
3635 // Neither has qualifiers that are a subset of the other's
3636 // qualifiers.
3637 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Douglas Gregor57373262008-10-22 14:17:15 +00003639 Result = ImplicitConversionSequence::Better;
3640 } else if (T1.isMoreQualifiedThan(T2)) {
3641 // T2 has fewer qualifiers, so it could be the better sequence.
3642 if (Result == ImplicitConversionSequence::Better)
3643 // Neither has qualifiers that are a subset of the other's
3644 // qualifiers.
3645 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003646
Douglas Gregor57373262008-10-22 14:17:15 +00003647 Result = ImplicitConversionSequence::Worse;
3648 } else {
3649 // Qualifiers are disjoint.
3650 return ImplicitConversionSequence::Indistinguishable;
3651 }
3652
3653 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003654 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003655 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003656 }
3657
Douglas Gregor57373262008-10-22 14:17:15 +00003658 // Check that the winning standard conversion sequence isn't using
3659 // the deprecated string literal array to pointer conversion.
3660 switch (Result) {
3661 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003662 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003663 Result = ImplicitConversionSequence::Indistinguishable;
3664 break;
3665
3666 case ImplicitConversionSequence::Indistinguishable:
3667 break;
3668
3669 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003670 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003671 Result = ImplicitConversionSequence::Indistinguishable;
3672 break;
3673 }
3674
3675 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003676}
3677
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003678/// CompareDerivedToBaseConversions - Compares two standard conversion
3679/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003680/// various kinds of derived-to-base conversions (C++
3681/// [over.ics.rank]p4b3). As part of these checks, we also look at
3682/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003683ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003684CompareDerivedToBaseConversions(Sema &S,
3685 const StandardConversionSequence& SCS1,
3686 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003687 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003688 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003689 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003690 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003691
3692 // Adjust the types we're converting from via the array-to-pointer
3693 // conversion, if we need to.
3694 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003695 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003696 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003697 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003698
3699 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003700 FromType1 = S.Context.getCanonicalType(FromType1);
3701 ToType1 = S.Context.getCanonicalType(ToType1);
3702 FromType2 = S.Context.getCanonicalType(FromType2);
3703 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003704
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003705 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003706 //
3707 // If class B is derived directly or indirectly from class A and
3708 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003709 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003710 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003711 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003712 SCS2.Second == ICK_Pointer_Conversion &&
3713 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3714 FromType1->isPointerType() && FromType2->isPointerType() &&
3715 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003716 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003717 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003718 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003719 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003720 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003721 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003722 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003723 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003724
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003725 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003727 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003728 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003729 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003730 return ImplicitConversionSequence::Worse;
3731 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003732
3733 // -- conversion of B* to A* is better than conversion of C* to A*,
3734 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003735 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003736 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003737 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003738 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003739 }
3740 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3741 SCS2.Second == ICK_Pointer_Conversion) {
3742 const ObjCObjectPointerType *FromPtr1
3743 = FromType1->getAs<ObjCObjectPointerType>();
3744 const ObjCObjectPointerType *FromPtr2
3745 = FromType2->getAs<ObjCObjectPointerType>();
3746 const ObjCObjectPointerType *ToPtr1
3747 = ToType1->getAs<ObjCObjectPointerType>();
3748 const ObjCObjectPointerType *ToPtr2
3749 = ToType2->getAs<ObjCObjectPointerType>();
3750
3751 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3752 // Apply the same conversion ranking rules for Objective-C pointer types
3753 // that we do for C++ pointers to class types. However, we employ the
3754 // Objective-C pseudo-subtyping relationship used for assignment of
3755 // Objective-C pointer types.
3756 bool FromAssignLeft
3757 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3758 bool FromAssignRight
3759 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3760 bool ToAssignLeft
3761 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3762 bool ToAssignRight
3763 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3764
3765 // A conversion to an a non-id object pointer type or qualified 'id'
3766 // type is better than a conversion to 'id'.
3767 if (ToPtr1->isObjCIdType() &&
3768 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3769 return ImplicitConversionSequence::Worse;
3770 if (ToPtr2->isObjCIdType() &&
3771 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3772 return ImplicitConversionSequence::Better;
3773
3774 // A conversion to a non-id object pointer type is better than a
3775 // conversion to a qualified 'id' type
3776 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3777 return ImplicitConversionSequence::Worse;
3778 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3779 return ImplicitConversionSequence::Better;
3780
3781 // A conversion to an a non-Class object pointer type or qualified 'Class'
3782 // type is better than a conversion to 'Class'.
3783 if (ToPtr1->isObjCClassType() &&
3784 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3785 return ImplicitConversionSequence::Worse;
3786 if (ToPtr2->isObjCClassType() &&
3787 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3788 return ImplicitConversionSequence::Better;
3789
3790 // A conversion to a non-Class object pointer type is better than a
3791 // conversion to a qualified 'Class' type.
3792 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3793 return ImplicitConversionSequence::Worse;
3794 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3795 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003796
Douglas Gregor395cc372011-01-31 18:51:41 +00003797 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3798 if (S.Context.hasSameType(FromType1, FromType2) &&
3799 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3800 (ToAssignLeft != ToAssignRight))
3801 return ToAssignLeft? ImplicitConversionSequence::Worse
3802 : ImplicitConversionSequence::Better;
3803
3804 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3805 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3806 (FromAssignLeft != FromAssignRight))
3807 return FromAssignLeft? ImplicitConversionSequence::Better
3808 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003809 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003810 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003811
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003812 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003813 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3814 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3815 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003817 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003819 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003820 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003821 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003823 ToType2->getAs<MemberPointerType>();
3824 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3825 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3826 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3827 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3828 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3829 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3830 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3831 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003832 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003833 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003834 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003835 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003836 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003837 return ImplicitConversionSequence::Better;
3838 }
3839 // conversion of B::* to C::* is better than conversion of A::* to C::*
3840 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003841 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003842 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003843 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003844 return ImplicitConversionSequence::Worse;
3845 }
3846 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003847
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003848 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003849 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003850 // -- binding of an expression of type C to a reference of type
3851 // B& is better than binding an expression of type C to a
3852 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003853 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3854 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3855 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003856 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003857 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003858 return ImplicitConversionSequence::Worse;
3859 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003860
Douglas Gregor225c41e2008-11-03 19:09:14 +00003861 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003862 // -- binding of an expression of type B to a reference of type
3863 // A& is better than binding an expression of type C to a
3864 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003865 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3866 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3867 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003868 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003869 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003870 return ImplicitConversionSequence::Worse;
3871 }
3872 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003873
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003874 return ImplicitConversionSequence::Indistinguishable;
3875}
3876
Douglas Gregorabe183d2010-04-13 16:31:36 +00003877/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3878/// determine whether they are reference-related,
3879/// reference-compatible, reference-compatible with added
3880/// qualification, or incompatible, for use in C++ initialization by
3881/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3882/// type, and the first type (T1) is the pointee type of the reference
3883/// type being initialized.
3884Sema::ReferenceCompareResult
3885Sema::CompareReferenceRelationship(SourceLocation Loc,
3886 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003887 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003888 bool &ObjCConversion,
3889 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003890 assert(!OrigT1->isReferenceType() &&
3891 "T1 must be the pointee type of the reference type");
3892 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3893
3894 QualType T1 = Context.getCanonicalType(OrigT1);
3895 QualType T2 = Context.getCanonicalType(OrigT2);
3896 Qualifiers T1Quals, T2Quals;
3897 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3898 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3899
3900 // C++ [dcl.init.ref]p4:
3901 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3902 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3903 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003904 DerivedToBase = false;
3905 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003906 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003907 if (UnqualT1 == UnqualT2) {
3908 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003909 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003910 IsDerivedFrom(UnqualT2, UnqualT1))
3911 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003912 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3913 UnqualT2->isObjCObjectOrInterfaceType() &&
3914 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3915 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003916 else
3917 return Ref_Incompatible;
3918
3919 // At this point, we know that T1 and T2 are reference-related (at
3920 // least).
3921
3922 // If the type is an array type, promote the element qualifiers to the type
3923 // for comparison.
3924 if (isa<ArrayType>(T1) && T1Quals)
3925 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3926 if (isa<ArrayType>(T2) && T2Quals)
3927 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3928
3929 // C++ [dcl.init.ref]p4:
3930 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3931 // reference-related to T2 and cv1 is the same cv-qualification
3932 // as, or greater cv-qualification than, cv2. For purposes of
3933 // overload resolution, cases for which cv1 is greater
3934 // cv-qualification than cv2 are identified as
3935 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003936 //
3937 // Note that we also require equivalence of Objective-C GC and address-space
3938 // qualifiers when performing these computations, so that e.g., an int in
3939 // address space 1 is not reference-compatible with an int in address
3940 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003941 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3942 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3943 T1Quals.removeObjCLifetime();
3944 T2Quals.removeObjCLifetime();
3945 ObjCLifetimeConversion = true;
3946 }
3947
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003948 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003949 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003950 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003951 return Ref_Compatible_With_Added_Qualification;
3952 else
3953 return Ref_Related;
3954}
3955
Douglas Gregor604eb652010-08-11 02:15:33 +00003956/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003957/// with DeclType. Return true if something definite is found.
3958static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003959FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3960 QualType DeclType, SourceLocation DeclLoc,
3961 Expr *Init, QualType T2, bool AllowRvalues,
3962 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003963 assert(T2->isRecordType() && "Can only find conversions of record types.");
3964 CXXRecordDecl *T2RecordDecl
3965 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3966
3967 OverloadCandidateSet CandidateSet(DeclLoc);
3968 const UnresolvedSetImpl *Conversions
3969 = T2RecordDecl->getVisibleConversionFunctions();
3970 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3971 E = Conversions->end(); I != E; ++I) {
3972 NamedDecl *D = *I;
3973 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3974 if (isa<UsingShadowDecl>(D))
3975 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3976
3977 FunctionTemplateDecl *ConvTemplate
3978 = dyn_cast<FunctionTemplateDecl>(D);
3979 CXXConversionDecl *Conv;
3980 if (ConvTemplate)
3981 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3982 else
3983 Conv = cast<CXXConversionDecl>(D);
3984
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003985 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003986 // explicit conversions, skip it.
3987 if (!AllowExplicit && Conv->isExplicit())
3988 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003989
Douglas Gregor604eb652010-08-11 02:15:33 +00003990 if (AllowRvalues) {
3991 bool DerivedToBase = false;
3992 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003993 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003994
3995 // If we are initializing an rvalue reference, don't permit conversion
3996 // functions that return lvalues.
3997 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3998 const ReferenceType *RefType
3999 = Conv->getConversionType()->getAs<LValueReferenceType>();
4000 if (RefType && !RefType->getPointeeType()->isFunctionType())
4001 continue;
4002 }
4003
Douglas Gregor604eb652010-08-11 02:15:33 +00004004 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004005 S.CompareReferenceRelationship(
4006 DeclLoc,
4007 Conv->getConversionType().getNonReferenceType()
4008 .getUnqualifiedType(),
4009 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004010 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004011 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004012 continue;
4013 } else {
4014 // If the conversion function doesn't return a reference type,
4015 // it can't be considered for this conversion. An rvalue reference
4016 // is only acceptable if its referencee is a function type.
4017
4018 const ReferenceType *RefType =
4019 Conv->getConversionType()->getAs<ReferenceType>();
4020 if (!RefType ||
4021 (!RefType->isLValueReferenceType() &&
4022 !RefType->getPointeeType()->isFunctionType()))
4023 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004024 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004025
Douglas Gregor604eb652010-08-11 02:15:33 +00004026 if (ConvTemplate)
4027 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004028 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004029 else
4030 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004031 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004032 }
4033
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004034 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4035
Sebastian Redl4680bf22010-06-30 18:13:39 +00004036 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004037 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004038 case OR_Success:
4039 // C++ [over.ics.ref]p1:
4040 //
4041 // [...] If the parameter binds directly to the result of
4042 // applying a conversion function to the argument
4043 // expression, the implicit conversion sequence is a
4044 // user-defined conversion sequence (13.3.3.1.2), with the
4045 // second standard conversion sequence either an identity
4046 // conversion or, if the conversion function returns an
4047 // entity of a type that is a derived class of the parameter
4048 // type, a derived-to-base Conversion.
4049 if (!Best->FinalConversion.DirectBinding)
4050 return false;
4051
Chandler Carruth25ca4212011-02-25 19:41:05 +00004052 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004053 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004054 ICS.setUserDefined();
4055 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4056 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004057 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004058 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004059 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004060 ICS.UserDefined.EllipsisConversion = false;
4061 assert(ICS.UserDefined.After.ReferenceBinding &&
4062 ICS.UserDefined.After.DirectBinding &&
4063 "Expected a direct reference binding!");
4064 return true;
4065
4066 case OR_Ambiguous:
4067 ICS.setAmbiguous();
4068 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4069 Cand != CandidateSet.end(); ++Cand)
4070 if (Cand->Viable)
4071 ICS.Ambiguous.addConversion(Cand->Function);
4072 return true;
4073
4074 case OR_No_Viable_Function:
4075 case OR_Deleted:
4076 // There was no suitable conversion, or we found a deleted
4077 // conversion; continue with other checks.
4078 return false;
4079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004080
David Blaikie7530c032012-01-17 06:56:22 +00004081 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004082}
4083
Douglas Gregorabe183d2010-04-13 16:31:36 +00004084/// \brief Compute an implicit conversion sequence for reference
4085/// initialization.
4086static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004087TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004088 SourceLocation DeclLoc,
4089 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004090 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004091 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4092
4093 // Most paths end in a failed conversion.
4094 ImplicitConversionSequence ICS;
4095 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4096
4097 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4098 QualType T2 = Init->getType();
4099
4100 // If the initializer is the address of an overloaded function, try
4101 // to resolve the overloaded function. If all goes well, T2 is the
4102 // type of the resulting function.
4103 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4104 DeclAccessPair Found;
4105 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4106 false, Found))
4107 T2 = Fn->getType();
4108 }
4109
4110 // Compute some basic properties of the types and the initializer.
4111 bool isRValRef = DeclType->isRValueReferenceType();
4112 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004113 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004114 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004115 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004116 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004117 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004118 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004119
Douglas Gregorabe183d2010-04-13 16:31:36 +00004120
Sebastian Redl4680bf22010-06-30 18:13:39 +00004121 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004122 // A reference to type "cv1 T1" is initialized by an expression
4123 // of type "cv2 T2" as follows:
4124
Sebastian Redl4680bf22010-06-30 18:13:39 +00004125 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004126 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004127 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4128 // reference-compatible with "cv2 T2," or
4129 //
4130 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4131 if (InitCategory.isLValue() &&
4132 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004133 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004134 // When a parameter of reference type binds directly (8.5.3)
4135 // to an argument expression, the implicit conversion sequence
4136 // is the identity conversion, unless the argument expression
4137 // has a type that is a derived class of the parameter type,
4138 // in which case the implicit conversion sequence is a
4139 // derived-to-base Conversion (13.3.3.1).
4140 ICS.setStandard();
4141 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004142 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4143 : ObjCConversion? ICK_Compatible_Conversion
4144 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004145 ICS.Standard.Third = ICK_Identity;
4146 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4147 ICS.Standard.setToType(0, T2);
4148 ICS.Standard.setToType(1, T1);
4149 ICS.Standard.setToType(2, T1);
4150 ICS.Standard.ReferenceBinding = true;
4151 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004152 ICS.Standard.IsLvalueReference = !isRValRef;
4153 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4154 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004155 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004156 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004157 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004158
Sebastian Redl4680bf22010-06-30 18:13:39 +00004159 // Nothing more to do: the inaccessibility/ambiguity check for
4160 // derived-to-base conversions is suppressed when we're
4161 // computing the implicit conversion sequence (C++
4162 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004163 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004164 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004165
Sebastian Redl4680bf22010-06-30 18:13:39 +00004166 // -- has a class type (i.e., T2 is a class type), where T1 is
4167 // not reference-related to T2, and can be implicitly
4168 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4169 // is reference-compatible with "cv3 T3" 92) (this
4170 // conversion is selected by enumerating the applicable
4171 // conversion functions (13.3.1.6) and choosing the best
4172 // one through overload resolution (13.3)),
4173 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004174 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004175 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004176 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4177 Init, T2, /*AllowRvalues=*/false,
4178 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004179 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004180 }
4181 }
4182
Sebastian Redl4680bf22010-06-30 18:13:39 +00004183 // -- Otherwise, the reference shall be an lvalue reference to a
4184 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004185 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004186 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004187 // We actually handle one oddity of C++ [over.ics.ref] at this
4188 // point, which is that, due to p2 (which short-circuits reference
4189 // binding by only attempting a simple conversion for non-direct
4190 // bindings) and p3's strange wording, we allow a const volatile
4191 // reference to bind to an rvalue. Hence the check for the presence
4192 // of "const" rather than checking for "const" being the only
4193 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004194 // This is also the point where rvalue references and lvalue inits no longer
4195 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004196 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004197 return ICS;
4198
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004199 // -- If the initializer expression
4200 //
4201 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004202 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004203 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4204 (InitCategory.isXValue() ||
4205 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4206 (InitCategory.isLValue() && T2->isFunctionType()))) {
4207 ICS.setStandard();
4208 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004210 : ObjCConversion? ICK_Compatible_Conversion
4211 : ICK_Identity;
4212 ICS.Standard.Third = ICK_Identity;
4213 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4214 ICS.Standard.setToType(0, T2);
4215 ICS.Standard.setToType(1, T1);
4216 ICS.Standard.setToType(2, T1);
4217 ICS.Standard.ReferenceBinding = true;
4218 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4219 // binding unless we're binding to a class prvalue.
4220 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4221 // allow the use of rvalue references in C++98/03 for the benefit of
4222 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004224 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004225 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004226 ICS.Standard.IsLvalueReference = !isRValRef;
4227 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004228 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004229 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004230 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004231 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004232 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004233 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004234
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004235 // -- has a class type (i.e., T2 is a class type), where T1 is not
4236 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237 // an xvalue, class prvalue, or function lvalue of type
4238 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004239 // "cv3 T3",
4240 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004241 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004242 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004243 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004244 // class subobject).
4245 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004247 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4248 Init, T2, /*AllowRvalues=*/true,
4249 AllowExplicit)) {
4250 // In the second case, if the reference is an rvalue reference
4251 // and the second standard conversion sequence of the
4252 // user-defined conversion sequence includes an lvalue-to-rvalue
4253 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004254 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004255 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4256 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4257
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004258 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004259 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004260
Douglas Gregorabe183d2010-04-13 16:31:36 +00004261 // -- Otherwise, a temporary of type "cv1 T1" is created and
4262 // initialized from the initializer expression using the
4263 // rules for a non-reference copy initialization (8.5). The
4264 // reference is then bound to the temporary. If T1 is
4265 // reference-related to T2, cv1 must be the same
4266 // cv-qualification as, or greater cv-qualification than,
4267 // cv2; otherwise, the program is ill-formed.
4268 if (RefRelationship == Sema::Ref_Related) {
4269 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4270 // we would be reference-compatible or reference-compatible with
4271 // added qualification. But that wasn't the case, so the reference
4272 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004273 //
4274 // Note that we only want to check address spaces and cvr-qualifiers here.
4275 // ObjC GC and lifetime qualifiers aren't important.
4276 Qualifiers T1Quals = T1.getQualifiers();
4277 Qualifiers T2Quals = T2.getQualifiers();
4278 T1Quals.removeObjCGCAttr();
4279 T1Quals.removeObjCLifetime();
4280 T2Quals.removeObjCGCAttr();
4281 T2Quals.removeObjCLifetime();
4282 if (!T1Quals.compatiblyIncludes(T2Quals))
4283 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004284 }
4285
4286 // If at least one of the types is a class type, the types are not
4287 // related, and we aren't allowed any user conversions, the
4288 // reference binding fails. This case is important for breaking
4289 // recursion, since TryImplicitConversion below will attempt to
4290 // create a temporary through the use of a copy constructor.
4291 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4292 (T1->isRecordType() || T2->isRecordType()))
4293 return ICS;
4294
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004295 // If T1 is reference-related to T2 and the reference is an rvalue
4296 // reference, the initializer expression shall not be an lvalue.
4297 if (RefRelationship >= Sema::Ref_Related &&
4298 isRValRef && Init->Classify(S.Context).isLValue())
4299 return ICS;
4300
Douglas Gregorabe183d2010-04-13 16:31:36 +00004301 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004302 // When a parameter of reference type is not bound directly to
4303 // an argument expression, the conversion sequence is the one
4304 // required to convert the argument expression to the
4305 // underlying type of the reference according to
4306 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4307 // to copy-initializing a temporary of the underlying type with
4308 // the argument expression. Any difference in top-level
4309 // cv-qualification is subsumed by the initialization itself
4310 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004311 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4312 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004313 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004314 /*CStyle=*/false,
4315 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004316
4317 // Of course, that's still a reference binding.
4318 if (ICS.isStandard()) {
4319 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004320 ICS.Standard.IsLvalueReference = !isRValRef;
4321 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4322 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004323 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004324 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004325 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004326 // Don't allow rvalue references to bind to lvalues.
4327 if (DeclType->isRValueReferenceType()) {
4328 if (const ReferenceType *RefType
4329 = ICS.UserDefined.ConversionFunction->getResultType()
4330 ->getAs<LValueReferenceType>()) {
4331 if (!RefType->getPointeeType()->isFunctionType()) {
4332 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4333 DeclType);
4334 return ICS;
4335 }
4336 }
4337 }
4338
Douglas Gregorabe183d2010-04-13 16:31:36 +00004339 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004340 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4341 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4342 ICS.UserDefined.After.BindsToRvalue = true;
4343 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4344 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004345 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004346
Douglas Gregorabe183d2010-04-13 16:31:36 +00004347 return ICS;
4348}
4349
Sebastian Redl5405b812011-10-16 18:19:34 +00004350static ImplicitConversionSequence
4351TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4352 bool SuppressUserConversions,
4353 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004354 bool AllowObjCWritebackConversion,
4355 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004356
4357/// TryListConversion - Try to copy-initialize a value of type ToType from the
4358/// initializer list From.
4359static ImplicitConversionSequence
4360TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4361 bool SuppressUserConversions,
4362 bool InOverloadResolution,
4363 bool AllowObjCWritebackConversion) {
4364 // C++11 [over.ics.list]p1:
4365 // When an argument is an initializer list, it is not an expression and
4366 // special rules apply for converting it to a parameter type.
4367
4368 ImplicitConversionSequence Result;
4369 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004370 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004371
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004372 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004373 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004374 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004375 return Result;
4376
Sebastian Redl5405b812011-10-16 18:19:34 +00004377 // C++11 [over.ics.list]p2:
4378 // If the parameter type is std::initializer_list<X> or "array of X" and
4379 // all the elements can be implicitly converted to X, the implicit
4380 // conversion sequence is the worst conversion necessary to convert an
4381 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004382 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004383 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004384 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004385 X = S.Context.getBaseElementType(ToType);
4386 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004387 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004388 if (!X.isNull()) {
4389 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4390 Expr *Init = From->getInit(i);
4391 ImplicitConversionSequence ICS =
4392 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4393 InOverloadResolution,
4394 AllowObjCWritebackConversion);
4395 // If a single element isn't convertible, fail.
4396 if (ICS.isBad()) {
4397 Result = ICS;
4398 break;
4399 }
4400 // Otherwise, look for the worst conversion.
4401 if (Result.isBad() ||
4402 CompareImplicitConversionSequences(S, ICS, Result) ==
4403 ImplicitConversionSequence::Worse)
4404 Result = ICS;
4405 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004406
4407 // For an empty list, we won't have computed any conversion sequence.
4408 // Introduce the identity conversion sequence.
4409 if (From->getNumInits() == 0) {
4410 Result.setStandard();
4411 Result.Standard.setAsIdentityConversion();
4412 Result.Standard.setFromType(ToType);
4413 Result.Standard.setAllToTypes(ToType);
4414 }
4415
Sebastian Redlfe592282012-01-17 22:49:48 +00004416 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004417 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004418 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004419 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004420
4421 // C++11 [over.ics.list]p3:
4422 // Otherwise, if the parameter is a non-aggregate class X and overload
4423 // resolution chooses a single best constructor [...] the implicit
4424 // conversion sequence is a user-defined conversion sequence. If multiple
4425 // constructors are viable but none is better than the others, the
4426 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004427 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4428 // This function can deal with initializer lists.
4429 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4430 /*AllowExplicit=*/false,
4431 InOverloadResolution, /*CStyle=*/false,
4432 AllowObjCWritebackConversion);
4433 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004434 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004435 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004436
4437 // C++11 [over.ics.list]p4:
4438 // Otherwise, if the parameter has an aggregate type which can be
4439 // initialized from the initializer list [...] the implicit conversion
4440 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004441 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004442 // Type is an aggregate, argument is an init list. At this point it comes
4443 // down to checking whether the initialization works.
4444 // FIXME: Find out whether this parameter is consumed or not.
4445 InitializedEntity Entity =
4446 InitializedEntity::InitializeParameter(S.Context, ToType,
4447 /*Consumed=*/false);
4448 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4449 Result.setUserDefined();
4450 Result.UserDefined.Before.setAsIdentityConversion();
4451 // Initializer lists don't have a type.
4452 Result.UserDefined.Before.setFromType(QualType());
4453 Result.UserDefined.Before.setAllToTypes(QualType());
4454
4455 Result.UserDefined.After.setAsIdentityConversion();
4456 Result.UserDefined.After.setFromType(ToType);
4457 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004458 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004459 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004460 return Result;
4461 }
4462
4463 // C++11 [over.ics.list]p5:
4464 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004465 if (ToType->isReferenceType()) {
4466 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4467 // mention initializer lists in any way. So we go by what list-
4468 // initialization would do and try to extrapolate from that.
4469
4470 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4471
4472 // If the initializer list has a single element that is reference-related
4473 // to the parameter type, we initialize the reference from that.
4474 if (From->getNumInits() == 1) {
4475 Expr *Init = From->getInit(0);
4476
4477 QualType T2 = Init->getType();
4478
4479 // If the initializer is the address of an overloaded function, try
4480 // to resolve the overloaded function. If all goes well, T2 is the
4481 // type of the resulting function.
4482 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4483 DeclAccessPair Found;
4484 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4485 Init, ToType, false, Found))
4486 T2 = Fn->getType();
4487 }
4488
4489 // Compute some basic properties of the types and the initializer.
4490 bool dummy1 = false;
4491 bool dummy2 = false;
4492 bool dummy3 = false;
4493 Sema::ReferenceCompareResult RefRelationship
4494 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4495 dummy2, dummy3);
4496
4497 if (RefRelationship >= Sema::Ref_Related)
4498 return TryReferenceInit(S, Init, ToType,
4499 /*FIXME:*/From->getLocStart(),
4500 SuppressUserConversions,
4501 /*AllowExplicit=*/false);
4502 }
4503
4504 // Otherwise, we bind the reference to a temporary created from the
4505 // initializer list.
4506 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4507 InOverloadResolution,
4508 AllowObjCWritebackConversion);
4509 if (Result.isFailure())
4510 return Result;
4511 assert(!Result.isEllipsis() &&
4512 "Sub-initialization cannot result in ellipsis conversion.");
4513
4514 // Can we even bind to a temporary?
4515 if (ToType->isRValueReferenceType() ||
4516 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4517 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4518 Result.UserDefined.After;
4519 SCS.ReferenceBinding = true;
4520 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4521 SCS.BindsToRvalue = true;
4522 SCS.BindsToFunctionLvalue = false;
4523 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4524 SCS.ObjCLifetimeConversionBinding = false;
4525 } else
4526 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4527 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004528 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004529 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004530
4531 // C++11 [over.ics.list]p6:
4532 // Otherwise, if the parameter type is not a class:
4533 if (!ToType->isRecordType()) {
4534 // - if the initializer list has one element, the implicit conversion
4535 // sequence is the one required to convert the element to the
4536 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004537 unsigned NumInits = From->getNumInits();
4538 if (NumInits == 1)
4539 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4540 SuppressUserConversions,
4541 InOverloadResolution,
4542 AllowObjCWritebackConversion);
4543 // - if the initializer list has no elements, the implicit conversion
4544 // sequence is the identity conversion.
4545 else if (NumInits == 0) {
4546 Result.setStandard();
4547 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004548 Result.Standard.setFromType(ToType);
4549 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004550 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004551 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004552 return Result;
4553 }
4554
4555 // C++11 [over.ics.list]p7:
4556 // In all cases other than those enumerated above, no conversion is possible
4557 return Result;
4558}
4559
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004560/// TryCopyInitialization - Try to copy-initialize a value of type
4561/// ToType from the expression From. Return the implicit conversion
4562/// sequence required to pass this argument, which may be a bad
4563/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004564/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004565/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004566static ImplicitConversionSequence
4567TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004569 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004570 bool AllowObjCWritebackConversion,
4571 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004572 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4573 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4574 InOverloadResolution,AllowObjCWritebackConversion);
4575
Douglas Gregorabe183d2010-04-13 16:31:36 +00004576 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004577 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004578 /*FIXME:*/From->getLocStart(),
4579 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004580 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004581
John McCall120d63c2010-08-24 20:38:10 +00004582 return TryImplicitConversion(S, From, ToType,
4583 SuppressUserConversions,
4584 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004585 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004586 /*CStyle=*/false,
4587 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004588}
4589
Anna Zaksf3546ee2011-07-28 19:46:48 +00004590static bool TryCopyInitialization(const CanQualType FromQTy,
4591 const CanQualType ToQTy,
4592 Sema &S,
4593 SourceLocation Loc,
4594 ExprValueKind FromVK) {
4595 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4596 ImplicitConversionSequence ICS =
4597 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4598
4599 return !ICS.isBad();
4600}
4601
Douglas Gregor96176b32008-11-18 23:14:02 +00004602/// TryObjectArgumentInitialization - Try to initialize the object
4603/// parameter of the given member function (@c Method) from the
4604/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004605static ImplicitConversionSequence
4606TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004607 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004608 CXXMethodDecl *Method,
4609 CXXRecordDecl *ActingContext) {
4610 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004611 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4612 // const volatile object.
4613 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4614 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004615 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004616
4617 // Set up the conversion sequence as a "bad" conversion, to allow us
4618 // to exit early.
4619 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004620
4621 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004622 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004623 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004624 FromType = PT->getPointeeType();
4625
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004626 // When we had a pointer, it's implicitly dereferenced, so we
4627 // better have an lvalue.
4628 assert(FromClassification.isLValue());
4629 }
4630
Anders Carlssona552f7c2009-05-01 18:34:30 +00004631 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004632
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004633 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004635 // parameter is
4636 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004637 // - "lvalue reference to cv X" for functions declared without a
4638 // ref-qualifier or with the & ref-qualifier
4639 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004640 // ref-qualifier
4641 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004642 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004643 // cv-qualification on the member function declaration.
4644 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004645 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004646 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004647 // (C++ [over.match.funcs]p5). We perform a simplified version of
4648 // reference binding here, that allows class rvalues to bind to
4649 // non-constant references.
4650
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004651 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004652 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004653 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004654 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004655 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004656 ICS.setBad(BadConversionSequence::bad_qualifiers,
4657 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004658 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004659 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004660
4661 // Check that we have either the same type or a derived type. It
4662 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004663 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004664 ImplicitConversionKind SecondKind;
4665 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4666 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004667 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004668 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004669 else {
John McCallb1bdc622010-02-25 01:37:24 +00004670 ICS.setBad(BadConversionSequence::unrelated_class,
4671 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004672 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004673 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004674
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004675 // Check the ref-qualifier.
4676 switch (Method->getRefQualifier()) {
4677 case RQ_None:
4678 // Do nothing; we don't care about lvalueness or rvalueness.
4679 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004681 case RQ_LValue:
4682 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4683 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004684 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004685 ImplicitParamType);
4686 return ICS;
4687 }
4688 break;
4689
4690 case RQ_RValue:
4691 if (!FromClassification.isRValue()) {
4692 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004693 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004694 ImplicitParamType);
4695 return ICS;
4696 }
4697 break;
4698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004699
Douglas Gregor96176b32008-11-18 23:14:02 +00004700 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004701 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004702 ICS.Standard.setAsIdentityConversion();
4703 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004704 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004705 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004706 ICS.Standard.ReferenceBinding = true;
4707 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004708 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004709 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004710 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4711 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4712 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004713 return ICS;
4714}
4715
4716/// PerformObjectArgumentInitialization - Perform initialization of
4717/// the implicit object parameter for the given Method with the given
4718/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004719ExprResult
4720Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004721 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004722 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004723 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004724 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004725 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004726 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004728 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004729 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004730 FromRecordType = PT->getPointeeType();
4731 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004732 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004733 } else {
4734 FromRecordType = From->getType();
4735 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004736 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004737 }
4738
John McCall701c89e2009-12-03 04:06:58 +00004739 // Note that we always use the true parent context when performing
4740 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004741 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004742 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4743 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004744 if (ICS.isBad()) {
4745 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4746 Qualifiers FromQs = FromRecordType.getQualifiers();
4747 Qualifiers ToQs = DestType.getQualifiers();
4748 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4749 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004750 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004751 diag::err_member_function_call_bad_cvr)
4752 << Method->getDeclName() << FromRecordType << (CVR - 1)
4753 << From->getSourceRange();
4754 Diag(Method->getLocation(), diag::note_previous_decl)
4755 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004756 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004757 }
4758 }
4759
Daniel Dunbar96a00142012-03-09 18:35:03 +00004760 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004761 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004762 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004763 }
Mike Stump1eb44332009-09-09 15:08:12 +00004764
John Wiegley429bb272011-04-08 18:41:53 +00004765 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4766 ExprResult FromRes =
4767 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4768 if (FromRes.isInvalid())
4769 return ExprError();
4770 From = FromRes.take();
4771 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004772
Douglas Gregor5fccd362010-03-03 23:55:11 +00004773 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004774 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004775 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004776 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004777}
4778
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004779/// TryContextuallyConvertToBool - Attempt to contextually convert the
4780/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004781static ImplicitConversionSequence
4782TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004783 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004784 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004785 // FIXME: Are these flags correct?
4786 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004787 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004788 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004789 /*CStyle=*/false,
4790 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004791}
4792
4793/// PerformContextuallyConvertToBool - Perform a contextual conversion
4794/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004795ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004796 if (checkPlaceholderForOverload(*this, From))
4797 return ExprError();
4798
John McCall120d63c2010-08-24 20:38:10 +00004799 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004800 if (!ICS.isBad())
4801 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004802
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004803 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004804 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004805 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004806 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004807 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004808}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004809
Richard Smith8ef7b202012-01-18 23:55:52 +00004810/// Check that the specified conversion is permitted in a converted constant
4811/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4812/// is acceptable.
4813static bool CheckConvertedConstantConversions(Sema &S,
4814 StandardConversionSequence &SCS) {
4815 // Since we know that the target type is an integral or unscoped enumeration
4816 // type, most conversion kinds are impossible. All possible First and Third
4817 // conversions are fine.
4818 switch (SCS.Second) {
4819 case ICK_Identity:
4820 case ICK_Integral_Promotion:
4821 case ICK_Integral_Conversion:
4822 return true;
4823
4824 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004825 // Conversion from an integral or unscoped enumeration type to bool is
4826 // classified as ICK_Boolean_Conversion, but it's also an integral
4827 // conversion, so it's permitted in a converted constant expression.
4828 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4829 SCS.getToType(2)->isBooleanType();
4830
Richard Smith8ef7b202012-01-18 23:55:52 +00004831 case ICK_Floating_Integral:
4832 case ICK_Complex_Real:
4833 return false;
4834
4835 case ICK_Lvalue_To_Rvalue:
4836 case ICK_Array_To_Pointer:
4837 case ICK_Function_To_Pointer:
4838 case ICK_NoReturn_Adjustment:
4839 case ICK_Qualification:
4840 case ICK_Compatible_Conversion:
4841 case ICK_Vector_Conversion:
4842 case ICK_Vector_Splat:
4843 case ICK_Derived_To_Base:
4844 case ICK_Pointer_Conversion:
4845 case ICK_Pointer_Member:
4846 case ICK_Block_Pointer_Conversion:
4847 case ICK_Writeback_Conversion:
4848 case ICK_Floating_Promotion:
4849 case ICK_Complex_Promotion:
4850 case ICK_Complex_Conversion:
4851 case ICK_Floating_Conversion:
4852 case ICK_TransparentUnionConversion:
4853 llvm_unreachable("unexpected second conversion kind");
4854
4855 case ICK_Num_Conversion_Kinds:
4856 break;
4857 }
4858
4859 llvm_unreachable("unknown conversion kind");
4860}
4861
4862/// CheckConvertedConstantExpression - Check that the expression From is a
4863/// converted constant expression of type T, perform the conversion and produce
4864/// the converted expression, per C++11 [expr.const]p3.
4865ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4866 llvm::APSInt &Value,
4867 CCEKind CCE) {
4868 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4869 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4870
4871 if (checkPlaceholderForOverload(*this, From))
4872 return ExprError();
4873
4874 // C++11 [expr.const]p3 with proposed wording fixes:
4875 // A converted constant expression of type T is a core constant expression,
4876 // implicitly converted to a prvalue of type T, where the converted
4877 // expression is a literal constant expression and the implicit conversion
4878 // sequence contains only user-defined conversions, lvalue-to-rvalue
4879 // conversions, integral promotions, and integral conversions other than
4880 // narrowing conversions.
4881 ImplicitConversionSequence ICS =
4882 TryImplicitConversion(From, T,
4883 /*SuppressUserConversions=*/false,
4884 /*AllowExplicit=*/false,
4885 /*InOverloadResolution=*/false,
4886 /*CStyle=*/false,
4887 /*AllowObjcWritebackConversion=*/false);
4888 StandardConversionSequence *SCS = 0;
4889 switch (ICS.getKind()) {
4890 case ImplicitConversionSequence::StandardConversion:
4891 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004892 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004893 diag::err_typecheck_converted_constant_expression_disallowed)
4894 << From->getType() << From->getSourceRange() << T;
4895 SCS = &ICS.Standard;
4896 break;
4897 case ImplicitConversionSequence::UserDefinedConversion:
4898 // We are converting from class type to an integral or enumeration type, so
4899 // the Before sequence must be trivial.
4900 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004901 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004902 diag::err_typecheck_converted_constant_expression_disallowed)
4903 << From->getType() << From->getSourceRange() << T;
4904 SCS = &ICS.UserDefined.After;
4905 break;
4906 case ImplicitConversionSequence::AmbiguousConversion:
4907 case ImplicitConversionSequence::BadConversion:
4908 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004909 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004910 diag::err_typecheck_converted_constant_expression)
4911 << From->getType() << From->getSourceRange() << T;
4912 return ExprError();
4913
4914 case ImplicitConversionSequence::EllipsisConversion:
4915 llvm_unreachable("ellipsis conversion in converted constant expression");
4916 }
4917
4918 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4919 if (Result.isInvalid())
4920 return Result;
4921
4922 // Check for a narrowing implicit conversion.
4923 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004924 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004925 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4926 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004927 case NK_Variable_Narrowing:
4928 // Implicit conversion to a narrower type, and the value is not a constant
4929 // expression. We'll diagnose this in a moment.
4930 case NK_Not_Narrowing:
4931 break;
4932
4933 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004934 Diag(From->getLocStart(),
4935 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4936 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004937 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004938 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004939 break;
4940
4941 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004942 Diag(From->getLocStart(),
4943 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4944 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004945 << CCE << /*Constant*/0 << From->getType() << T;
4946 break;
4947 }
4948
4949 // Check the expression is a constant expression.
4950 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4951 Expr::EvalResult Eval;
4952 Eval.Diag = &Notes;
4953
4954 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4955 // The expression can't be folded, so we can't keep it at this position in
4956 // the AST.
4957 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004958 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004959 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004960
4961 if (Notes.empty()) {
4962 // It's a constant expression.
4963 return Result;
4964 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004965 }
4966
4967 // It's not a constant expression. Produce an appropriate diagnostic.
4968 if (Notes.size() == 1 &&
4969 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4970 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4971 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004972 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004973 << CCE << From->getSourceRange();
4974 for (unsigned I = 0; I < Notes.size(); ++I)
4975 Diag(Notes[I].first, Notes[I].second);
4976 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004977 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004978}
4979
John McCall0bcc9bc2011-09-09 06:11:02 +00004980/// dropPointerConversions - If the given standard conversion sequence
4981/// involves any pointer conversions, remove them. This may change
4982/// the result type of the conversion sequence.
4983static void dropPointerConversion(StandardConversionSequence &SCS) {
4984 if (SCS.Second == ICK_Pointer_Conversion) {
4985 SCS.Second = ICK_Identity;
4986 SCS.Third = ICK_Identity;
4987 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4988 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004989}
John McCall120d63c2010-08-24 20:38:10 +00004990
John McCall0bcc9bc2011-09-09 06:11:02 +00004991/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4992/// convert the expression From to an Objective-C pointer type.
4993static ImplicitConversionSequence
4994TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4995 // Do an implicit conversion to 'id'.
4996 QualType Ty = S.Context.getObjCIdType();
4997 ImplicitConversionSequence ICS
4998 = TryImplicitConversion(S, From, Ty,
4999 // FIXME: Are these flags correct?
5000 /*SuppressUserConversions=*/false,
5001 /*AllowExplicit=*/true,
5002 /*InOverloadResolution=*/false,
5003 /*CStyle=*/false,
5004 /*AllowObjCWritebackConversion=*/false);
5005
5006 // Strip off any final conversions to 'id'.
5007 switch (ICS.getKind()) {
5008 case ImplicitConversionSequence::BadConversion:
5009 case ImplicitConversionSequence::AmbiguousConversion:
5010 case ImplicitConversionSequence::EllipsisConversion:
5011 break;
5012
5013 case ImplicitConversionSequence::UserDefinedConversion:
5014 dropPointerConversion(ICS.UserDefined.After);
5015 break;
5016
5017 case ImplicitConversionSequence::StandardConversion:
5018 dropPointerConversion(ICS.Standard);
5019 break;
5020 }
5021
5022 return ICS;
5023}
5024
5025/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5026/// conversion of the expression From to an Objective-C pointer type.
5027ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005028 if (checkPlaceholderForOverload(*this, From))
5029 return ExprError();
5030
John McCallc12c5bb2010-05-15 11:32:37 +00005031 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005032 ImplicitConversionSequence ICS =
5033 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005034 if (!ICS.isBad())
5035 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005036 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005037}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005038
Richard Smithf39aec12012-02-04 07:07:42 +00005039/// Determine whether the provided type is an integral type, or an enumeration
5040/// type of a permitted flavor.
5041static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5042 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5043 : T->isIntegralOrUnscopedEnumerationType();
5044}
5045
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005046/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005047/// enumeration type.
5048///
5049/// This routine will attempt to convert an expression of class type to an
5050/// integral or enumeration type, if that class type only has a single
5051/// conversion to an integral or enumeration type.
5052///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005053/// \param Loc The source location of the construct that requires the
5054/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005055///
James Dennett40ae6662012-06-22 08:52:37 +00005056/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005057///
James Dennett40ae6662012-06-22 08:52:37 +00005058/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005059///
Richard Smithf39aec12012-02-04 07:07:42 +00005060/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5061/// enumerations should be considered.
5062///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005063/// \returns The expression, converted to an integral or enumeration type if
5064/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005065ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005066Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005067 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005068 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005069 // We can't perform any more checking for type-dependent expressions.
5070 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005071 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005072
Eli Friedmanceccab92012-01-26 00:26:18 +00005073 // Process placeholders immediately.
5074 if (From->hasPlaceholderType()) {
5075 ExprResult result = CheckPlaceholderExpr(From);
5076 if (result.isInvalid()) return result;
5077 From = result.take();
5078 }
5079
Douglas Gregorc30614b2010-06-29 23:17:37 +00005080 // If the expression already has integral or enumeration type, we're golden.
5081 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005082 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005083 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005084
5085 // FIXME: Check for missing '()' if T is a function type?
5086
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087 // 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 +00005088 // expression of integral or enumeration type.
5089 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005090 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005091 if (!Diagnoser.Suppress)
5092 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005093 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005094 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005095
Douglas Gregorc30614b2010-06-29 23:17:37 +00005096 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005097 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005098 ICEConvertDiagnoser &Diagnoser;
5099 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005100
Douglas Gregorab41fe92012-05-04 22:38:52 +00005101 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5102 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005103
5104 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005105 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005106 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005107 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005108
5109 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005110 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005111
Douglas Gregorc30614b2010-06-29 23:17:37 +00005112 // Look for a conversion to an integral or enumeration type.
5113 UnresolvedSet<4> ViableConversions;
5114 UnresolvedSet<4> ExplicitConversions;
5115 const UnresolvedSetImpl *Conversions
5116 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005117
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005118 bool HadMultipleCandidates = (Conversions->size() > 1);
5119
Douglas Gregorc30614b2010-06-29 23:17:37 +00005120 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005121 E = Conversions->end();
5122 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005123 ++I) {
5124 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005125 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5126 if (isIntegralOrEnumerationType(
5127 Conversion->getConversionType().getNonReferenceType(),
5128 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005129 if (Conversion->isExplicit())
5130 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5131 else
5132 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5133 }
Richard Smithf39aec12012-02-04 07:07:42 +00005134 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005136
Douglas Gregorc30614b2010-06-29 23:17:37 +00005137 switch (ViableConversions.size()) {
5138 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005139 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005140 DeclAccessPair Found = ExplicitConversions[0];
5141 CXXConversionDecl *Conversion
5142 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005143
Douglas Gregorc30614b2010-06-29 23:17:37 +00005144 // The user probably meant to invoke the given explicit
5145 // conversion; use it.
5146 QualType ConvTy
5147 = Conversion->getConversionType().getNonReferenceType();
5148 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005149 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005150
Douglas Gregorab41fe92012-05-04 22:38:52 +00005151 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005152 << FixItHint::CreateInsertion(From->getLocStart(),
5153 "static_cast<" + TypeStr + ">(")
5154 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5155 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005156 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
5158 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005159 // explicit conversion function.
5160 if (isSFINAEContext())
5161 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005162
Douglas Gregorc30614b2010-06-29 23:17:37 +00005163 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005164 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5165 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005166 if (Result.isInvalid())
5167 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005168 // Record usage of conversion in an implicit cast.
5169 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5170 CK_UserDefinedConversion,
5171 Result.get(), 0,
5172 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005173 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005174
Douglas Gregorc30614b2010-06-29 23:17:37 +00005175 // We'll complain below about a non-integral condition type.
5176 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005177
Douglas Gregorc30614b2010-06-29 23:17:37 +00005178 case 1: {
5179 // Apply this conversion.
5180 DeclAccessPair Found = ViableConversions[0];
5181 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005182
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005183 CXXConversionDecl *Conversion
5184 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5185 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005186 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005187 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005188 if (isSFINAEContext())
5189 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005190
Douglas Gregorab41fe92012-05-04 22:38:52 +00005191 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5192 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005193 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005194
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005195 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5196 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005197 if (Result.isInvalid())
5198 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005199 // Record usage of conversion in an implicit cast.
5200 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5201 CK_UserDefinedConversion,
5202 Result.get(), 0,
5203 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005204 break;
5205 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005206
Douglas Gregorc30614b2010-06-29 23:17:37 +00005207 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005208 if (Diagnoser.Suppress)
5209 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005210
Douglas Gregorab41fe92012-05-04 22:38:52 +00005211 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005212 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5213 CXXConversionDecl *Conv
5214 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5215 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005216 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005217 }
John McCall9ae2f072010-08-23 23:25:46 +00005218 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005220
Richard Smith282e7e62012-02-04 09:53:13 +00005221 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005222 !Diagnoser.Suppress) {
5223 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5224 << From->getSourceRange();
5225 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005226
Eli Friedmanceccab92012-01-26 00:26:18 +00005227 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005228}
5229
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005230/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005231/// candidate functions, using the given function call arguments. If
5232/// @p SuppressUserConversions, then don't allow user-defined
5233/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005234///
James Dennett699c9042012-06-15 07:13:21 +00005235/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005236/// based on an incomplete set of function arguments. This feature is used by
5237/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005238void
5239Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005240 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005241 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005242 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005243 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005244 bool PartialOverloading,
5245 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005246 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005247 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005248 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005249 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005250 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005251
Douglas Gregor88a35142008-12-22 05:46:06 +00005252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005253 if (!isa<CXXConstructorDecl>(Method)) {
5254 // If we get here, it's because we're calling a member function
5255 // that is named without a member access expression (e.g.,
5256 // "this->f") that was either written explicitly or created
5257 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005258 // function, e.g., X::f(). We use an empty type for the implied
5259 // object argument (C++ [over.call.func]p3), and the acting context
5260 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005261 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005263 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005264 return;
5265 }
5266 // We treat a constructor like a non-member function, since its object
5267 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005268 }
5269
Douglas Gregorfd476482009-11-13 23:59:09 +00005270 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005271 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005272
Douglas Gregor7edfb692009-11-23 12:27:39 +00005273 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005274 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005275
Douglas Gregor66724ea2009-11-14 01:20:54 +00005276 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5277 // C++ [class.copy]p3:
5278 // A member function template is never instantiated to perform the copy
5279 // of a class object to an object of its class type.
5280 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005281 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005282 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005283 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5284 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005285 return;
5286 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005287
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005288 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005289 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005290 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005291 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005292 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005293 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005294 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005295 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005296
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005297 unsigned NumArgsInProto = Proto->getNumArgs();
5298
5299 // (C++ 13.3.2p2): A candidate function having fewer than m
5300 // parameters is viable only if it has an ellipsis in its parameter
5301 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005302 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005303 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005304 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005305 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005306 return;
5307 }
5308
5309 // (C++ 13.3.2p2): A candidate function having more than m parameters
5310 // is viable only if the (m+1)st parameter has a default argument
5311 // (8.3.6). For the purposes of overload resolution, the
5312 // parameter list is truncated on the right, so that there are
5313 // exactly m parameters.
5314 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005315 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005316 // Not enough arguments.
5317 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005318 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005319 return;
5320 }
5321
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005322 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005323 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005324 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5325 if (CheckCUDATarget(Caller, Function)) {
5326 Candidate.Viable = false;
5327 Candidate.FailureKind = ovl_fail_bad_target;
5328 return;
5329 }
5330
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005331 // Determine the implicit conversion sequences for each of the
5332 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005333 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005334 if (ArgIdx < NumArgsInProto) {
5335 // (C++ 13.3.2p3): for F to be a viable function, there shall
5336 // exist for each argument an implicit conversion sequence
5337 // (13.3.3.1) that converts that argument to the corresponding
5338 // parameter of F.
5339 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005340 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005341 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005342 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005343 /*InOverloadResolution=*/true,
5344 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005345 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005346 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005347 if (Candidate.Conversions[ArgIdx].isBad()) {
5348 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005349 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005350 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005351 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005352 } else {
5353 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5354 // argument for which there is no corresponding parameter is
5355 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005356 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005357 }
5358 }
5359}
5360
Douglas Gregor063daf62009-03-13 18:40:31 +00005361/// \brief Add all of the function declarations in the given function set to
5362/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005363void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005364 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005365 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005366 bool SuppressUserConversions,
5367 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005368 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005369 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5370 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005371 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005372 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005373 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005374 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005375 Args.slice(1), CandidateSet,
5376 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005377 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005378 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005379 SuppressUserConversions);
5380 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005381 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005382 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5383 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005384 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005385 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005386 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005387 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005388 Args[0]->Classify(Context), Args.slice(1),
5389 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005390 else
John McCall9aa472c2010-03-19 07:35:19 +00005391 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005392 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005393 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005394 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005395 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005396}
5397
John McCall314be4e2009-11-17 07:50:12 +00005398/// AddMethodCandidate - Adds a named decl (which is some kind of
5399/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005400void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005401 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005402 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005403 Expr **Args, unsigned NumArgs,
5404 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005405 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005406 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005407 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005408
5409 if (isa<UsingShadowDecl>(Decl))
5410 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005411
John McCall314be4e2009-11-17 07:50:12 +00005412 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5413 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5414 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005415 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5416 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005417 ObjectType, ObjectClassification,
5418 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005419 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005420 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005421 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005422 ObjectType, ObjectClassification,
5423 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005424 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005425 }
5426}
5427
Douglas Gregor96176b32008-11-18 23:14:02 +00005428/// AddMethodCandidate - Adds the given C++ member function to the set
5429/// of candidate functions, using the given function call arguments
5430/// and the object argument (@c Object). For example, in a call
5431/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5432/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5433/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005434/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005435void
John McCall9aa472c2010-03-19 07:35:19 +00005436Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005437 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005438 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005439 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005440 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005441 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005442 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005443 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005444 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005445 assert(!isa<CXXConstructorDecl>(Method) &&
5446 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005447
Douglas Gregor3f396022009-09-28 04:47:19 +00005448 if (!CandidateSet.isNewCandidate(Method))
5449 return;
5450
Douglas Gregor7edfb692009-11-23 12:27:39 +00005451 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005452 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005453
Douglas Gregor96176b32008-11-18 23:14:02 +00005454 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005455 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005456 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005457 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005458 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005459 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005460 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005461
5462 unsigned NumArgsInProto = Proto->getNumArgs();
5463
5464 // (C++ 13.3.2p2): A candidate function having fewer than m
5465 // parameters is viable only if it has an ellipsis in its parameter
5466 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005467 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005468 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005469 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005470 return;
5471 }
5472
5473 // (C++ 13.3.2p2): A candidate function having more than m parameters
5474 // is viable only if the (m+1)st parameter has a default argument
5475 // (8.3.6). For the purposes of overload resolution, the
5476 // parameter list is truncated on the right, so that there are
5477 // exactly m parameters.
5478 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005479 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005480 // Not enough arguments.
5481 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005482 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005483 return;
5484 }
5485
5486 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005487
John McCall701c89e2009-12-03 04:06:58 +00005488 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005489 // The implicit object argument is ignored.
5490 Candidate.IgnoreObjectArgument = true;
5491 else {
5492 // Determine the implicit conversion sequence for the object
5493 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005494 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005495 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5496 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005497 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005498 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005499 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005500 return;
5501 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005502 }
5503
5504 // Determine the implicit conversion sequences for each of the
5505 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005506 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005507 if (ArgIdx < NumArgsInProto) {
5508 // (C++ 13.3.2p3): for F to be a viable function, there shall
5509 // exist for each argument an implicit conversion sequence
5510 // (13.3.3.1) that converts that argument to the corresponding
5511 // parameter of F.
5512 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005513 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005514 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005515 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005516 /*InOverloadResolution=*/true,
5517 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005518 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005519 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005520 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005521 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005522 break;
5523 }
5524 } else {
5525 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5526 // argument for which there is no corresponding parameter is
5527 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005528 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005529 }
5530 }
5531}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005532
Douglas Gregor6b906862009-08-21 00:16:32 +00005533/// \brief Add a C++ member function template as a candidate to the candidate
5534/// set, using template argument deduction to produce an appropriate member
5535/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005536void
Douglas Gregor6b906862009-08-21 00:16:32 +00005537Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005538 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005539 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005540 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005541 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005542 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005543 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005544 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005545 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005546 if (!CandidateSet.isNewCandidate(MethodTmpl))
5547 return;
5548
Douglas Gregor6b906862009-08-21 00:16:32 +00005549 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005550 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005551 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005552 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005553 // candidate functions in the usual way.113) A given name can refer to one
5554 // or more function templates and also to a set of overloaded non-template
5555 // functions. In such a case, the candidate functions generated from each
5556 // function template are combined with the set of non-template candidate
5557 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005558 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005559 FunctionDecl *Specialization = 0;
5560 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005561 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5562 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005563 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005564 Candidate.FoundDecl = FoundDecl;
5565 Candidate.Function = MethodTmpl->getTemplatedDecl();
5566 Candidate.Viable = false;
5567 Candidate.FailureKind = ovl_fail_bad_deduction;
5568 Candidate.IsSurrogate = false;
5569 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005570 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005571 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005572 Info);
5573 return;
5574 }
Mike Stump1eb44332009-09-09 15:08:12 +00005575
Douglas Gregor6b906862009-08-21 00:16:32 +00005576 // Add the function template specialization produced by template argument
5577 // deduction as a candidate.
5578 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005579 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005580 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005581 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005582 ActingContext, ObjectType, ObjectClassification, Args,
5583 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005584}
5585
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005586/// \brief Add a C++ function template specialization as a candidate
5587/// in the candidate set, using template argument deduction to produce
5588/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005589void
Douglas Gregore53060f2009-06-25 22:08:12 +00005590Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005591 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005592 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005593 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005594 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005595 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005596 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5597 return;
5598
Douglas Gregore53060f2009-06-25 22:08:12 +00005599 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005600 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005601 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005602 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005603 // candidate functions in the usual way.113) A given name can refer to one
5604 // or more function templates and also to a set of overloaded non-template
5605 // functions. In such a case, the candidate functions generated from each
5606 // function template are combined with the set of non-template candidate
5607 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005608 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005609 FunctionDecl *Specialization = 0;
5610 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005611 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5612 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005613 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005614 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005615 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5616 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005617 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005618 Candidate.IsSurrogate = false;
5619 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005620 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005621 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005622 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005623 return;
5624 }
Mike Stump1eb44332009-09-09 15:08:12 +00005625
Douglas Gregore53060f2009-06-25 22:08:12 +00005626 // Add the function template specialization produced by template argument
5627 // deduction as a candidate.
5628 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005629 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005630 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005631}
Mike Stump1eb44332009-09-09 15:08:12 +00005632
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005633/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005634/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005635/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005636/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005637/// (which may or may not be the same type as the type that the
5638/// conversion function produces).
5639void
5640Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005641 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005642 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005643 Expr *From, QualType ToType,
5644 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005645 assert(!Conversion->getDescribedFunctionTemplate() &&
5646 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005647 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005648 if (!CandidateSet.isNewCandidate(Conversion))
5649 return;
5650
Douglas Gregor7edfb692009-11-23 12:27:39 +00005651 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005652 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005653
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005654 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005655 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005656 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005657 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005658 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005659 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005660 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005661 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005662 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005663 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005664 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005665
Douglas Gregorbca39322010-08-19 15:37:02 +00005666 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005667 // For conversion functions, the function is considered to be a member of
5668 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005669 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005670 //
5671 // Determine the implicit conversion sequence for the implicit
5672 // object parameter.
5673 QualType ImplicitParamType = From->getType();
5674 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5675 ImplicitParamType = FromPtrType->getPointeeType();
5676 CXXRecordDecl *ConversionContext
5677 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005678
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005679 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005680 = TryObjectArgumentInitialization(*this, From->getType(),
5681 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005682 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005683
John McCall1d318332010-01-12 00:44:57 +00005684 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005685 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005686 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005687 return;
5688 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005689
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005690 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005691 // derived to base as such conversions are given Conversion Rank. They only
5692 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5693 QualType FromCanon
5694 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5695 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5696 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5697 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005698 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005699 return;
5700 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005701
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005702 // To determine what the conversion from the result of calling the
5703 // conversion function to the type we're eventually trying to
5704 // convert to (ToType), we need to synthesize a call to the
5705 // conversion function and attempt copy initialization from it. This
5706 // makes sure that we get the right semantics with respect to
5707 // lvalues/rvalues and the type. Fortunately, we can allocate this
5708 // call on the stack and we don't need its arguments to be
5709 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005710 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005711 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005712 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5713 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005714 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005715 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005716
Richard Smith87c1f1f2011-07-13 22:53:21 +00005717 QualType ConversionType = Conversion->getConversionType();
5718 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005719 Candidate.Viable = false;
5720 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5721 return;
5722 }
5723
Richard Smith87c1f1f2011-07-13 22:53:21 +00005724 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005725
Mike Stump1eb44332009-09-09 15:08:12 +00005726 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005727 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5728 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005729 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005730 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005731 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005732 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005733 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005734 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005735 /*InOverloadResolution=*/false,
5736 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005737
John McCall1d318332010-01-12 00:44:57 +00005738 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005739 case ImplicitConversionSequence::StandardConversion:
5740 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005741
Douglas Gregorc520c842010-04-12 23:42:09 +00005742 // C++ [over.ics.user]p3:
5743 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005744 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005745 // shall have exact match rank.
5746 if (Conversion->getPrimaryTemplate() &&
5747 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5748 Candidate.Viable = false;
5749 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005751
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005752 // C++0x [dcl.init.ref]p5:
5753 // In the second case, if the reference is an rvalue reference and
5754 // the second standard conversion sequence of the user-defined
5755 // conversion sequence includes an lvalue-to-rvalue conversion, the
5756 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005757 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005758 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5759 Candidate.Viable = false;
5760 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5761 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005762 break;
5763
5764 case ImplicitConversionSequence::BadConversion:
5765 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005766 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005767 break;
5768
5769 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005770 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005771 "Can only end up with a standard conversion sequence or failure");
5772 }
5773}
5774
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005775/// \brief Adds a conversion function template specialization
5776/// candidate to the overload set, using template argument deduction
5777/// to deduce the template arguments of the conversion function
5778/// template from the type that we are converting to (C++
5779/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005780void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005781Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005782 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005783 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005784 Expr *From, QualType ToType,
5785 OverloadCandidateSet &CandidateSet) {
5786 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5787 "Only conversion function templates permitted here");
5788
Douglas Gregor3f396022009-09-28 04:47:19 +00005789 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5790 return;
5791
Craig Topper93e45992012-09-19 02:26:47 +00005792 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005793 CXXConversionDecl *Specialization = 0;
5794 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005795 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005796 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005797 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005798 Candidate.FoundDecl = FoundDecl;
5799 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5800 Candidate.Viable = false;
5801 Candidate.FailureKind = ovl_fail_bad_deduction;
5802 Candidate.IsSurrogate = false;
5803 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005804 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005805 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005806 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005807 return;
5808 }
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005810 // Add the conversion function template specialization produced by
5811 // template argument deduction as a candidate.
5812 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005813 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005814 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005815}
5816
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005817/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5818/// converts the given @c Object to a function pointer via the
5819/// conversion function @c Conversion, and then attempts to call it
5820/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5821/// the type of function that we'll eventually be calling.
5822void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005823 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005824 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005825 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005826 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005827 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005828 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005829 if (!CandidateSet.isNewCandidate(Conversion))
5830 return;
5831
Douglas Gregor7edfb692009-11-23 12:27:39 +00005832 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005833 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005834
Ahmed Charles13a140c2012-02-25 11:00:22 +00005835 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005836 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005837 Candidate.Function = 0;
5838 Candidate.Surrogate = Conversion;
5839 Candidate.Viable = true;
5840 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005841 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005842 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005843
5844 // Determine the implicit conversion sequence for the implicit
5845 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005846 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005847 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005848 Object->Classify(Context),
5849 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005850 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005851 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005852 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005853 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005854 return;
5855 }
5856
5857 // The first conversion is actually a user-defined conversion whose
5858 // first conversion is ObjectInit's standard conversion (which is
5859 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005860 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005861 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005862 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005863 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005864 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005865 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005866 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005867 = Candidate.Conversions[0].UserDefined.Before;
5868 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5869
Mike Stump1eb44332009-09-09 15:08:12 +00005870 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005871 unsigned NumArgsInProto = Proto->getNumArgs();
5872
5873 // (C++ 13.3.2p2): A candidate function having fewer than m
5874 // parameters is viable only if it has an ellipsis in its parameter
5875 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005876 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005877 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005878 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005879 return;
5880 }
5881
5882 // Function types don't have any default arguments, so just check if
5883 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005884 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005885 // Not enough arguments.
5886 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005887 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005888 return;
5889 }
5890
5891 // Determine the implicit conversion sequences for each of the
5892 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005893 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005894 if (ArgIdx < NumArgsInProto) {
5895 // (C++ 13.3.2p3): for F to be a viable function, there shall
5896 // exist for each argument an implicit conversion sequence
5897 // (13.3.3.1) that converts that argument to the corresponding
5898 // parameter of F.
5899 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005900 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005901 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005902 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005903 /*InOverloadResolution=*/false,
5904 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005905 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005906 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005907 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005908 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005909 break;
5910 }
5911 } else {
5912 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5913 // argument for which there is no corresponding parameter is
5914 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005915 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005916 }
5917 }
5918}
5919
Douglas Gregor063daf62009-03-13 18:40:31 +00005920/// \brief Add overload candidates for overloaded operators that are
5921/// member functions.
5922///
5923/// Add the overloaded operator candidates that are member functions
5924/// for the operator Op that was used in an operator expression such
5925/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5926/// CandidateSet will store the added overload candidates. (C++
5927/// [over.match.oper]).
5928void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5929 SourceLocation OpLoc,
5930 Expr **Args, unsigned NumArgs,
5931 OverloadCandidateSet& CandidateSet,
5932 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005933 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5934
5935 // C++ [over.match.oper]p3:
5936 // For a unary operator @ with an operand of a type whose
5937 // cv-unqualified version is T1, and for a binary operator @ with
5938 // a left operand of a type whose cv-unqualified version is T1 and
5939 // a right operand of a type whose cv-unqualified version is T2,
5940 // three sets of candidate functions, designated member
5941 // candidates, non-member candidates and built-in candidates, are
5942 // constructed as follows:
5943 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005944
5945 // -- If T1 is a class type, the set of member candidates is the
5946 // result of the qualified lookup of T1::operator@
5947 // (13.3.1.1.1); otherwise, the set of member candidates is
5948 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005949 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005950 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005951 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005952 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005953
John McCalla24dc2e2009-11-17 02:14:36 +00005954 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5955 LookupQualifiedName(Operators, T1Rec->getDecl());
5956 Operators.suppressDiagnostics();
5957
Mike Stump1eb44332009-09-09 15:08:12 +00005958 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005959 OperEnd = Operators.end();
5960 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005961 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005962 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005963 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005964 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005965 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005966 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005967}
5968
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005969/// AddBuiltinCandidate - Add a candidate for a built-in
5970/// operator. ResultTy and ParamTys are the result and parameter types
5971/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005972/// arguments being passed to the candidate. IsAssignmentOperator
5973/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005974/// operator. NumContextualBoolArguments is the number of arguments
5975/// (at the beginning of the argument list) that will be contextually
5976/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005977void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005978 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005979 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005980 bool IsAssignmentOperator,
5981 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005982 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005983 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005984
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005985 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005986 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005987 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005988 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005989 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005990 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005991 Candidate.BuiltinTypes.ResultTy = ResultTy;
5992 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5993 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5994
5995 // Determine the implicit conversion sequences for each of the
5996 // arguments.
5997 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005998 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005999 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006000 // C++ [over.match.oper]p4:
6001 // For the built-in assignment operators, conversions of the
6002 // left operand are restricted as follows:
6003 // -- no temporaries are introduced to hold the left operand, and
6004 // -- no user-defined conversions are applied to the left
6005 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006006 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006007 //
6008 // We block these conversions by turning off user-defined
6009 // conversions, since that is the only way that initialization of
6010 // a reference to a non-class type can occur from something that
6011 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006012 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006013 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006014 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006015 Candidate.Conversions[ArgIdx]
6016 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006017 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006018 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006019 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006020 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006021 /*InOverloadResolution=*/false,
6022 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006023 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006024 }
John McCall1d318332010-01-12 00:44:57 +00006025 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006026 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006027 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006028 break;
6029 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006030 }
6031}
6032
6033/// BuiltinCandidateTypeSet - A set of types that will be used for the
6034/// candidate operator functions for built-in operators (C++
6035/// [over.built]). The types are separated into pointer types and
6036/// enumeration types.
6037class BuiltinCandidateTypeSet {
6038 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006039 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006040
6041 /// PointerTypes - The set of pointer types that will be used in the
6042 /// built-in candidates.
6043 TypeSet PointerTypes;
6044
Sebastian Redl78eb8742009-04-19 21:53:20 +00006045 /// MemberPointerTypes - The set of member pointer types that will be
6046 /// used in the built-in candidates.
6047 TypeSet MemberPointerTypes;
6048
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006049 /// EnumerationTypes - The set of enumeration types that will be
6050 /// used in the built-in candidates.
6051 TypeSet EnumerationTypes;
6052
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006053 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006054 /// candidates.
6055 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006056
6057 /// \brief A flag indicating non-record types are viable candidates
6058 bool HasNonRecordTypes;
6059
6060 /// \brief A flag indicating whether either arithmetic or enumeration types
6061 /// were present in the candidate set.
6062 bool HasArithmeticOrEnumeralTypes;
6063
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006064 /// \brief A flag indicating whether the nullptr type was present in the
6065 /// candidate set.
6066 bool HasNullPtrType;
6067
Douglas Gregor5842ba92009-08-24 15:23:48 +00006068 /// Sema - The semantic analysis instance where we are building the
6069 /// candidate type set.
6070 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006071
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006072 /// Context - The AST context in which we will build the type sets.
6073 ASTContext &Context;
6074
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006075 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6076 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006077 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006078
6079public:
6080 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006081 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006082
Mike Stump1eb44332009-09-09 15:08:12 +00006083 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006084 : HasNonRecordTypes(false),
6085 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006086 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006087 SemaRef(SemaRef),
6088 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006089
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006090 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006091 SourceLocation Loc,
6092 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006093 bool AllowExplicitConversions,
6094 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006095
6096 /// pointer_begin - First pointer type found;
6097 iterator pointer_begin() { return PointerTypes.begin(); }
6098
Sebastian Redl78eb8742009-04-19 21:53:20 +00006099 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006100 iterator pointer_end() { return PointerTypes.end(); }
6101
Sebastian Redl78eb8742009-04-19 21:53:20 +00006102 /// member_pointer_begin - First member pointer type found;
6103 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6104
6105 /// member_pointer_end - Past the last member pointer type found;
6106 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6107
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006108 /// enumeration_begin - First enumeration type found;
6109 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6110
Sebastian Redl78eb8742009-04-19 21:53:20 +00006111 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006112 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006113
Douglas Gregor26bcf672010-05-19 03:21:00 +00006114 iterator vector_begin() { return VectorTypes.begin(); }
6115 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006116
6117 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6118 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006119 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006120};
6121
Sebastian Redl78eb8742009-04-19 21:53:20 +00006122/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006123/// the set of pointer types along with any more-qualified variants of
6124/// that type. For example, if @p Ty is "int const *", this routine
6125/// will add "int const *", "int const volatile *", "int const
6126/// restrict *", and "int const volatile restrict *" to the set of
6127/// pointer types. Returns true if the add of @p Ty itself succeeded,
6128/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006129///
6130/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006131bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006132BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6133 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006134
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006135 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006136 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006137 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006138
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006139 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006140 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006141 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006142 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006143 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6144 PointeeTy = PTy->getPointeeType();
6145 buildObjCPtr = true;
6146 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006147 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006148 }
6149
Sebastian Redla9efada2009-11-18 20:39:26 +00006150 // Don't add qualified variants of arrays. For one, they're not allowed
6151 // (the qualifier would sink to the element type), and for another, the
6152 // only overload situation where it matters is subscript or pointer +- int,
6153 // and those shouldn't have qualifier variants anyway.
6154 if (PointeeTy->isArrayType())
6155 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006156
John McCall0953e762009-09-24 19:53:00 +00006157 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006158 bool hasVolatile = VisibleQuals.hasVolatile();
6159 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006160
John McCall0953e762009-09-24 19:53:00 +00006161 // Iterate through all strict supersets of BaseCVR.
6162 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6163 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006164 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006165 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006166
6167 // Skip over restrict if no restrict found anywhere in the types, or if
6168 // the type cannot be restrict-qualified.
6169 if ((CVR & Qualifiers::Restrict) &&
6170 (!hasRestrict ||
6171 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6172 continue;
6173
6174 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006175 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006176
6177 // Build qualified pointer type.
6178 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006179 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006180 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006181 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006182 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6183
6184 // Insert qualified pointer type.
6185 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006186 }
6187
6188 return true;
6189}
6190
Sebastian Redl78eb8742009-04-19 21:53:20 +00006191/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6192/// to the set of pointer types along with any more-qualified variants of
6193/// that type. For example, if @p Ty is "int const *", this routine
6194/// will add "int const *", "int const volatile *", "int const
6195/// restrict *", and "int const volatile restrict *" to the set of
6196/// pointer types. Returns true if the add of @p Ty itself succeeded,
6197/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006198///
6199/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006200bool
6201BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6202 QualType Ty) {
6203 // Insert this type.
6204 if (!MemberPointerTypes.insert(Ty))
6205 return false;
6206
John McCall0953e762009-09-24 19:53:00 +00006207 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6208 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006209
John McCall0953e762009-09-24 19:53:00 +00006210 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006211 // Don't add qualified variants of arrays. For one, they're not allowed
6212 // (the qualifier would sink to the element type), and for another, the
6213 // only overload situation where it matters is subscript or pointer +- int,
6214 // and those shouldn't have qualifier variants anyway.
6215 if (PointeeTy->isArrayType())
6216 return true;
John McCall0953e762009-09-24 19:53:00 +00006217 const Type *ClassTy = PointerTy->getClass();
6218
6219 // Iterate through all strict supersets of the pointee type's CVR
6220 // qualifiers.
6221 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6222 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6223 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006224
John McCall0953e762009-09-24 19:53:00 +00006225 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006226 MemberPointerTypes.insert(
6227 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006228 }
6229
6230 return true;
6231}
6232
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006233/// AddTypesConvertedFrom - Add each of the types to which the type @p
6234/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006235/// primarily interested in pointer types and enumeration types. We also
6236/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006237/// AllowUserConversions is true if we should look at the conversion
6238/// functions of a class type, and AllowExplicitConversions if we
6239/// should also include the explicit conversion functions of a class
6240/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006241void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006242BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006243 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006244 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006245 bool AllowExplicitConversions,
6246 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006247 // Only deal with canonical types.
6248 Ty = Context.getCanonicalType(Ty);
6249
6250 // Look through reference types; they aren't part of the type of an
6251 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006252 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006253 Ty = RefTy->getPointeeType();
6254
John McCall3b657512011-01-19 10:06:00 +00006255 // If we're dealing with an array type, decay to the pointer.
6256 if (Ty->isArrayType())
6257 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6258
6259 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006260 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006261
Chandler Carruth6a577462010-12-13 01:44:01 +00006262 // Flag if we ever add a non-record type.
6263 const RecordType *TyRec = Ty->getAs<RecordType>();
6264 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6265
Chandler Carruth6a577462010-12-13 01:44:01 +00006266 // Flag if we encounter an arithmetic type.
6267 HasArithmeticOrEnumeralTypes =
6268 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6269
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006270 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6271 PointerTypes.insert(Ty);
6272 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006273 // Insert our type, and its more-qualified variants, into the set
6274 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006275 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006276 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006277 } else if (Ty->isMemberPointerType()) {
6278 // Member pointers are far easier, since the pointee can't be converted.
6279 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6280 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006281 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006282 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006283 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006284 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006285 // We treat vector types as arithmetic types in many contexts as an
6286 // extension.
6287 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006288 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006289 } else if (Ty->isNullPtrType()) {
6290 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006291 } else if (AllowUserConversions && TyRec) {
6292 // No conversion functions in incomplete types.
6293 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6294 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006295
Chandler Carruth6a577462010-12-13 01:44:01 +00006296 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6297 const UnresolvedSetImpl *Conversions
6298 = ClassDecl->getVisibleConversionFunctions();
6299 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6300 E = Conversions->end(); I != E; ++I) {
6301 NamedDecl *D = I.getDecl();
6302 if (isa<UsingShadowDecl>(D))
6303 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006304
Chandler Carruth6a577462010-12-13 01:44:01 +00006305 // Skip conversion function templates; they don't tell us anything
6306 // about which builtin types we can convert to.
6307 if (isa<FunctionTemplateDecl>(D))
6308 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006309
Chandler Carruth6a577462010-12-13 01:44:01 +00006310 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6311 if (AllowExplicitConversions || !Conv->isExplicit()) {
6312 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6313 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006314 }
6315 }
6316 }
6317}
6318
Douglas Gregor19b7b152009-08-24 13:43:27 +00006319/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6320/// the volatile- and non-volatile-qualified assignment operators for the
6321/// given type to the candidate set.
6322static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6323 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006324 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006325 unsigned NumArgs,
6326 OverloadCandidateSet &CandidateSet) {
6327 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006328
Douglas Gregor19b7b152009-08-24 13:43:27 +00006329 // T& operator=(T&, T)
6330 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6331 ParamTypes[1] = T;
6332 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6333 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006334
Douglas Gregor19b7b152009-08-24 13:43:27 +00006335 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6336 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006337 ParamTypes[0]
6338 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006339 ParamTypes[1] = T;
6340 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006341 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006342 }
6343}
Mike Stump1eb44332009-09-09 15:08:12 +00006344
Sebastian Redl9994a342009-10-25 17:03:50 +00006345/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6346/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006347static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6348 Qualifiers VRQuals;
6349 const RecordType *TyRec;
6350 if (const MemberPointerType *RHSMPType =
6351 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006352 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006353 else
6354 TyRec = ArgExpr->getType()->getAs<RecordType>();
6355 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006356 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006357 VRQuals.addVolatile();
6358 VRQuals.addRestrict();
6359 return VRQuals;
6360 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006361
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006362 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006363 if (!ClassDecl->hasDefinition())
6364 return VRQuals;
6365
John McCalleec51cf2010-01-20 00:46:10 +00006366 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006367 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006368
John McCalleec51cf2010-01-20 00:46:10 +00006369 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006370 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006371 NamedDecl *D = I.getDecl();
6372 if (isa<UsingShadowDecl>(D))
6373 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6374 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006375 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6376 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6377 CanTy = ResTypeRef->getPointeeType();
6378 // Need to go down the pointer/mempointer chain and add qualifiers
6379 // as see them.
6380 bool done = false;
6381 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006382 if (CanTy.isRestrictQualified())
6383 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006384 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6385 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006386 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006387 CanTy->getAs<MemberPointerType>())
6388 CanTy = ResTypeMPtr->getPointeeType();
6389 else
6390 done = true;
6391 if (CanTy.isVolatileQualified())
6392 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006393 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6394 return VRQuals;
6395 }
6396 }
6397 }
6398 return VRQuals;
6399}
John McCall00071ec2010-11-13 05:51:15 +00006400
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006401namespace {
John McCall00071ec2010-11-13 05:51:15 +00006402
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006403/// \brief Helper class to manage the addition of builtin operator overload
6404/// candidates. It provides shared state and utility methods used throughout
6405/// the process, as well as a helper method to add each group of builtin
6406/// operator overloads from the standard to a candidate set.
6407class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006408 // Common instance state available to all overload candidate addition methods.
6409 Sema &S;
6410 Expr **Args;
6411 unsigned NumArgs;
6412 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006413 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006414 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006415 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006416
Chandler Carruth6d695582010-12-12 10:35:00 +00006417 // Define some constants used to index and iterate over the arithemetic types
6418 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006419 // The "promoted arithmetic types" are the arithmetic
6420 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006421 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006422 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006423 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006424 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006425 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006426 LastPromotedArithmeticType = 11;
6427 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006428
Chandler Carruth6d695582010-12-12 10:35:00 +00006429 /// \brief Get the canonical type for a given arithmetic type index.
6430 CanQualType getArithmeticType(unsigned index) {
6431 assert(index < NumArithmeticTypes);
6432 static CanQualType ASTContext::* const
6433 ArithmeticTypes[NumArithmeticTypes] = {
6434 // Start of promoted types.
6435 &ASTContext::FloatTy,
6436 &ASTContext::DoubleTy,
6437 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006438
Chandler Carruth6d695582010-12-12 10:35:00 +00006439 // Start of integral types.
6440 &ASTContext::IntTy,
6441 &ASTContext::LongTy,
6442 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006443 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006444 &ASTContext::UnsignedIntTy,
6445 &ASTContext::UnsignedLongTy,
6446 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006447 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006448 // End of promoted types.
6449
6450 &ASTContext::BoolTy,
6451 &ASTContext::CharTy,
6452 &ASTContext::WCharTy,
6453 &ASTContext::Char16Ty,
6454 &ASTContext::Char32Ty,
6455 &ASTContext::SignedCharTy,
6456 &ASTContext::ShortTy,
6457 &ASTContext::UnsignedCharTy,
6458 &ASTContext::UnsignedShortTy,
6459 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006460 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006461 };
6462 return S.Context.*ArithmeticTypes[index];
6463 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006464
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006465 /// \brief Gets the canonical type resulting from the usual arithemetic
6466 /// converions for the given arithmetic types.
6467 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6468 // Accelerator table for performing the usual arithmetic conversions.
6469 // The rules are basically:
6470 // - if either is floating-point, use the wider floating-point
6471 // - if same signedness, use the higher rank
6472 // - if same size, use unsigned of the higher rank
6473 // - use the larger type
6474 // These rules, together with the axiom that higher ranks are
6475 // never smaller, are sufficient to precompute all of these results
6476 // *except* when dealing with signed types of higher rank.
6477 // (we could precompute SLL x UI for all known platforms, but it's
6478 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006479 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006480 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006481 Dep=-1,
6482 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006483 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006484 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006485 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006486/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6487/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6488/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6489/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6490/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6491/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6492/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6493/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6494/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6495/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6496/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006497 };
6498
6499 assert(L < LastPromotedArithmeticType);
6500 assert(R < LastPromotedArithmeticType);
6501 int Idx = ConversionsTable[L][R];
6502
6503 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006504 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006505
6506 // Slow path: we need to compare widths.
6507 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006508 CanQualType LT = getArithmeticType(L),
6509 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006510 unsigned LW = S.Context.getIntWidth(LT),
6511 RW = S.Context.getIntWidth(RT);
6512
6513 // If they're different widths, use the signed type.
6514 if (LW > RW) return LT;
6515 else if (LW < RW) return RT;
6516
6517 // Otherwise, use the unsigned type of the signed type's rank.
6518 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6519 assert(L == SLL || R == SLL);
6520 return S.Context.UnsignedLongLongTy;
6521 }
6522
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006523 /// \brief Helper method to factor out the common pattern of adding overloads
6524 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006525 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006526 bool HasVolatile,
6527 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006528 QualType ParamTypes[2] = {
6529 S.Context.getLValueReferenceType(CandidateTy),
6530 S.Context.IntTy
6531 };
6532
6533 // Non-volatile version.
6534 if (NumArgs == 1)
6535 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6536 else
6537 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6538
6539 // Use a heuristic to reduce number of builtin candidates in the set:
6540 // add volatile version only if there are conversions to a volatile type.
6541 if (HasVolatile) {
6542 ParamTypes[0] =
6543 S.Context.getLValueReferenceType(
6544 S.Context.getVolatileType(CandidateTy));
6545 if (NumArgs == 1)
6546 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6547 else
6548 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6549 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006550
6551 // Add restrict version only if there are conversions to a restrict type
6552 // and our candidate type is a non-restrict-qualified pointer.
6553 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6554 !CandidateTy.isRestrictQualified()) {
6555 ParamTypes[0]
6556 = S.Context.getLValueReferenceType(
6557 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6558 if (NumArgs == 1)
6559 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6560 else
6561 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6562
6563 if (HasVolatile) {
6564 ParamTypes[0]
6565 = S.Context.getLValueReferenceType(
6566 S.Context.getCVRQualifiedType(CandidateTy,
6567 (Qualifiers::Volatile |
6568 Qualifiers::Restrict)));
6569 if (NumArgs == 1)
6570 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6571 CandidateSet);
6572 else
6573 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6574 }
6575 }
6576
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006577 }
6578
6579public:
6580 BuiltinOperatorOverloadBuilder(
6581 Sema &S, Expr **Args, unsigned NumArgs,
6582 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006583 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006584 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006585 OverloadCandidateSet &CandidateSet)
6586 : S(S), Args(Args), NumArgs(NumArgs),
6587 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006588 HasArithmeticOrEnumeralCandidateType(
6589 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006590 CandidateTypes(CandidateTypes),
6591 CandidateSet(CandidateSet) {
6592 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006593 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006594 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006595 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006596 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006597 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006598 assert(getArithmeticType(FirstPromotedArithmeticType)
6599 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006600 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006601 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006602 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006603 "Invalid last promoted arithmetic type");
6604 }
6605
6606 // C++ [over.built]p3:
6607 //
6608 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6609 // is either volatile or empty, there exist candidate operator
6610 // functions of the form
6611 //
6612 // VQ T& operator++(VQ T&);
6613 // T operator++(VQ T&, int);
6614 //
6615 // C++ [over.built]p4:
6616 //
6617 // For every pair (T, VQ), where T is an arithmetic type other
6618 // than bool, and VQ is either volatile or empty, there exist
6619 // candidate operator functions of the form
6620 //
6621 // VQ T& operator--(VQ T&);
6622 // T operator--(VQ T&, int);
6623 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006624 if (!HasArithmeticOrEnumeralCandidateType)
6625 return;
6626
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006627 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6628 Arith < NumArithmeticTypes; ++Arith) {
6629 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006630 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006631 VisibleTypeConversionsQuals.hasVolatile(),
6632 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006633 }
6634 }
6635
6636 // C++ [over.built]p5:
6637 //
6638 // For every pair (T, VQ), where T is a cv-qualified or
6639 // cv-unqualified object type, and VQ is either volatile or
6640 // empty, there exist candidate operator functions of the form
6641 //
6642 // T*VQ& operator++(T*VQ&);
6643 // T*VQ& operator--(T*VQ&);
6644 // T* operator++(T*VQ&, int);
6645 // T* operator--(T*VQ&, int);
6646 void addPlusPlusMinusMinusPointerOverloads() {
6647 for (BuiltinCandidateTypeSet::iterator
6648 Ptr = CandidateTypes[0].pointer_begin(),
6649 PtrEnd = CandidateTypes[0].pointer_end();
6650 Ptr != PtrEnd; ++Ptr) {
6651 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006652 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006653 continue;
6654
6655 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006656 (!(*Ptr).isVolatileQualified() &&
6657 VisibleTypeConversionsQuals.hasVolatile()),
6658 (!(*Ptr).isRestrictQualified() &&
6659 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006660 }
6661 }
6662
6663 // C++ [over.built]p6:
6664 // For every cv-qualified or cv-unqualified object type T, there
6665 // exist candidate operator functions of the form
6666 //
6667 // T& operator*(T*);
6668 //
6669 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006670 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006671 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006672 // T& operator*(T*);
6673 void addUnaryStarPointerOverloads() {
6674 for (BuiltinCandidateTypeSet::iterator
6675 Ptr = CandidateTypes[0].pointer_begin(),
6676 PtrEnd = CandidateTypes[0].pointer_end();
6677 Ptr != PtrEnd; ++Ptr) {
6678 QualType ParamTy = *Ptr;
6679 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006680 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6681 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006682
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006683 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6684 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6685 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006686
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006687 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6688 &ParamTy, Args, 1, CandidateSet);
6689 }
6690 }
6691
6692 // C++ [over.built]p9:
6693 // For every promoted arithmetic type T, there exist candidate
6694 // operator functions of the form
6695 //
6696 // T operator+(T);
6697 // T operator-(T);
6698 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006699 if (!HasArithmeticOrEnumeralCandidateType)
6700 return;
6701
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006702 for (unsigned Arith = FirstPromotedArithmeticType;
6703 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006704 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006705 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6706 }
6707
6708 // Extension: We also add these operators for vector types.
6709 for (BuiltinCandidateTypeSet::iterator
6710 Vec = CandidateTypes[0].vector_begin(),
6711 VecEnd = CandidateTypes[0].vector_end();
6712 Vec != VecEnd; ++Vec) {
6713 QualType VecTy = *Vec;
6714 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6715 }
6716 }
6717
6718 // C++ [over.built]p8:
6719 // For every type T, there exist candidate operator functions of
6720 // the form
6721 //
6722 // T* operator+(T*);
6723 void addUnaryPlusPointerOverloads() {
6724 for (BuiltinCandidateTypeSet::iterator
6725 Ptr = CandidateTypes[0].pointer_begin(),
6726 PtrEnd = CandidateTypes[0].pointer_end();
6727 Ptr != PtrEnd; ++Ptr) {
6728 QualType ParamTy = *Ptr;
6729 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6730 }
6731 }
6732
6733 // C++ [over.built]p10:
6734 // For every promoted integral type T, there exist candidate
6735 // operator functions of the form
6736 //
6737 // T operator~(T);
6738 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006739 if (!HasArithmeticOrEnumeralCandidateType)
6740 return;
6741
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006742 for (unsigned Int = FirstPromotedIntegralType;
6743 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006744 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006745 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6746 }
6747
6748 // Extension: We also add this operator for vector types.
6749 for (BuiltinCandidateTypeSet::iterator
6750 Vec = CandidateTypes[0].vector_begin(),
6751 VecEnd = CandidateTypes[0].vector_end();
6752 Vec != VecEnd; ++Vec) {
6753 QualType VecTy = *Vec;
6754 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6755 }
6756 }
6757
6758 // C++ [over.match.oper]p16:
6759 // For every pointer to member type T, there exist candidate operator
6760 // functions of the form
6761 //
6762 // bool operator==(T,T);
6763 // bool operator!=(T,T);
6764 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6765 /// Set of (canonical) types that we've already handled.
6766 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6767
6768 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6769 for (BuiltinCandidateTypeSet::iterator
6770 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6771 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6772 MemPtr != MemPtrEnd;
6773 ++MemPtr) {
6774 // Don't add the same builtin candidate twice.
6775 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6776 continue;
6777
6778 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6779 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6780 CandidateSet);
6781 }
6782 }
6783 }
6784
6785 // C++ [over.built]p15:
6786 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006787 // For every T, where T is an enumeration type, a pointer type, or
6788 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006789 //
6790 // bool operator<(T, T);
6791 // bool operator>(T, T);
6792 // bool operator<=(T, T);
6793 // bool operator>=(T, T);
6794 // bool operator==(T, T);
6795 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006796 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006797 // C++ [over.match.oper]p3:
6798 // [...]the built-in candidates include all of the candidate operator
6799 // functions defined in 13.6 that, compared to the given operator, [...]
6800 // do not have the same parameter-type-list as any non-template non-member
6801 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006802 //
Eli Friedman97c67392012-09-18 21:52:24 +00006803 // Note that in practice, this only affects enumeration types because there
6804 // aren't any built-in candidates of record type, and a user-defined operator
6805 // must have an operand of record or enumeration type. Also, the only other
6806 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006807 // cannot be overloaded for enumeration types, so this is the only place
6808 // where we must suppress candidates like this.
6809 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6810 UserDefinedBinaryOperators;
6811
6812 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6813 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6814 CandidateTypes[ArgIdx].enumeration_end()) {
6815 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6816 CEnd = CandidateSet.end();
6817 C != CEnd; ++C) {
6818 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6819 continue;
6820
Eli Friedman97c67392012-09-18 21:52:24 +00006821 if (C->Function->isFunctionTemplateSpecialization())
6822 continue;
6823
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006824 QualType FirstParamType =
6825 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6826 QualType SecondParamType =
6827 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6828
6829 // Skip if either parameter isn't of enumeral type.
6830 if (!FirstParamType->isEnumeralType() ||
6831 !SecondParamType->isEnumeralType())
6832 continue;
6833
6834 // Add this operator to the set of known user-defined operators.
6835 UserDefinedBinaryOperators.insert(
6836 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6837 S.Context.getCanonicalType(SecondParamType)));
6838 }
6839 }
6840 }
6841
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006842 /// Set of (canonical) types that we've already handled.
6843 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6844
6845 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6846 for (BuiltinCandidateTypeSet::iterator
6847 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6848 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6849 Ptr != PtrEnd; ++Ptr) {
6850 // Don't add the same builtin candidate twice.
6851 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6852 continue;
6853
6854 QualType ParamTypes[2] = { *Ptr, *Ptr };
6855 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6856 CandidateSet);
6857 }
6858 for (BuiltinCandidateTypeSet::iterator
6859 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6860 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6861 Enum != EnumEnd; ++Enum) {
6862 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6863
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006864 // Don't add the same builtin candidate twice, or if a user defined
6865 // candidate exists.
6866 if (!AddedTypes.insert(CanonType) ||
6867 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6868 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006869 continue;
6870
6871 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006872 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6873 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006874 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006875
6876 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6877 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6878 if (AddedTypes.insert(NullPtrTy) &&
6879 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6880 NullPtrTy))) {
6881 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6882 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6883 CandidateSet);
6884 }
6885 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006886 }
6887 }
6888
6889 // C++ [over.built]p13:
6890 //
6891 // For every cv-qualified or cv-unqualified object type T
6892 // there exist candidate operator functions of the form
6893 //
6894 // T* operator+(T*, ptrdiff_t);
6895 // T& operator[](T*, ptrdiff_t); [BELOW]
6896 // T* operator-(T*, ptrdiff_t);
6897 // T* operator+(ptrdiff_t, T*);
6898 // T& operator[](ptrdiff_t, T*); [BELOW]
6899 //
6900 // C++ [over.built]p14:
6901 //
6902 // For every T, where T is a pointer to object type, there
6903 // exist candidate operator functions of the form
6904 //
6905 // ptrdiff_t operator-(T, T);
6906 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6907 /// Set of (canonical) types that we've already handled.
6908 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6909
6910 for (int Arg = 0; Arg < 2; ++Arg) {
6911 QualType AsymetricParamTypes[2] = {
6912 S.Context.getPointerDiffType(),
6913 S.Context.getPointerDiffType(),
6914 };
6915 for (BuiltinCandidateTypeSet::iterator
6916 Ptr = CandidateTypes[Arg].pointer_begin(),
6917 PtrEnd = CandidateTypes[Arg].pointer_end();
6918 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006919 QualType PointeeTy = (*Ptr)->getPointeeType();
6920 if (!PointeeTy->isObjectType())
6921 continue;
6922
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006923 AsymetricParamTypes[Arg] = *Ptr;
6924 if (Arg == 0 || Op == OO_Plus) {
6925 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6926 // T* operator+(ptrdiff_t, T*);
6927 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6928 CandidateSet);
6929 }
6930 if (Op == OO_Minus) {
6931 // ptrdiff_t operator-(T, T);
6932 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6933 continue;
6934
6935 QualType ParamTypes[2] = { *Ptr, *Ptr };
6936 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6937 Args, 2, CandidateSet);
6938 }
6939 }
6940 }
6941 }
6942
6943 // C++ [over.built]p12:
6944 //
6945 // For every pair of promoted arithmetic types L and R, there
6946 // exist candidate operator functions of the form
6947 //
6948 // LR operator*(L, R);
6949 // LR operator/(L, R);
6950 // LR operator+(L, R);
6951 // LR operator-(L, R);
6952 // bool operator<(L, R);
6953 // bool operator>(L, R);
6954 // bool operator<=(L, R);
6955 // bool operator>=(L, R);
6956 // bool operator==(L, R);
6957 // bool operator!=(L, R);
6958 //
6959 // where LR is the result of the usual arithmetic conversions
6960 // between types L and R.
6961 //
6962 // C++ [over.built]p24:
6963 //
6964 // For every pair of promoted arithmetic types L and R, there exist
6965 // candidate operator functions of the form
6966 //
6967 // LR operator?(bool, L, R);
6968 //
6969 // where LR is the result of the usual arithmetic conversions
6970 // between types L and R.
6971 // Our candidates ignore the first parameter.
6972 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006973 if (!HasArithmeticOrEnumeralCandidateType)
6974 return;
6975
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006976 for (unsigned Left = FirstPromotedArithmeticType;
6977 Left < LastPromotedArithmeticType; ++Left) {
6978 for (unsigned Right = FirstPromotedArithmeticType;
6979 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006980 QualType LandR[2] = { getArithmeticType(Left),
6981 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006982 QualType Result =
6983 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006984 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006985 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6986 }
6987 }
6988
6989 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6990 // conditional operator for vector types.
6991 for (BuiltinCandidateTypeSet::iterator
6992 Vec1 = CandidateTypes[0].vector_begin(),
6993 Vec1End = CandidateTypes[0].vector_end();
6994 Vec1 != Vec1End; ++Vec1) {
6995 for (BuiltinCandidateTypeSet::iterator
6996 Vec2 = CandidateTypes[1].vector_begin(),
6997 Vec2End = CandidateTypes[1].vector_end();
6998 Vec2 != Vec2End; ++Vec2) {
6999 QualType LandR[2] = { *Vec1, *Vec2 };
7000 QualType Result = S.Context.BoolTy;
7001 if (!isComparison) {
7002 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7003 Result = *Vec1;
7004 else
7005 Result = *Vec2;
7006 }
7007
7008 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7009 }
7010 }
7011 }
7012
7013 // C++ [over.built]p17:
7014 //
7015 // For every pair of promoted integral types L and R, there
7016 // exist candidate operator functions of the form
7017 //
7018 // LR operator%(L, R);
7019 // LR operator&(L, R);
7020 // LR operator^(L, R);
7021 // LR operator|(L, R);
7022 // L operator<<(L, R);
7023 // L operator>>(L, R);
7024 //
7025 // where LR is the result of the usual arithmetic conversions
7026 // between types L and R.
7027 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007028 if (!HasArithmeticOrEnumeralCandidateType)
7029 return;
7030
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007031 for (unsigned Left = FirstPromotedIntegralType;
7032 Left < LastPromotedIntegralType; ++Left) {
7033 for (unsigned Right = FirstPromotedIntegralType;
7034 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007035 QualType LandR[2] = { getArithmeticType(Left),
7036 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007037 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7038 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007039 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007040 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7041 }
7042 }
7043 }
7044
7045 // C++ [over.built]p20:
7046 //
7047 // For every pair (T, VQ), where T is an enumeration or
7048 // pointer to member type and VQ is either volatile or
7049 // empty, there exist candidate operator functions of the form
7050 //
7051 // VQ T& operator=(VQ T&, T);
7052 void addAssignmentMemberPointerOrEnumeralOverloads() {
7053 /// Set of (canonical) types that we've already handled.
7054 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7055
7056 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7057 for (BuiltinCandidateTypeSet::iterator
7058 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7059 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7060 Enum != EnumEnd; ++Enum) {
7061 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7062 continue;
7063
7064 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7065 CandidateSet);
7066 }
7067
7068 for (BuiltinCandidateTypeSet::iterator
7069 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7070 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7071 MemPtr != MemPtrEnd; ++MemPtr) {
7072 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7073 continue;
7074
7075 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7076 CandidateSet);
7077 }
7078 }
7079 }
7080
7081 // C++ [over.built]p19:
7082 //
7083 // For every pair (T, VQ), where T is any type and VQ is either
7084 // volatile or empty, there exist candidate operator functions
7085 // of the form
7086 //
7087 // T*VQ& operator=(T*VQ&, T*);
7088 //
7089 // C++ [over.built]p21:
7090 //
7091 // For every pair (T, VQ), where T is a cv-qualified or
7092 // cv-unqualified object type and VQ is either volatile or
7093 // empty, there exist candidate operator functions of the form
7094 //
7095 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7096 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7097 void addAssignmentPointerOverloads(bool isEqualOp) {
7098 /// Set of (canonical) types that we've already handled.
7099 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7100
7101 for (BuiltinCandidateTypeSet::iterator
7102 Ptr = CandidateTypes[0].pointer_begin(),
7103 PtrEnd = CandidateTypes[0].pointer_end();
7104 Ptr != PtrEnd; ++Ptr) {
7105 // If this is operator=, keep track of the builtin candidates we added.
7106 if (isEqualOp)
7107 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007108 else if (!(*Ptr)->getPointeeType()->isObjectType())
7109 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007110
7111 // non-volatile version
7112 QualType ParamTypes[2] = {
7113 S.Context.getLValueReferenceType(*Ptr),
7114 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7115 };
7116 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7117 /*IsAssigmentOperator=*/ isEqualOp);
7118
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007119 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7120 VisibleTypeConversionsQuals.hasVolatile();
7121 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007122 // volatile version
7123 ParamTypes[0] =
7124 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7125 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7126 /*IsAssigmentOperator=*/isEqualOp);
7127 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007128
7129 if (!(*Ptr).isRestrictQualified() &&
7130 VisibleTypeConversionsQuals.hasRestrict()) {
7131 // restrict version
7132 ParamTypes[0]
7133 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7134 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7135 /*IsAssigmentOperator=*/isEqualOp);
7136
7137 if (NeedVolatile) {
7138 // volatile restrict version
7139 ParamTypes[0]
7140 = S.Context.getLValueReferenceType(
7141 S.Context.getCVRQualifiedType(*Ptr,
7142 (Qualifiers::Volatile |
7143 Qualifiers::Restrict)));
7144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7145 CandidateSet,
7146 /*IsAssigmentOperator=*/isEqualOp);
7147 }
7148 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007149 }
7150
7151 if (isEqualOp) {
7152 for (BuiltinCandidateTypeSet::iterator
7153 Ptr = CandidateTypes[1].pointer_begin(),
7154 PtrEnd = CandidateTypes[1].pointer_end();
7155 Ptr != PtrEnd; ++Ptr) {
7156 // Make sure we don't add the same candidate twice.
7157 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7158 continue;
7159
Chandler Carruth6df868e2010-12-12 08:17:55 +00007160 QualType ParamTypes[2] = {
7161 S.Context.getLValueReferenceType(*Ptr),
7162 *Ptr,
7163 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007164
7165 // non-volatile version
7166 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7167 /*IsAssigmentOperator=*/true);
7168
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007169 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7170 VisibleTypeConversionsQuals.hasVolatile();
7171 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007172 // volatile version
7173 ParamTypes[0] =
7174 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007175 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7176 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007177 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007178
7179 if (!(*Ptr).isRestrictQualified() &&
7180 VisibleTypeConversionsQuals.hasRestrict()) {
7181 // restrict version
7182 ParamTypes[0]
7183 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7184 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7185 CandidateSet, /*IsAssigmentOperator=*/true);
7186
7187 if (NeedVolatile) {
7188 // volatile restrict version
7189 ParamTypes[0]
7190 = S.Context.getLValueReferenceType(
7191 S.Context.getCVRQualifiedType(*Ptr,
7192 (Qualifiers::Volatile |
7193 Qualifiers::Restrict)));
7194 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7195 CandidateSet, /*IsAssigmentOperator=*/true);
7196
7197 }
7198 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007199 }
7200 }
7201 }
7202
7203 // C++ [over.built]p18:
7204 //
7205 // For every triple (L, VQ, R), where L is an arithmetic type,
7206 // VQ is either volatile or empty, and R is a promoted
7207 // arithmetic type, there exist candidate operator functions of
7208 // the form
7209 //
7210 // VQ L& operator=(VQ L&, R);
7211 // VQ L& operator*=(VQ L&, R);
7212 // VQ L& operator/=(VQ L&, R);
7213 // VQ L& operator+=(VQ L&, R);
7214 // VQ L& operator-=(VQ L&, R);
7215 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007216 if (!HasArithmeticOrEnumeralCandidateType)
7217 return;
7218
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007219 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7220 for (unsigned Right = FirstPromotedArithmeticType;
7221 Right < LastPromotedArithmeticType; ++Right) {
7222 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007223 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007224
7225 // Add this built-in operator as a candidate (VQ is empty).
7226 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007227 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007228 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7229 /*IsAssigmentOperator=*/isEqualOp);
7230
7231 // Add this built-in operator as a candidate (VQ is 'volatile').
7232 if (VisibleTypeConversionsQuals.hasVolatile()) {
7233 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007234 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007235 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007236 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7237 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007238 /*IsAssigmentOperator=*/isEqualOp);
7239 }
7240 }
7241 }
7242
7243 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7244 for (BuiltinCandidateTypeSet::iterator
7245 Vec1 = CandidateTypes[0].vector_begin(),
7246 Vec1End = CandidateTypes[0].vector_end();
7247 Vec1 != Vec1End; ++Vec1) {
7248 for (BuiltinCandidateTypeSet::iterator
7249 Vec2 = CandidateTypes[1].vector_begin(),
7250 Vec2End = CandidateTypes[1].vector_end();
7251 Vec2 != Vec2End; ++Vec2) {
7252 QualType ParamTypes[2];
7253 ParamTypes[1] = *Vec2;
7254 // Add this built-in operator as a candidate (VQ is empty).
7255 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7256 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7257 /*IsAssigmentOperator=*/isEqualOp);
7258
7259 // Add this built-in operator as a candidate (VQ is 'volatile').
7260 if (VisibleTypeConversionsQuals.hasVolatile()) {
7261 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7262 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007263 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7264 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007265 /*IsAssigmentOperator=*/isEqualOp);
7266 }
7267 }
7268 }
7269 }
7270
7271 // C++ [over.built]p22:
7272 //
7273 // For every triple (L, VQ, R), where L is an integral type, VQ
7274 // is either volatile or empty, and R is a promoted integral
7275 // type, there exist candidate operator functions of the form
7276 //
7277 // VQ L& operator%=(VQ L&, R);
7278 // VQ L& operator<<=(VQ L&, R);
7279 // VQ L& operator>>=(VQ L&, R);
7280 // VQ L& operator&=(VQ L&, R);
7281 // VQ L& operator^=(VQ L&, R);
7282 // VQ L& operator|=(VQ L&, R);
7283 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007284 if (!HasArithmeticOrEnumeralCandidateType)
7285 return;
7286
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007287 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7288 for (unsigned Right = FirstPromotedIntegralType;
7289 Right < LastPromotedIntegralType; ++Right) {
7290 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007291 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007292
7293 // Add this built-in operator as a candidate (VQ is empty).
7294 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007295 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007296 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7297 if (VisibleTypeConversionsQuals.hasVolatile()) {
7298 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007299 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007300 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7301 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7303 CandidateSet);
7304 }
7305 }
7306 }
7307 }
7308
7309 // C++ [over.operator]p23:
7310 //
7311 // There also exist candidate operator functions of the form
7312 //
7313 // bool operator!(bool);
7314 // bool operator&&(bool, bool);
7315 // bool operator||(bool, bool);
7316 void addExclaimOverload() {
7317 QualType ParamTy = S.Context.BoolTy;
7318 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7319 /*IsAssignmentOperator=*/false,
7320 /*NumContextualBoolArguments=*/1);
7321 }
7322 void addAmpAmpOrPipePipeOverload() {
7323 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7324 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7325 /*IsAssignmentOperator=*/false,
7326 /*NumContextualBoolArguments=*/2);
7327 }
7328
7329 // C++ [over.built]p13:
7330 //
7331 // For every cv-qualified or cv-unqualified object type T there
7332 // exist candidate operator functions of the form
7333 //
7334 // T* operator+(T*, ptrdiff_t); [ABOVE]
7335 // T& operator[](T*, ptrdiff_t);
7336 // T* operator-(T*, ptrdiff_t); [ABOVE]
7337 // T* operator+(ptrdiff_t, T*); [ABOVE]
7338 // T& operator[](ptrdiff_t, T*);
7339 void addSubscriptOverloads() {
7340 for (BuiltinCandidateTypeSet::iterator
7341 Ptr = CandidateTypes[0].pointer_begin(),
7342 PtrEnd = CandidateTypes[0].pointer_end();
7343 Ptr != PtrEnd; ++Ptr) {
7344 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7345 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007346 if (!PointeeType->isObjectType())
7347 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007348
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007349 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7350
7351 // T& operator[](T*, ptrdiff_t)
7352 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7353 }
7354
7355 for (BuiltinCandidateTypeSet::iterator
7356 Ptr = CandidateTypes[1].pointer_begin(),
7357 PtrEnd = CandidateTypes[1].pointer_end();
7358 Ptr != PtrEnd; ++Ptr) {
7359 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7360 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007361 if (!PointeeType->isObjectType())
7362 continue;
7363
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007364 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7365
7366 // T& operator[](ptrdiff_t, T*)
7367 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7368 }
7369 }
7370
7371 // C++ [over.built]p11:
7372 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7373 // C1 is the same type as C2 or is a derived class of C2, T is an object
7374 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7375 // there exist candidate operator functions of the form
7376 //
7377 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7378 //
7379 // where CV12 is the union of CV1 and CV2.
7380 void addArrowStarOverloads() {
7381 for (BuiltinCandidateTypeSet::iterator
7382 Ptr = CandidateTypes[0].pointer_begin(),
7383 PtrEnd = CandidateTypes[0].pointer_end();
7384 Ptr != PtrEnd; ++Ptr) {
7385 QualType C1Ty = (*Ptr);
7386 QualType C1;
7387 QualifierCollector Q1;
7388 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7389 if (!isa<RecordType>(C1))
7390 continue;
7391 // heuristic to reduce number of builtin candidates in the set.
7392 // Add volatile/restrict version only if there are conversions to a
7393 // volatile/restrict type.
7394 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7395 continue;
7396 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7397 continue;
7398 for (BuiltinCandidateTypeSet::iterator
7399 MemPtr = CandidateTypes[1].member_pointer_begin(),
7400 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7401 MemPtr != MemPtrEnd; ++MemPtr) {
7402 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7403 QualType C2 = QualType(mptr->getClass(), 0);
7404 C2 = C2.getUnqualifiedType();
7405 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7406 break;
7407 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7408 // build CV12 T&
7409 QualType T = mptr->getPointeeType();
7410 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7411 T.isVolatileQualified())
7412 continue;
7413 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7414 T.isRestrictQualified())
7415 continue;
7416 T = Q1.apply(S.Context, T);
7417 QualType ResultTy = S.Context.getLValueReferenceType(T);
7418 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7419 }
7420 }
7421 }
7422
7423 // Note that we don't consider the first argument, since it has been
7424 // contextually converted to bool long ago. The candidates below are
7425 // therefore added as binary.
7426 //
7427 // C++ [over.built]p25:
7428 // For every type T, where T is a pointer, pointer-to-member, or scoped
7429 // enumeration type, there exist candidate operator functions of the form
7430 //
7431 // T operator?(bool, T, T);
7432 //
7433 void addConditionalOperatorOverloads() {
7434 /// Set of (canonical) types that we've already handled.
7435 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7436
7437 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7438 for (BuiltinCandidateTypeSet::iterator
7439 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7440 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7441 Ptr != PtrEnd; ++Ptr) {
7442 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7443 continue;
7444
7445 QualType ParamTypes[2] = { *Ptr, *Ptr };
7446 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7447 }
7448
7449 for (BuiltinCandidateTypeSet::iterator
7450 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7451 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7452 MemPtr != MemPtrEnd; ++MemPtr) {
7453 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7454 continue;
7455
7456 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7457 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7458 }
7459
David Blaikie4e4d0842012-03-11 07:00:24 +00007460 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007461 for (BuiltinCandidateTypeSet::iterator
7462 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7463 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7464 Enum != EnumEnd; ++Enum) {
7465 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7466 continue;
7467
7468 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7469 continue;
7470
7471 QualType ParamTypes[2] = { *Enum, *Enum };
7472 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7473 }
7474 }
7475 }
7476 }
7477};
7478
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007479} // end anonymous namespace
7480
7481/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7482/// operator overloads to the candidate set (C++ [over.built]), based
7483/// on the operator @p Op and the arguments given. For example, if the
7484/// operator is a binary '+', this routine might add "int
7485/// operator+(int, int)" to cover integer addition.
7486void
7487Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7488 SourceLocation OpLoc,
7489 Expr **Args, unsigned NumArgs,
7490 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007491 // Find all of the types that the arguments can convert to, but only
7492 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007493 // that make use of these types. Also record whether we encounter non-record
7494 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007495 Qualifiers VisibleTypeConversionsQuals;
7496 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007497 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7498 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007499
7500 bool HasNonRecordCandidateType = false;
7501 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007502 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007503 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7504 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7505 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7506 OpLoc,
7507 true,
7508 (Op == OO_Exclaim ||
7509 Op == OO_AmpAmp ||
7510 Op == OO_PipePipe),
7511 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007512 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7513 CandidateTypes[ArgIdx].hasNonRecordTypes();
7514 HasArithmeticOrEnumeralCandidateType =
7515 HasArithmeticOrEnumeralCandidateType ||
7516 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007517 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007518
Chandler Carruth6a577462010-12-13 01:44:01 +00007519 // Exit early when no non-record types have been added to the candidate set
7520 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007521 //
7522 // We can't exit early for !, ||, or &&, since there we have always have
7523 // 'bool' overloads.
7524 if (!HasNonRecordCandidateType &&
7525 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007526 return;
7527
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007528 // Setup an object to manage the common state for building overloads.
7529 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7530 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007531 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007532 CandidateTypes, CandidateSet);
7533
7534 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007535 switch (Op) {
7536 case OO_None:
7537 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007538 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007539
Chandler Carruthabb71842010-12-12 08:51:33 +00007540 case OO_New:
7541 case OO_Delete:
7542 case OO_Array_New:
7543 case OO_Array_Delete:
7544 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007545 llvm_unreachable(
7546 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007547
7548 case OO_Comma:
7549 case OO_Arrow:
7550 // C++ [over.match.oper]p3:
7551 // -- For the operator ',', the unary operator '&', or the
7552 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007553 break;
7554
7555 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007556 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007557 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007558 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007559
7560 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007561 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007562 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007563 } else {
7564 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7565 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7566 }
Douglas Gregor74253732008-11-19 15:42:04 +00007567 break;
7568
Chandler Carruthabb71842010-12-12 08:51:33 +00007569 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007570 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007571 OpBuilder.addUnaryStarPointerOverloads();
7572 else
7573 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7574 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007575
Chandler Carruthabb71842010-12-12 08:51:33 +00007576 case OO_Slash:
7577 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007578 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007579
7580 case OO_PlusPlus:
7581 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007582 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7583 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007584 break;
7585
Douglas Gregor19b7b152009-08-24 13:43:27 +00007586 case OO_EqualEqual:
7587 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007588 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007589 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007590
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007591 case OO_Less:
7592 case OO_Greater:
7593 case OO_LessEqual:
7594 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007595 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007596 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7597 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007598
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007599 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007600 case OO_Caret:
7601 case OO_Pipe:
7602 case OO_LessLess:
7603 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007604 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007605 break;
7606
Chandler Carruthabb71842010-12-12 08:51:33 +00007607 case OO_Amp: // '&' is either unary or binary
7608 if (NumArgs == 1)
7609 // C++ [over.match.oper]p3:
7610 // -- For the operator ',', the unary operator '&', or the
7611 // operator '->', the built-in candidates set is empty.
7612 break;
7613
7614 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7615 break;
7616
7617 case OO_Tilde:
7618 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7619 break;
7620
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007621 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007622 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007623 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007624
7625 case OO_PlusEqual:
7626 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007627 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007628 // Fall through.
7629
7630 case OO_StarEqual:
7631 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007632 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007633 break;
7634
7635 case OO_PercentEqual:
7636 case OO_LessLessEqual:
7637 case OO_GreaterGreaterEqual:
7638 case OO_AmpEqual:
7639 case OO_CaretEqual:
7640 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007641 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007642 break;
7643
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007644 case OO_Exclaim:
7645 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007646 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007647
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007648 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007649 case OO_PipePipe:
7650 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007651 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007652
7653 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007654 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007655 break;
7656
7657 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007658 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007659 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007660
7661 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007662 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007663 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7664 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007665 }
7666}
7667
Douglas Gregorfa047642009-02-04 00:32:51 +00007668/// \brief Add function candidates found via argument-dependent lookup
7669/// to the set of overloading candidates.
7670///
7671/// This routine performs argument-dependent name lookup based on the
7672/// given function name (which may also be an operator name) and adds
7673/// all of the overload candidates found by ADL to the overload
7674/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007675void
Douglas Gregorfa047642009-02-04 00:32:51 +00007676Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007677 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007678 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007679 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007680 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007681 bool PartialOverloading,
7682 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007683 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007684
John McCalla113e722010-01-26 06:04:06 +00007685 // FIXME: This approach for uniquing ADL results (and removing
7686 // redundant candidates from the set) relies on pointer-equality,
7687 // which means we need to key off the canonical decl. However,
7688 // always going back to the canonical decl might not get us the
7689 // right set of default arguments. What default arguments are
7690 // we supposed to consider on ADL candidates, anyway?
7691
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007692 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007693 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007694 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007695
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007696 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007697 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7698 CandEnd = CandidateSet.end();
7699 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007700 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007701 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007702 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007703 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007704 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007705
7706 // For each of the ADL candidates we found, add it to the overload
7707 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007708 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007709 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007710 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007711 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007712 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007713
Ahmed Charles13a140c2012-02-25 11:00:22 +00007714 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7715 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007716 } else
John McCall6e266892010-01-26 03:27:55 +00007717 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007718 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007719 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007720 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007721}
7722
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007723/// isBetterOverloadCandidate - Determines whether the first overload
7724/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007725bool
John McCall120d63c2010-08-24 20:38:10 +00007726isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007727 const OverloadCandidate &Cand1,
7728 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007729 SourceLocation Loc,
7730 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007731 // Define viable functions to be better candidates than non-viable
7732 // functions.
7733 if (!Cand2.Viable)
7734 return Cand1.Viable;
7735 else if (!Cand1.Viable)
7736 return false;
7737
Douglas Gregor88a35142008-12-22 05:46:06 +00007738 // C++ [over.match.best]p1:
7739 //
7740 // -- if F is a static member function, ICS1(F) is defined such
7741 // that ICS1(F) is neither better nor worse than ICS1(G) for
7742 // any function G, and, symmetrically, ICS1(G) is neither
7743 // better nor worse than ICS1(F).
7744 unsigned StartArg = 0;
7745 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7746 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007747
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007748 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007749 // A viable function F1 is defined to be a better function than another
7750 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007751 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007752 unsigned NumArgs = Cand1.NumConversions;
7753 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007754 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007755 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007756 switch (CompareImplicitConversionSequences(S,
7757 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007758 Cand2.Conversions[ArgIdx])) {
7759 case ImplicitConversionSequence::Better:
7760 // Cand1 has a better conversion sequence.
7761 HasBetterConversion = true;
7762 break;
7763
7764 case ImplicitConversionSequence::Worse:
7765 // Cand1 can't be better than Cand2.
7766 return false;
7767
7768 case ImplicitConversionSequence::Indistinguishable:
7769 // Do nothing.
7770 break;
7771 }
7772 }
7773
Mike Stump1eb44332009-09-09 15:08:12 +00007774 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007775 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007776 if (HasBetterConversion)
7777 return true;
7778
Mike Stump1eb44332009-09-09 15:08:12 +00007779 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007780 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007781 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007782 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7783 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007784
7785 // -- F1 and F2 are function template specializations, and the function
7786 // template for F1 is more specialized than the template for F2
7787 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007788 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007789 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007790 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007791 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007792 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7793 Cand2.Function->getPrimaryTemplate(),
7794 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007795 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007796 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007797 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007798 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007799 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007800
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007801 // -- the context is an initialization by user-defined conversion
7802 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7803 // from the return type of F1 to the destination type (i.e.,
7804 // the type of the entity being initialized) is a better
7805 // conversion sequence than the standard conversion sequence
7806 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007807 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007808 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007809 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007810 // First check whether we prefer one of the conversion functions over the
7811 // other. This only distinguishes the results in non-standard, extension
7812 // cases such as the conversion from a lambda closure type to a function
7813 // pointer or block.
7814 ImplicitConversionSequence::CompareKind FuncResult
7815 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7816 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7817 return FuncResult;
7818
John McCall120d63c2010-08-24 20:38:10 +00007819 switch (CompareStandardConversionSequences(S,
7820 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007821 Cand2.FinalConversion)) {
7822 case ImplicitConversionSequence::Better:
7823 // Cand1 has a better conversion sequence.
7824 return true;
7825
7826 case ImplicitConversionSequence::Worse:
7827 // Cand1 can't be better than Cand2.
7828 return false;
7829
7830 case ImplicitConversionSequence::Indistinguishable:
7831 // Do nothing
7832 break;
7833 }
7834 }
7835
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007836 return false;
7837}
7838
Mike Stump1eb44332009-09-09 15:08:12 +00007839/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007840/// within an overload candidate set.
7841///
James Dennettefce31f2012-06-22 08:10:18 +00007842/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007843/// which overload resolution occurs.
7844///
James Dennettefce31f2012-06-22 08:10:18 +00007845/// \param Best If overload resolution was successful or found a deleted
7846/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007847///
7848/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007849OverloadingResult
7850OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007851 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007852 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007853 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007854 Best = end();
7855 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7856 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007857 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007858 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007859 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007860 }
7861
7862 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007863 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007864 return OR_No_Viable_Function;
7865
7866 // Make sure that this function is better than every other viable
7867 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007868 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007869 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007870 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007871 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007872 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007873 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007874 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007875 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007876 }
Mike Stump1eb44332009-09-09 15:08:12 +00007877
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007878 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007879 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007880 (Best->Function->isDeleted() ||
7881 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007882 return OR_Deleted;
7883
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007884 return OR_Success;
7885}
7886
John McCall3c80f572010-01-12 02:15:36 +00007887namespace {
7888
7889enum OverloadCandidateKind {
7890 oc_function,
7891 oc_method,
7892 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007893 oc_function_template,
7894 oc_method_template,
7895 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007896 oc_implicit_default_constructor,
7897 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007898 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007899 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007900 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007901 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007902};
7903
John McCall220ccbf2010-01-13 00:25:19 +00007904OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7905 FunctionDecl *Fn,
7906 std::string &Description) {
7907 bool isTemplate = false;
7908
7909 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7910 isTemplate = true;
7911 Description = S.getTemplateArgumentBindingsText(
7912 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7913 }
John McCallb1622a12010-01-06 09:43:14 +00007914
7915 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007916 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007917 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007918
Sebastian Redlf677ea32011-02-05 19:23:19 +00007919 if (Ctor->getInheritedConstructor())
7920 return oc_implicit_inherited_constructor;
7921
Sean Hunt82713172011-05-25 23:16:36 +00007922 if (Ctor->isDefaultConstructor())
7923 return oc_implicit_default_constructor;
7924
7925 if (Ctor->isMoveConstructor())
7926 return oc_implicit_move_constructor;
7927
7928 assert(Ctor->isCopyConstructor() &&
7929 "unexpected sort of implicit constructor");
7930 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007931 }
7932
7933 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7934 // This actually gets spelled 'candidate function' for now, but
7935 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007936 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007937 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007938
Sean Hunt82713172011-05-25 23:16:36 +00007939 if (Meth->isMoveAssignmentOperator())
7940 return oc_implicit_move_assignment;
7941
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007942 if (Meth->isCopyAssignmentOperator())
7943 return oc_implicit_copy_assignment;
7944
7945 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7946 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007947 }
7948
John McCall220ccbf2010-01-13 00:25:19 +00007949 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007950}
7951
Sebastian Redlf677ea32011-02-05 19:23:19 +00007952void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7953 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7954 if (!Ctor) return;
7955
7956 Ctor = Ctor->getInheritedConstructor();
7957 if (!Ctor) return;
7958
7959 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7960}
7961
John McCall3c80f572010-01-12 02:15:36 +00007962} // end anonymous namespace
7963
7964// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007965void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007966 std::string FnDesc;
7967 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007968 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7969 << (unsigned) K << FnDesc;
7970 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7971 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007972 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007973}
7974
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007975//Notes the location of all overload candidates designated through
7976// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007977void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007978 assert(OverloadedExpr->getType() == Context.OverloadTy);
7979
7980 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7981 OverloadExpr *OvlExpr = Ovl.Expression;
7982
7983 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7984 IEnd = OvlExpr->decls_end();
7985 I != IEnd; ++I) {
7986 if (FunctionTemplateDecl *FunTmpl =
7987 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007988 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007989 } else if (FunctionDecl *Fun
7990 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007991 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007992 }
7993 }
7994}
7995
John McCall1d318332010-01-12 00:44:57 +00007996/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7997/// "lead" diagnostic; it will be given two arguments, the source and
7998/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007999void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8000 Sema &S,
8001 SourceLocation CaretLoc,
8002 const PartialDiagnostic &PDiag) const {
8003 S.Diag(CaretLoc, PDiag)
8004 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00008005 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00008006 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8007 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008008 }
John McCall81201622010-01-08 04:41:39 +00008009}
8010
John McCall1d318332010-01-12 00:44:57 +00008011namespace {
8012
John McCalladbb8f82010-01-13 09:16:55 +00008013void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8014 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8015 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008016 assert(Cand->Function && "for now, candidate must be a function");
8017 FunctionDecl *Fn = Cand->Function;
8018
8019 // There's a conversion slot for the object argument if this is a
8020 // non-constructor method. Note that 'I' corresponds the
8021 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008022 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008023 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008024 if (I == 0)
8025 isObjectArgument = true;
8026 else
8027 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008028 }
8029
John McCall220ccbf2010-01-13 00:25:19 +00008030 std::string FnDesc;
8031 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8032
John McCalladbb8f82010-01-13 09:16:55 +00008033 Expr *FromExpr = Conv.Bad.FromExpr;
8034 QualType FromTy = Conv.Bad.getFromType();
8035 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008036
John McCall5920dbb2010-02-02 02:42:52 +00008037 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008038 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008039 Expr *E = FromExpr->IgnoreParens();
8040 if (isa<UnaryOperator>(E))
8041 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008042 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008043
8044 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8045 << (unsigned) FnKind << FnDesc
8046 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8047 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008048 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008049 return;
8050 }
8051
John McCall258b2032010-01-23 08:10:49 +00008052 // Do some hand-waving analysis to see if the non-viability is due
8053 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008054 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8055 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8056 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8057 CToTy = RT->getPointeeType();
8058 else {
8059 // TODO: detect and diagnose the full richness of const mismatches.
8060 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8061 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8062 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8063 }
8064
8065 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8066 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008067 Qualifiers FromQs = CFromTy.getQualifiers();
8068 Qualifiers ToQs = CToTy.getQualifiers();
8069
8070 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8072 << (unsigned) FnKind << FnDesc
8073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8074 << FromTy
8075 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8076 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008077 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008078 return;
8079 }
8080
John McCallf85e1932011-06-15 23:02:42 +00008081 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008083 << (unsigned) FnKind << FnDesc
8084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8085 << FromTy
8086 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8087 << (unsigned) isObjectArgument << I+1;
8088 MaybeEmitInheritedConstructorNote(S, Fn);
8089 return;
8090 }
8091
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008092 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8094 << (unsigned) FnKind << FnDesc
8095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8096 << FromTy
8097 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8098 << (unsigned) isObjectArgument << I+1;
8099 MaybeEmitInheritedConstructorNote(S, Fn);
8100 return;
8101 }
8102
John McCall651f3ee2010-01-14 03:28:57 +00008103 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8104 assert(CVR && "unexpected qualifiers mismatch");
8105
8106 if (isObjectArgument) {
8107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8108 << (unsigned) FnKind << FnDesc
8109 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8110 << FromTy << (CVR - 1);
8111 } else {
8112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8113 << (unsigned) FnKind << FnDesc
8114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8115 << FromTy << (CVR - 1) << I+1;
8116 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008117 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008118 return;
8119 }
8120
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008121 // Special diagnostic for failure to convert an initializer list, since
8122 // telling the user that it has type void is not useful.
8123 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8125 << (unsigned) FnKind << FnDesc
8126 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8127 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8128 MaybeEmitInheritedConstructorNote(S, Fn);
8129 return;
8130 }
8131
John McCall258b2032010-01-23 08:10:49 +00008132 // Diagnose references or pointers to incomplete types differently,
8133 // since it's far from impossible that the incompleteness triggered
8134 // the failure.
8135 QualType TempFromTy = FromTy.getNonReferenceType();
8136 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8137 TempFromTy = PTy->getPointeeType();
8138 if (TempFromTy->isIncompleteType()) {
8139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8140 << (unsigned) FnKind << FnDesc
8141 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8142 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008143 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008144 return;
8145 }
8146
Douglas Gregor85789812010-06-30 23:01:39 +00008147 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008148 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008149 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8150 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8151 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8152 FromPtrTy->getPointeeType()) &&
8153 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8154 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008155 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008156 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008157 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008158 }
8159 } else if (const ObjCObjectPointerType *FromPtrTy
8160 = FromTy->getAs<ObjCObjectPointerType>()) {
8161 if (const ObjCObjectPointerType *ToPtrTy
8162 = ToTy->getAs<ObjCObjectPointerType>())
8163 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8164 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8165 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8166 FromPtrTy->getPointeeType()) &&
8167 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008168 BaseToDerivedConversion = 2;
8169 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008170 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8171 !FromTy->isIncompleteType() &&
8172 !ToRefTy->getPointeeType()->isIncompleteType() &&
8173 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8174 BaseToDerivedConversion = 3;
8175 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8176 ToTy.getNonReferenceType().getCanonicalType() ==
8177 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8179 << (unsigned) FnKind << FnDesc
8180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8181 << (unsigned) isObjectArgument << I + 1;
8182 MaybeEmitInheritedConstructorNote(S, Fn);
8183 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008184 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008186
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008187 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008188 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008189 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008190 << (unsigned) FnKind << FnDesc
8191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008192 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008193 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008194 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008195 return;
8196 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008197
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008198 if (isa<ObjCObjectPointerType>(CFromTy) &&
8199 isa<PointerType>(CToTy)) {
8200 Qualifiers FromQs = CFromTy.getQualifiers();
8201 Qualifiers ToQs = CToTy.getQualifiers();
8202 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8203 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8204 << (unsigned) FnKind << FnDesc
8205 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8206 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8207 MaybeEmitInheritedConstructorNote(S, Fn);
8208 return;
8209 }
8210 }
8211
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008212 // Emit the generic diagnostic and, optionally, add the hints to it.
8213 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8214 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008215 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008216 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8217 << (unsigned) (Cand->Fix.Kind);
8218
8219 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008220 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8221 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008222 FDiag << *HI;
8223 S.Diag(Fn->getLocation(), FDiag);
8224
Sebastian Redlf677ea32011-02-05 19:23:19 +00008225 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008226}
8227
8228void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8229 unsigned NumFormalArgs) {
8230 // TODO: treat calls to a missing default constructor as a special case
8231
8232 FunctionDecl *Fn = Cand->Function;
8233 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8234
8235 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008236
Douglas Gregor439d3c32011-05-05 00:13:13 +00008237 // With invalid overloaded operators, it's possible that we think we
8238 // have an arity mismatch when it fact it looks like we have the
8239 // right number of arguments, because only overloaded operators have
8240 // the weird behavior of overloading member and non-member functions.
8241 // Just don't report anything.
8242 if (Fn->isInvalidDecl() &&
8243 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8244 return;
8245
John McCalladbb8f82010-01-13 09:16:55 +00008246 // at least / at most / exactly
8247 unsigned mode, modeCount;
8248 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008249 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8250 (Cand->FailureKind == ovl_fail_bad_deduction &&
8251 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008252 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008253 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008254 mode = 0; // "at least"
8255 else
8256 mode = 2; // "exactly"
8257 modeCount = MinParams;
8258 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008259 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8260 (Cand->FailureKind == ovl_fail_bad_deduction &&
8261 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008262 if (MinParams != FnTy->getNumArgs())
8263 mode = 1; // "at most"
8264 else
8265 mode = 2; // "exactly"
8266 modeCount = FnTy->getNumArgs();
8267 }
8268
8269 std::string Description;
8270 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8271
Richard Smithf7b80562012-05-11 05:16:41 +00008272 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8274 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8275 << Fn->getParamDecl(0) << NumFormalArgs;
8276 else
8277 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8278 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8279 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008280 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008281}
8282
John McCall342fec42010-02-01 18:53:26 +00008283/// Diagnose a failed template-argument deduction.
8284void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008285 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008286 FunctionDecl *Fn = Cand->Function; // pattern
8287
Douglas Gregora9333192010-05-08 17:41:32 +00008288 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008289 NamedDecl *ParamD;
8290 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8291 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8292 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008293 switch (Cand->DeductionFailure.Result) {
8294 case Sema::TDK_Success:
8295 llvm_unreachable("TDK_success while diagnosing bad deduction");
8296
8297 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008298 assert(ParamD && "no parameter found for incomplete deduction result");
8299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8300 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008301 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008302 return;
8303 }
8304
John McCall57e97782010-08-05 09:05:08 +00008305 case Sema::TDK_Underqualified: {
8306 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8307 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8308
8309 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8310
8311 // Param will have been canonicalized, but it should just be a
8312 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008313 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008314 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008315 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008316 assert(S.Context.hasSameType(Param, NonCanonParam));
8317
8318 // Arg has also been canonicalized, but there's nothing we can do
8319 // about that. It also doesn't matter as much, because it won't
8320 // have any template parameters in it (because deduction isn't
8321 // done on dependent types).
8322 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8323
8324 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8325 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008326 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008327 return;
8328 }
8329
8330 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008331 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008332 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008333 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008334 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008335 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008336 which = 1;
8337 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008338 which = 2;
8339 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008340
Douglas Gregora9333192010-05-08 17:41:32 +00008341 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008342 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008343 << *Cand->DeductionFailure.getFirstArg()
8344 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008345 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008346 return;
8347 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008348
Douglas Gregorf1a84452010-05-08 19:15:54 +00008349 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008350 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008351 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008352 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008353 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8354 << ParamD->getDeclName();
8355 else {
8356 int index = 0;
8357 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8358 index = TTP->getIndex();
8359 else if (NonTypeTemplateParmDecl *NTTP
8360 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8361 index = NTTP->getIndex();
8362 else
8363 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008364 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008365 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8366 << (index + 1);
8367 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008368 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008369 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008370
Douglas Gregora18592e2010-05-08 18:13:28 +00008371 case Sema::TDK_TooManyArguments:
8372 case Sema::TDK_TooFewArguments:
8373 DiagnoseArityMismatch(S, Cand, NumArgs);
8374 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008375
8376 case Sema::TDK_InstantiationDepth:
8377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008378 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008379 return;
8380
8381 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008382 // Format the template argument list into the argument string.
8383 llvm::SmallString<128> TemplateArgString;
8384 if (TemplateArgumentList *Args =
8385 Cand->DeductionFailure.getTemplateArgumentList()) {
8386 TemplateArgString = " ";
8387 TemplateArgString += S.getTemplateArgumentBindingsText(
8388 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8389 }
8390
Richard Smith4493c0a2012-05-09 05:17:00 +00008391 // If this candidate was disabled by enable_if, say so.
8392 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8393 if (PDiag && PDiag->second.getDiagID() ==
8394 diag::err_typename_nested_not_found_enable_if) {
8395 // FIXME: Use the source range of the condition, and the fully-qualified
8396 // name of the enable_if template. These are both present in PDiag.
8397 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8398 << "'enable_if'" << TemplateArgString;
8399 return;
8400 }
8401
Richard Smithb8590f32012-05-07 09:03:25 +00008402 // Format the SFINAE diagnostic into the argument string.
8403 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8404 // formatted message in another diagnostic.
8405 llvm::SmallString<128> SFINAEArgString;
8406 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008407 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008408 SFINAEArgString = ": ";
8409 R = SourceRange(PDiag->first, PDiag->first);
8410 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8411 }
8412
Douglas Gregorec20f462010-05-08 20:07:26 +00008413 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008414 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008415 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008416 return;
8417 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008418
John McCall342fec42010-02-01 18:53:26 +00008419 // TODO: diagnose these individually, then kill off
8420 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008421 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008422 case Sema::TDK_FailedOverloadResolution:
8423 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008424 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008425 return;
8426 }
8427}
8428
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008429/// CUDA: diagnose an invalid call across targets.
8430void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8431 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8432 FunctionDecl *Callee = Cand->Function;
8433
8434 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8435 CalleeTarget = S.IdentifyCUDATarget(Callee);
8436
8437 std::string FnDesc;
8438 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8439
8440 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8441 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8442}
8443
John McCall342fec42010-02-01 18:53:26 +00008444/// Generates a 'note' diagnostic for an overload candidate. We've
8445/// already generated a primary error at the call site.
8446///
8447/// It really does need to be a single diagnostic with its caret
8448/// pointed at the candidate declaration. Yes, this creates some
8449/// major challenges of technical writing. Yes, this makes pointing
8450/// out problems with specific arguments quite awkward. It's still
8451/// better than generating twenty screens of text for every failed
8452/// overload.
8453///
8454/// It would be great to be able to express per-candidate problems
8455/// more richly for those diagnostic clients that cared, but we'd
8456/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008457void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008458 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008459 FunctionDecl *Fn = Cand->Function;
8460
John McCall81201622010-01-08 04:41:39 +00008461 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008462 if (Cand->Viable && (Fn->isDeleted() ||
8463 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008464 std::string FnDesc;
8465 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008466
8467 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008468 << FnKind << FnDesc
8469 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008470 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008471 return;
John McCall81201622010-01-08 04:41:39 +00008472 }
8473
John McCall220ccbf2010-01-13 00:25:19 +00008474 // We don't really have anything else to say about viable candidates.
8475 if (Cand->Viable) {
8476 S.NoteOverloadCandidate(Fn);
8477 return;
8478 }
John McCall1d318332010-01-12 00:44:57 +00008479
John McCalladbb8f82010-01-13 09:16:55 +00008480 switch (Cand->FailureKind) {
8481 case ovl_fail_too_many_arguments:
8482 case ovl_fail_too_few_arguments:
8483 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008484
John McCalladbb8f82010-01-13 09:16:55 +00008485 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008486 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008487
John McCall717e8912010-01-23 05:17:32 +00008488 case ovl_fail_trivial_conversion:
8489 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008490 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008491 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008492
John McCallb1bdc622010-02-25 01:37:24 +00008493 case ovl_fail_bad_conversion: {
8494 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008495 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008496 if (Cand->Conversions[I].isBad())
8497 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008498
John McCalladbb8f82010-01-13 09:16:55 +00008499 // FIXME: this currently happens when we're called from SemaInit
8500 // when user-conversion overload fails. Figure out how to handle
8501 // those conditions and diagnose them well.
8502 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008503 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008504
8505 case ovl_fail_bad_target:
8506 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008507 }
John McCalla1d7d622010-01-08 00:58:21 +00008508}
8509
8510void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8511 // Desugar the type of the surrogate down to a function type,
8512 // retaining as many typedefs as possible while still showing
8513 // the function type (and, therefore, its parameter types).
8514 QualType FnType = Cand->Surrogate->getConversionType();
8515 bool isLValueReference = false;
8516 bool isRValueReference = false;
8517 bool isPointer = false;
8518 if (const LValueReferenceType *FnTypeRef =
8519 FnType->getAs<LValueReferenceType>()) {
8520 FnType = FnTypeRef->getPointeeType();
8521 isLValueReference = true;
8522 } else if (const RValueReferenceType *FnTypeRef =
8523 FnType->getAs<RValueReferenceType>()) {
8524 FnType = FnTypeRef->getPointeeType();
8525 isRValueReference = true;
8526 }
8527 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8528 FnType = FnTypePtr->getPointeeType();
8529 isPointer = true;
8530 }
8531 // Desugar down to a function type.
8532 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8533 // Reconstruct the pointer/reference as appropriate.
8534 if (isPointer) FnType = S.Context.getPointerType(FnType);
8535 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8536 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8537
8538 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8539 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008540 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008541}
8542
8543void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008544 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008545 SourceLocation OpLoc,
8546 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008547 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008548 std::string TypeStr("operator");
8549 TypeStr += Opc;
8550 TypeStr += "(";
8551 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008552 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008553 TypeStr += ")";
8554 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8555 } else {
8556 TypeStr += ", ";
8557 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8558 TypeStr += ")";
8559 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8560 }
8561}
8562
8563void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8564 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008565 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008566 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8567 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008568 if (ICS.isBad()) break; // all meaningless after first invalid
8569 if (!ICS.isAmbiguous()) continue;
8570
John McCall120d63c2010-08-24 20:38:10 +00008571 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008572 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008573 }
8574}
8575
John McCall1b77e732010-01-15 23:32:50 +00008576SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8577 if (Cand->Function)
8578 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008579 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008580 return Cand->Surrogate->getLocation();
8581 return SourceLocation();
8582}
8583
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008584static unsigned
8585RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008586 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008587 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008588 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008589
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008590 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008591 case Sema::TDK_Incomplete:
8592 return 1;
8593
8594 case Sema::TDK_Underqualified:
8595 case Sema::TDK_Inconsistent:
8596 return 2;
8597
8598 case Sema::TDK_SubstitutionFailure:
8599 case Sema::TDK_NonDeducedMismatch:
8600 return 3;
8601
8602 case Sema::TDK_InstantiationDepth:
8603 case Sema::TDK_FailedOverloadResolution:
8604 return 4;
8605
8606 case Sema::TDK_InvalidExplicitArguments:
8607 return 5;
8608
8609 case Sema::TDK_TooManyArguments:
8610 case Sema::TDK_TooFewArguments:
8611 return 6;
8612 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008613 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008614}
8615
John McCallbf65c0b2010-01-12 00:48:53 +00008616struct CompareOverloadCandidatesForDisplay {
8617 Sema &S;
8618 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008619
8620 bool operator()(const OverloadCandidate *L,
8621 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008622 // Fast-path this check.
8623 if (L == R) return false;
8624
John McCall81201622010-01-08 04:41:39 +00008625 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008626 if (L->Viable) {
8627 if (!R->Viable) return true;
8628
8629 // TODO: introduce a tri-valued comparison for overload
8630 // candidates. Would be more worthwhile if we had a sort
8631 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008632 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8633 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008634 } else if (R->Viable)
8635 return false;
John McCall81201622010-01-08 04:41:39 +00008636
John McCall1b77e732010-01-15 23:32:50 +00008637 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008638
John McCall1b77e732010-01-15 23:32:50 +00008639 // Criteria by which we can sort non-viable candidates:
8640 if (!L->Viable) {
8641 // 1. Arity mismatches come after other candidates.
8642 if (L->FailureKind == ovl_fail_too_many_arguments ||
8643 L->FailureKind == ovl_fail_too_few_arguments)
8644 return false;
8645 if (R->FailureKind == ovl_fail_too_many_arguments ||
8646 R->FailureKind == ovl_fail_too_few_arguments)
8647 return true;
John McCall81201622010-01-08 04:41:39 +00008648
John McCall717e8912010-01-23 05:17:32 +00008649 // 2. Bad conversions come first and are ordered by the number
8650 // of bad conversions and quality of good conversions.
8651 if (L->FailureKind == ovl_fail_bad_conversion) {
8652 if (R->FailureKind != ovl_fail_bad_conversion)
8653 return true;
8654
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008655 // The conversion that can be fixed with a smaller number of changes,
8656 // comes first.
8657 unsigned numLFixes = L->Fix.NumConversionsFixed;
8658 unsigned numRFixes = R->Fix.NumConversionsFixed;
8659 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8660 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008661 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008662 if (numLFixes < numRFixes)
8663 return true;
8664 else
8665 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008666 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008667
John McCall717e8912010-01-23 05:17:32 +00008668 // If there's any ordering between the defined conversions...
8669 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008670 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008671
8672 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008673 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008674 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008675 switch (CompareImplicitConversionSequences(S,
8676 L->Conversions[I],
8677 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008678 case ImplicitConversionSequence::Better:
8679 leftBetter++;
8680 break;
8681
8682 case ImplicitConversionSequence::Worse:
8683 leftBetter--;
8684 break;
8685
8686 case ImplicitConversionSequence::Indistinguishable:
8687 break;
8688 }
8689 }
8690 if (leftBetter > 0) return true;
8691 if (leftBetter < 0) return false;
8692
8693 } else if (R->FailureKind == ovl_fail_bad_conversion)
8694 return false;
8695
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008696 if (L->FailureKind == ovl_fail_bad_deduction) {
8697 if (R->FailureKind != ovl_fail_bad_deduction)
8698 return true;
8699
8700 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8701 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008702 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008703 } else if (R->FailureKind == ovl_fail_bad_deduction)
8704 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008705
John McCall1b77e732010-01-15 23:32:50 +00008706 // TODO: others?
8707 }
8708
8709 // Sort everything else by location.
8710 SourceLocation LLoc = GetLocationForCandidate(L);
8711 SourceLocation RLoc = GetLocationForCandidate(R);
8712
8713 // Put candidates without locations (e.g. builtins) at the end.
8714 if (LLoc.isInvalid()) return false;
8715 if (RLoc.isInvalid()) return true;
8716
8717 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008718 }
8719};
8720
John McCall717e8912010-01-23 05:17:32 +00008721/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008722/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008723void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008724 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008725 assert(!Cand->Viable);
8726
8727 // Don't do anything on failures other than bad conversion.
8728 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8729
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008730 // We only want the FixIts if all the arguments can be corrected.
8731 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008732 // Use a implicit copy initialization to check conversion fixes.
8733 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008734
John McCall717e8912010-01-23 05:17:32 +00008735 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008736 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008737 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008738 while (true) {
8739 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8740 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008741 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008742 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008743 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008744 }
John McCall717e8912010-01-23 05:17:32 +00008745 }
8746
8747 if (ConvIdx == ConvCount)
8748 return;
8749
John McCallb1bdc622010-02-25 01:37:24 +00008750 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8751 "remaining conversion is initialized?");
8752
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008753 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008754 // operation somehow.
8755 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008756
8757 const FunctionProtoType* Proto;
8758 unsigned ArgIdx = ConvIdx;
8759
8760 if (Cand->IsSurrogate) {
8761 QualType ConvType
8762 = Cand->Surrogate->getConversionType().getNonReferenceType();
8763 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8764 ConvType = ConvPtrType->getPointeeType();
8765 Proto = ConvType->getAs<FunctionProtoType>();
8766 ArgIdx--;
8767 } else if (Cand->Function) {
8768 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8769 if (isa<CXXMethodDecl>(Cand->Function) &&
8770 !isa<CXXConstructorDecl>(Cand->Function))
8771 ArgIdx--;
8772 } else {
8773 // Builtin binary operator with a bad first conversion.
8774 assert(ConvCount <= 3);
8775 for (; ConvIdx != ConvCount; ++ConvIdx)
8776 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008777 = TryCopyInitialization(S, Args[ConvIdx],
8778 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008779 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008780 /*InOverloadResolution*/ true,
8781 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008782 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008783 return;
8784 }
8785
8786 // Fill in the rest of the conversions.
8787 unsigned NumArgsInProto = Proto->getNumArgs();
8788 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008789 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008790 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008791 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008792 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008793 /*InOverloadResolution=*/true,
8794 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008795 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008796 // Store the FixIt in the candidate if it exists.
8797 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008798 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008799 }
John McCall717e8912010-01-23 05:17:32 +00008800 else
8801 Cand->Conversions[ConvIdx].setEllipsis();
8802 }
8803}
8804
John McCalla1d7d622010-01-08 00:58:21 +00008805} // end anonymous namespace
8806
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008807/// PrintOverloadCandidates - When overload resolution fails, prints
8808/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008809/// set.
John McCall120d63c2010-08-24 20:38:10 +00008810void OverloadCandidateSet::NoteCandidates(Sema &S,
8811 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008812 llvm::ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008813 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008814 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008815 // Sort the candidates by viability and position. Sorting directly would
8816 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008817 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008818 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8819 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008820 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008821 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008822 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008823 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008824 if (Cand->Function || Cand->IsSurrogate)
8825 Cands.push_back(Cand);
8826 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8827 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008828 }
8829 }
8830
John McCallbf65c0b2010-01-12 00:48:53 +00008831 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008832 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008833
John McCall1d318332010-01-12 00:44:57 +00008834 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008835
Chris Lattner5f9e2722011-07-23 10:55:15 +00008836 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008837 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8838 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008839 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008840 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8841 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008842
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008843 // Set an arbitrary limit on the number of candidate functions we'll spam
8844 // the user with. FIXME: This limit should depend on details of the
8845 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008846 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008847 break;
8848 }
8849 ++CandsShown;
8850
John McCalla1d7d622010-01-08 00:58:21 +00008851 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008852 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008853 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008854 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008855 else {
8856 assert(Cand->Viable &&
8857 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008858 // Generally we only see ambiguities including viable builtin
8859 // operators if overload resolution got screwed up by an
8860 // ambiguous user-defined conversion.
8861 //
8862 // FIXME: It's quite possible for different conversions to see
8863 // different ambiguities, though.
8864 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008865 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008866 ReportedAmbiguousConversions = true;
8867 }
John McCalla1d7d622010-01-08 00:58:21 +00008868
John McCall1d318332010-01-12 00:44:57 +00008869 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008870 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008871 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008872 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008873
8874 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008875 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008876}
8877
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008878// [PossiblyAFunctionType] --> [Return]
8879// NonFunctionType --> NonFunctionType
8880// R (A) --> R(A)
8881// R (*)(A) --> R (A)
8882// R (&)(A) --> R (A)
8883// R (S::*)(A) --> R (A)
8884QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8885 QualType Ret = PossiblyAFunctionType;
8886 if (const PointerType *ToTypePtr =
8887 PossiblyAFunctionType->getAs<PointerType>())
8888 Ret = ToTypePtr->getPointeeType();
8889 else if (const ReferenceType *ToTypeRef =
8890 PossiblyAFunctionType->getAs<ReferenceType>())
8891 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008892 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008893 PossiblyAFunctionType->getAs<MemberPointerType>())
8894 Ret = MemTypePtr->getPointeeType();
8895 Ret =
8896 Context.getCanonicalType(Ret).getUnqualifiedType();
8897 return Ret;
8898}
Douglas Gregor904eed32008-11-10 20:40:00 +00008899
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008900// A helper class to help with address of function resolution
8901// - allows us to avoid passing around all those ugly parameters
8902class AddressOfFunctionResolver
8903{
8904 Sema& S;
8905 Expr* SourceExpr;
8906 const QualType& TargetType;
8907 QualType TargetFunctionType; // Extracted function type from target type
8908
8909 bool Complain;
8910 //DeclAccessPair& ResultFunctionAccessPair;
8911 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008912
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008913 bool TargetTypeIsNonStaticMemberFunction;
8914 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008915
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008916 OverloadExpr::FindResult OvlExprInfo;
8917 OverloadExpr *OvlExpr;
8918 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008919 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008920
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008921public:
8922 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8923 const QualType& TargetType, bool Complain)
8924 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8925 Complain(Complain), Context(S.getASTContext()),
8926 TargetTypeIsNonStaticMemberFunction(
8927 !!TargetType->getAs<MemberPointerType>()),
8928 FoundNonTemplateFunction(false),
8929 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8930 OvlExpr(OvlExprInfo.Expression)
8931 {
8932 ExtractUnqualifiedFunctionTypeFromTargetType();
8933
8934 if (!TargetFunctionType->isFunctionType()) {
8935 if (OvlExpr->hasExplicitTemplateArgs()) {
8936 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008937 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008938 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008939
8940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8941 if (!Method->isStatic()) {
8942 // If the target type is a non-function type and the function
8943 // found is a non-static member function, pretend as if that was
8944 // the target, it's the only possible type to end up with.
8945 TargetTypeIsNonStaticMemberFunction = true;
8946
8947 // And skip adding the function if its not in the proper form.
8948 // We'll diagnose this due to an empty set of functions.
8949 if (!OvlExprInfo.HasFormOfMemberPointer)
8950 return;
8951 }
8952 }
8953
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008954 Matches.push_back(std::make_pair(dap,Fn));
8955 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008956 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008957 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008958 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008959
8960 if (OvlExpr->hasExplicitTemplateArgs())
8961 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008962
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008963 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8964 // C++ [over.over]p4:
8965 // If more than one function is selected, [...]
8966 if (Matches.size() > 1) {
8967 if (FoundNonTemplateFunction)
8968 EliminateAllTemplateMatches();
8969 else
8970 EliminateAllExceptMostSpecializedTemplate();
8971 }
8972 }
8973 }
8974
8975private:
8976 bool isTargetTypeAFunction() const {
8977 return TargetFunctionType->isFunctionType();
8978 }
8979
8980 // [ToType] [Return]
8981
8982 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8983 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8984 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8985 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8986 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8987 }
8988
8989 // return true if any matching specializations were found
8990 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8991 const DeclAccessPair& CurAccessFunPair) {
8992 if (CXXMethodDecl *Method
8993 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8994 // Skip non-static function templates when converting to pointer, and
8995 // static when converting to member pointer.
8996 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8997 return false;
8998 }
8999 else if (TargetTypeIsNonStaticMemberFunction)
9000 return false;
9001
9002 // C++ [over.over]p2:
9003 // If the name is a function template, template argument deduction is
9004 // done (14.8.2.2), and if the argument deduction succeeds, the
9005 // resulting template argument list is used to generate a single
9006 // function template specialization, which is added to the set of
9007 // overloaded functions considered.
9008 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009009 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009010 if (Sema::TemplateDeductionResult Result
9011 = S.DeduceTemplateArguments(FunctionTemplate,
9012 &OvlExplicitTemplateArgs,
9013 TargetFunctionType, Specialization,
9014 Info)) {
9015 // FIXME: make a note of the failed deduction for diagnostics.
9016 (void)Result;
9017 return false;
9018 }
9019
9020 // Template argument deduction ensures that we have an exact match.
9021 // This function template specicalization works.
9022 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9023 assert(TargetFunctionType
9024 == Context.getCanonicalType(Specialization->getType()));
9025 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9026 return true;
9027 }
9028
9029 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9030 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009032 // Skip non-static functions when converting to pointer, and static
9033 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009034 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9035 return false;
9036 }
9037 else if (TargetTypeIsNonStaticMemberFunction)
9038 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009039
Chandler Carruthbd647292009-12-29 06:17:27 +00009040 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009041 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009042 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9043 if (S.CheckCUDATarget(Caller, FunDecl))
9044 return false;
9045
Douglas Gregor43c79c22009-12-09 00:47:37 +00009046 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009047 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9048 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009049 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9050 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009051 Matches.push_back(std::make_pair(CurAccessFunPair,
9052 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009053 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009054 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009055 }
Mike Stump1eb44332009-09-09 15:08:12 +00009056 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009057
9058 return false;
9059 }
9060
9061 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9062 bool Ret = false;
9063
9064 // If the overload expression doesn't have the form of a pointer to
9065 // member, don't try to convert it to a pointer-to-member type.
9066 if (IsInvalidFormOfPointerToMemberFunction())
9067 return false;
9068
9069 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9070 E = OvlExpr->decls_end();
9071 I != E; ++I) {
9072 // Look through any using declarations to find the underlying function.
9073 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9074
9075 // C++ [over.over]p3:
9076 // Non-member functions and static member functions match
9077 // targets of type "pointer-to-function" or "reference-to-function."
9078 // Nonstatic member functions match targets of
9079 // type "pointer-to-member-function."
9080 // Note that according to DR 247, the containing class does not matter.
9081 if (FunctionTemplateDecl *FunctionTemplate
9082 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9083 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9084 Ret = true;
9085 }
9086 // If we have explicit template arguments supplied, skip non-templates.
9087 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9088 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9089 Ret = true;
9090 }
9091 assert(Ret || Matches.empty());
9092 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009093 }
9094
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009095 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009096 // [...] and any given function template specialization F1 is
9097 // eliminated if the set contains a second function template
9098 // specialization whose function template is more specialized
9099 // than the function template of F1 according to the partial
9100 // ordering rules of 14.5.5.2.
9101
9102 // The algorithm specified above is quadratic. We instead use a
9103 // two-pass algorithm (similar to the one used to identify the
9104 // best viable function in an overload set) that identifies the
9105 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009106
9107 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9108 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9109 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009110
John McCallc373d482010-01-27 01:50:18 +00009111 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009112 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9113 TPOC_Other, 0, SourceExpr->getLocStart(),
9114 S.PDiag(),
9115 S.PDiag(diag::err_addr_ovl_ambiguous)
9116 << Matches[0].second->getDeclName(),
9117 S.PDiag(diag::note_ovl_candidate)
9118 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009119 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009120
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009121 if (Result != MatchesCopy.end()) {
9122 // Make it the first and only element
9123 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9124 Matches[0].second = cast<FunctionDecl>(*Result);
9125 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009126 }
9127 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009128
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009129 void EliminateAllTemplateMatches() {
9130 // [...] any function template specializations in the set are
9131 // eliminated if the set also contains a non-template function, [...]
9132 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9133 if (Matches[I].second->getPrimaryTemplate() == 0)
9134 ++I;
9135 else {
9136 Matches[I] = Matches[--N];
9137 Matches.set_size(N);
9138 }
9139 }
9140 }
9141
9142public:
9143 void ComplainNoMatchesFound() const {
9144 assert(Matches.empty());
9145 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9146 << OvlExpr->getName() << TargetFunctionType
9147 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009148 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009149 }
9150
9151 bool IsInvalidFormOfPointerToMemberFunction() const {
9152 return TargetTypeIsNonStaticMemberFunction &&
9153 !OvlExprInfo.HasFormOfMemberPointer;
9154 }
9155
9156 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9157 // TODO: Should we condition this on whether any functions might
9158 // have matched, or is it more appropriate to do that in callers?
9159 // TODO: a fixit wouldn't hurt.
9160 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9161 << TargetType << OvlExpr->getSourceRange();
9162 }
9163
9164 void ComplainOfInvalidConversion() const {
9165 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9166 << OvlExpr->getName() << TargetType;
9167 }
9168
9169 void ComplainMultipleMatchesFound() const {
9170 assert(Matches.size() > 1);
9171 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9172 << OvlExpr->getName()
9173 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009174 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009175 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009176
9177 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9178
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009179 int getNumMatches() const { return Matches.size(); }
9180
9181 FunctionDecl* getMatchingFunctionDecl() const {
9182 if (Matches.size() != 1) return 0;
9183 return Matches[0].second;
9184 }
9185
9186 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9187 if (Matches.size() != 1) return 0;
9188 return &Matches[0].first;
9189 }
9190};
9191
9192/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9193/// an overloaded function (C++ [over.over]), where @p From is an
9194/// expression with overloaded function type and @p ToType is the type
9195/// we're trying to resolve to. For example:
9196///
9197/// @code
9198/// int f(double);
9199/// int f(int);
9200///
9201/// int (*pfd)(double) = f; // selects f(double)
9202/// @endcode
9203///
9204/// This routine returns the resulting FunctionDecl if it could be
9205/// resolved, and NULL otherwise. When @p Complain is true, this
9206/// routine will emit diagnostics if there is an error.
9207FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009208Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9209 QualType TargetType,
9210 bool Complain,
9211 DeclAccessPair &FoundResult,
9212 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009213 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009214
9215 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9216 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009217 int NumMatches = Resolver.getNumMatches();
9218 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009219 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009220 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9221 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9222 else
9223 Resolver.ComplainNoMatchesFound();
9224 }
9225 else if (NumMatches > 1 && Complain)
9226 Resolver.ComplainMultipleMatchesFound();
9227 else if (NumMatches == 1) {
9228 Fn = Resolver.getMatchingFunctionDecl();
9229 assert(Fn);
9230 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009231 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009232 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009233 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009234 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009235
9236 if (pHadMultipleCandidates)
9237 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009238 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009239}
9240
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009241/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009242/// resolve that overloaded function expression down to a single function.
9243///
9244/// This routine can only resolve template-ids that refer to a single function
9245/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009246/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009247/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009248FunctionDecl *
9249Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9250 bool Complain,
9251 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009252 // C++ [over.over]p1:
9253 // [...] [Note: any redundant set of parentheses surrounding the
9254 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009255 // C++ [over.over]p1:
9256 // [...] The overloaded function name can be preceded by the &
9257 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009258
Douglas Gregor4b52e252009-12-21 23:17:24 +00009259 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009260 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009261 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009262
9263 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009264 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009265
Douglas Gregor4b52e252009-12-21 23:17:24 +00009266 // Look through all of the overloaded functions, searching for one
9267 // whose type matches exactly.
9268 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009269 for (UnresolvedSetIterator I = ovl->decls_begin(),
9270 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009271 // C++0x [temp.arg.explicit]p3:
9272 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009273 // where deduction is not done, if a template argument list is
9274 // specified and it, along with any default template arguments,
9275 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009276 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009277 FunctionTemplateDecl *FunctionTemplate
9278 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009279
Douglas Gregor4b52e252009-12-21 23:17:24 +00009280 // C++ [over.over]p2:
9281 // If the name is a function template, template argument deduction is
9282 // done (14.8.2.2), and if the argument deduction succeeds, the
9283 // resulting template argument list is used to generate a single
9284 // function template specialization, which is added to the set of
9285 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009286 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009287 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009288 if (TemplateDeductionResult Result
9289 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9290 Specialization, Info)) {
9291 // FIXME: make a note of the failed deduction for diagnostics.
9292 (void)Result;
9293 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009294 }
9295
John McCall864c0412011-04-26 20:42:42 +00009296 assert(Specialization && "no specialization and no error?");
9297
Douglas Gregor4b52e252009-12-21 23:17:24 +00009298 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009299 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009300 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009301 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9302 << ovl->getName();
9303 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009304 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009305 return 0;
John McCall864c0412011-04-26 20:42:42 +00009306 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009307
John McCall864c0412011-04-26 20:42:42 +00009308 Matched = Specialization;
9309 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009311
Douglas Gregor4b52e252009-12-21 23:17:24 +00009312 return Matched;
9313}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009314
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009315
9316
9317
John McCall6dbba4f2011-10-11 23:14:30 +00009318// Resolve and fix an overloaded expression that can be resolved
9319// because it identifies a single function template specialization.
9320//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009321// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009322//
9323// Return true if it was logically possible to so resolve the
9324// expression, regardless of whether or not it succeeded. Always
9325// returns true if 'complain' is set.
9326bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9327 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9328 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009329 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009330 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009331 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009332
John McCall6dbba4f2011-10-11 23:14:30 +00009333 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009334
John McCall864c0412011-04-26 20:42:42 +00009335 DeclAccessPair found;
9336 ExprResult SingleFunctionExpression;
9337 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9338 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009339 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009340 SrcExpr = ExprError();
9341 return true;
9342 }
John McCall864c0412011-04-26 20:42:42 +00009343
9344 // It is only correct to resolve to an instance method if we're
9345 // resolving a form that's permitted to be a pointer to member.
9346 // Otherwise we'll end up making a bound member expression, which
9347 // is illegal in all the contexts we resolve like this.
9348 if (!ovl.HasFormOfMemberPointer &&
9349 isa<CXXMethodDecl>(fn) &&
9350 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009351 if (!complain) return false;
9352
9353 Diag(ovl.Expression->getExprLoc(),
9354 diag::err_bound_member_function)
9355 << 0 << ovl.Expression->getSourceRange();
9356
9357 // TODO: I believe we only end up here if there's a mix of
9358 // static and non-static candidates (otherwise the expression
9359 // would have 'bound member' type, not 'overload' type).
9360 // Ideally we would note which candidate was chosen and why
9361 // the static candidates were rejected.
9362 SrcExpr = ExprError();
9363 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009364 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009365
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009366 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009367 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009368 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009369
9370 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009371 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009372 SingleFunctionExpression =
9373 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009374 if (SingleFunctionExpression.isInvalid()) {
9375 SrcExpr = ExprError();
9376 return true;
9377 }
9378 }
John McCall864c0412011-04-26 20:42:42 +00009379 }
9380
9381 if (!SingleFunctionExpression.isUsable()) {
9382 if (complain) {
9383 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9384 << ovl.Expression->getName()
9385 << DestTypeForComplaining
9386 << OpRangeForComplaining
9387 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009388 NoteAllOverloadCandidates(SrcExpr.get());
9389
9390 SrcExpr = ExprError();
9391 return true;
9392 }
9393
9394 return false;
John McCall864c0412011-04-26 20:42:42 +00009395 }
9396
John McCall6dbba4f2011-10-11 23:14:30 +00009397 SrcExpr = SingleFunctionExpression;
9398 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009399}
9400
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009401/// \brief Add a single candidate to the overload set.
9402static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009403 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009404 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009405 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009406 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009407 bool PartialOverloading,
9408 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009409 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009410 if (isa<UsingShadowDecl>(Callee))
9411 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9412
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009413 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009414 if (ExplicitTemplateArgs) {
9415 assert(!KnownValid && "Explicit template arguments?");
9416 return;
9417 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009418 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9419 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009420 return;
John McCallba135432009-11-21 08:51:07 +00009421 }
9422
9423 if (FunctionTemplateDecl *FuncTemplate
9424 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009425 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009426 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009427 return;
9428 }
9429
Richard Smith2ced0442011-06-26 22:19:54 +00009430 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009431}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009432
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009433/// \brief Add the overload candidates named by callee and/or found by argument
9434/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009435void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009436 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009437 OverloadCandidateSet &CandidateSet,
9438 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009439
9440#ifndef NDEBUG
9441 // Verify that ArgumentDependentLookup is consistent with the rules
9442 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009443 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009444 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9445 // and let Y be the lookup set produced by argument dependent
9446 // lookup (defined as follows). If X contains
9447 //
9448 // -- a declaration of a class member, or
9449 //
9450 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009451 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009452 //
9453 // -- a declaration that is neither a function or a function
9454 // template
9455 //
9456 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009457
John McCall3b4294e2009-12-16 12:17:52 +00009458 if (ULE->requiresADL()) {
9459 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9460 E = ULE->decls_end(); I != E; ++I) {
9461 assert(!(*I)->getDeclContext()->isRecord());
9462 assert(isa<UsingShadowDecl>(*I) ||
9463 !(*I)->getDeclContext()->isFunctionOrMethod());
9464 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009465 }
9466 }
9467#endif
9468
John McCall3b4294e2009-12-16 12:17:52 +00009469 // It would be nice to avoid this copy.
9470 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009471 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009472 if (ULE->hasExplicitTemplateArgs()) {
9473 ULE->copyTemplateArgumentsInto(TABuffer);
9474 ExplicitTemplateArgs = &TABuffer;
9475 }
9476
9477 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9478 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009479 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9480 CandidateSet, PartialOverloading,
9481 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009482
John McCall3b4294e2009-12-16 12:17:52 +00009483 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009484 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009485 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009486 Args, ExplicitTemplateArgs,
9487 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009488 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009489}
John McCall578b69b2009-12-16 08:11:27 +00009490
Richard Smithf50e88a2011-06-05 22:42:48 +00009491/// Attempt to recover from an ill-formed use of a non-dependent name in a
9492/// template, where the non-dependent name was declared after the template
9493/// was defined. This is common in code written for a compilers which do not
9494/// correctly implement two-stage name lookup.
9495///
9496/// Returns true if a viable candidate was found and a diagnostic was issued.
9497static bool
9498DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9499 const CXXScopeSpec &SS, LookupResult &R,
9500 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009501 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009502 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9503 return false;
9504
9505 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009506 if (DC->isTransparentContext())
9507 continue;
9508
Richard Smithf50e88a2011-06-05 22:42:48 +00009509 SemaRef.LookupQualifiedName(R, DC);
9510
9511 if (!R.empty()) {
9512 R.suppressDiagnostics();
9513
9514 if (isa<CXXRecordDecl>(DC)) {
9515 // Don't diagnose names we find in classes; we get much better
9516 // diagnostics for these from DiagnoseEmptyLookup.
9517 R.clear();
9518 return false;
9519 }
9520
9521 OverloadCandidateSet Candidates(FnLoc);
9522 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9523 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009524 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009525 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009526
9527 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009528 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009529 // No viable functions. Don't bother the user with notes for functions
9530 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009531 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009532 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009533 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009534
9535 // Find the namespaces where ADL would have looked, and suggest
9536 // declaring the function there instead.
9537 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9538 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009539 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009540 AssociatedNamespaces,
9541 AssociatedClasses);
9542 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009543 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009544 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009545 for (Sema::AssociatedNamespaceSet::iterator
9546 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009547 end = AssociatedNamespaces.end(); it != end; ++it) {
9548 if (!Std->Encloses(*it))
9549 SuggestedNamespaces.insert(*it);
9550 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009551 } else {
9552 // Lacking the 'std::' namespace, use all of the associated namespaces.
9553 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009554 }
9555
9556 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9557 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009558 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009559 SemaRef.Diag(Best->Function->getLocation(),
9560 diag::note_not_found_by_two_phase_lookup)
9561 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009562 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009563 SemaRef.Diag(Best->Function->getLocation(),
9564 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009565 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009566 } else {
9567 // FIXME: It would be useful to list the associated namespaces here,
9568 // but the diagnostics infrastructure doesn't provide a way to produce
9569 // a localized representation of a list of items.
9570 SemaRef.Diag(Best->Function->getLocation(),
9571 diag::note_not_found_by_two_phase_lookup)
9572 << R.getLookupName() << 2;
9573 }
9574
9575 // Try to recover by calling this function.
9576 return true;
9577 }
9578
9579 R.clear();
9580 }
9581
9582 return false;
9583}
9584
9585/// Attempt to recover from ill-formed use of a non-dependent operator in a
9586/// template, where the non-dependent operator was declared after the template
9587/// was defined.
9588///
9589/// Returns true if a viable candidate was found and a diagnostic was issued.
9590static bool
9591DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9592 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009593 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009594 DeclarationName OpName =
9595 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9596 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9597 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009598 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009599}
9600
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009601namespace {
9602// Callback to limit the allowed keywords and to only accept typo corrections
9603// that are keywords or whose decls refer to functions (or template functions)
9604// that accept the given number of arguments.
9605class RecoveryCallCCC : public CorrectionCandidateCallback {
9606 public:
9607 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9608 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009609 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009610 WantRemainingKeywords = false;
9611 }
9612
9613 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9614 if (!candidate.getCorrectionDecl())
9615 return candidate.isKeyword();
9616
9617 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9618 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9619 FunctionDecl *FD = 0;
9620 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9621 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9622 FD = FTD->getTemplatedDecl();
9623 if (!HasExplicitTemplateArgs && !FD) {
9624 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9625 // If the Decl is neither a function nor a template function,
9626 // determine if it is a pointer or reference to a function. If so,
9627 // check against the number of arguments expected for the pointee.
9628 QualType ValType = cast<ValueDecl>(ND)->getType();
9629 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9630 ValType = ValType->getPointeeType();
9631 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9632 if (FPT->getNumArgs() == NumArgs)
9633 return true;
9634 }
9635 }
9636 if (FD && FD->getNumParams() >= NumArgs &&
9637 FD->getMinRequiredArguments() <= NumArgs)
9638 return true;
9639 }
9640 return false;
9641 }
9642
9643 private:
9644 unsigned NumArgs;
9645 bool HasExplicitTemplateArgs;
9646};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009647
9648// Callback that effectively disabled typo correction
9649class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9650 public:
9651 NoTypoCorrectionCCC() {
9652 WantTypeSpecifiers = false;
9653 WantExpressionKeywords = false;
9654 WantCXXNamedCasts = false;
9655 WantRemainingKeywords = false;
9656 }
9657
9658 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9659 return false;
9660 }
9661};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009662
9663class BuildRecoveryCallExprRAII {
9664 Sema &SemaRef;
9665public:
9666 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9667 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9668 SemaRef.IsBuildingRecoveryCallExpr = true;
9669 }
9670
9671 ~BuildRecoveryCallExprRAII() {
9672 SemaRef.IsBuildingRecoveryCallExpr = false;
9673 }
9674};
9675
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009676}
9677
John McCall578b69b2009-12-16 08:11:27 +00009678/// Attempts to recover from a call where no functions were found.
9679///
9680/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009681static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009682BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009683 UnresolvedLookupExpr *ULE,
9684 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009685 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009686 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009687 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009688 // Do not try to recover if it is already building a recovery call.
9689 // This stops infinite loops for template instantiations like
9690 //
9691 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9692 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9693 //
9694 if (SemaRef.IsBuildingRecoveryCallExpr)
9695 return ExprError();
9696 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009697
9698 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009699 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009700 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009701
John McCall3b4294e2009-12-16 12:17:52 +00009702 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009703 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009704 if (ULE->hasExplicitTemplateArgs()) {
9705 ULE->copyTemplateArgumentsInto(TABuffer);
9706 ExplicitTemplateArgs = &TABuffer;
9707 }
9708
John McCall578b69b2009-12-16 08:11:27 +00009709 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9710 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009711 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009712 NoTypoCorrectionCCC RejectAll;
9713 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9714 (CorrectionCandidateCallback*)&Validator :
9715 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009716 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009717 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009718 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009719 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009720 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009721 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009722
John McCall3b4294e2009-12-16 12:17:52 +00009723 assert(!R.empty() && "lookup results empty despite recovery");
9724
9725 // Build an implicit member call if appropriate. Just drop the
9726 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009727 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009728 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009729 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9730 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009731 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009732 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009733 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009734 else
9735 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9736
9737 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009738 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009739
9740 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009741 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009742 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009743 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009744 MultiExprArg(Args.data(), Args.size()),
9745 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009746}
Douglas Gregord7a95972010-06-08 17:35:15 +00009747
Sam Panzere1715b62012-08-21 00:52:01 +00009748/// \brief Constructs and populates an OverloadedCandidateSet from
9749/// the given function.
9750/// \returns true when an the ExprResult output parameter has been set.
9751bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9752 UnresolvedLookupExpr *ULE,
9753 Expr **Args, unsigned NumArgs,
9754 SourceLocation RParenLoc,
9755 OverloadCandidateSet *CandidateSet,
9756 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009757#ifndef NDEBUG
9758 if (ULE->requiresADL()) {
9759 // To do ADL, we must have found an unqualified name.
9760 assert(!ULE->getQualifier() && "qualified name with ADL");
9761
9762 // We don't perform ADL for implicit declarations of builtins.
9763 // Verify that this was correctly set up.
9764 FunctionDecl *F;
9765 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9766 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9767 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009768 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009769
John McCall3b4294e2009-12-16 12:17:52 +00009770 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009771 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009772 } else
9773 assert(!ULE->isStdAssociatedNamespace() &&
9774 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009775#endif
9776
John McCall5acb0c92011-10-17 18:40:02 +00009777 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009778 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9779 *Result = ExprError();
9780 return true;
9781 }
Douglas Gregor17330012009-02-04 15:01:18 +00009782
John McCall3b4294e2009-12-16 12:17:52 +00009783 // Add the functions denoted by the callee to the set of candidate
9784 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009785 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009786 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009787
9788 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009789 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9790 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009791 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009792 // In Microsoft mode, if we are inside a template class member function then
9793 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009794 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009795 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009796 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009797 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009798 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9799 llvm::makeArrayRef(Args, NumArgs),
9800 Context.DependentTy, VK_RValue,
9801 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009802 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009803 *Result = Owned(CE);
9804 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009805 }
Sam Panzere1715b62012-08-21 00:52:01 +00009806 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009807 }
John McCall578b69b2009-12-16 08:11:27 +00009808
John McCall5acb0c92011-10-17 18:40:02 +00009809 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009810 return false;
9811}
John McCall5acb0c92011-10-17 18:40:02 +00009812
Sam Panzere1715b62012-08-21 00:52:01 +00009813/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9814/// the completed call expression. If overload resolution fails, emits
9815/// diagnostics and returns ExprError()
9816static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9817 UnresolvedLookupExpr *ULE,
9818 SourceLocation LParenLoc,
9819 Expr **Args, unsigned NumArgs,
9820 SourceLocation RParenLoc,
9821 Expr *ExecConfig,
9822 OverloadCandidateSet *CandidateSet,
9823 OverloadCandidateSet::iterator *Best,
9824 OverloadingResult OverloadResult,
9825 bool AllowTypoCorrection) {
9826 if (CandidateSet->empty())
9827 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9828 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9829 RParenLoc, /*EmptyLookup=*/true,
9830 AllowTypoCorrection);
9831
9832 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009833 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009834 FunctionDecl *FDecl = (*Best)->Function;
9835 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9836 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9837 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9838 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9839 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9840 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009841 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009842
Richard Smithf50e88a2011-06-05 22:42:48 +00009843 case OR_No_Viable_Function: {
9844 // Try to recover by looking for viable functions which the user might
9845 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009846 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009847 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9848 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009849 /*EmptyLookup=*/false,
9850 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009851 if (!Recovery.isInvalid())
9852 return Recovery;
9853
Sam Panzere1715b62012-08-21 00:52:01 +00009854 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009855 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009856 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009857 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9858 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009859 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009860 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009861
9862 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009863 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009864 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009865 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9866 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009867 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009868
Sam Panzere1715b62012-08-21 00:52:01 +00009869 case OR_Deleted: {
9870 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9871 << (*Best)->Function->isDeleted()
9872 << ULE->getName()
9873 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9874 << Fn->getSourceRange();
9875 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9876 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009877
Sam Panzere1715b62012-08-21 00:52:01 +00009878 // We emitted an error for the unvailable/deleted function call but keep
9879 // the call in the AST.
9880 FunctionDecl *FDecl = (*Best)->Function;
9881 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9882 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9883 RParenLoc, ExecConfig);
9884 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009885 }
9886
Douglas Gregorff331c12010-07-25 18:17:45 +00009887 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009888 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009889}
9890
Sam Panzere1715b62012-08-21 00:52:01 +00009891/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9892/// (which eventually refers to the declaration Func) and the call
9893/// arguments Args/NumArgs, attempt to resolve the function call down
9894/// to a specific function. If overload resolution succeeds, returns
9895/// the call expression produced by overload resolution.
9896/// Otherwise, emits diagnostics and returns ExprError.
9897ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9898 UnresolvedLookupExpr *ULE,
9899 SourceLocation LParenLoc,
9900 Expr **Args, unsigned NumArgs,
9901 SourceLocation RParenLoc,
9902 Expr *ExecConfig,
9903 bool AllowTypoCorrection) {
9904 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9905 ExprResult result;
9906
9907 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9908 &CandidateSet, &result))
9909 return result;
9910
9911 OverloadCandidateSet::iterator Best;
9912 OverloadingResult OverloadResult =
9913 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9914
9915 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9916 RParenLoc, ExecConfig, &CandidateSet,
9917 &Best, OverloadResult,
9918 AllowTypoCorrection);
9919}
9920
John McCall6e266892010-01-26 03:27:55 +00009921static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009922 return Functions.size() > 1 ||
9923 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9924}
9925
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009926/// \brief Create a unary operation that may resolve to an overloaded
9927/// operator.
9928///
9929/// \param OpLoc The location of the operator itself (e.g., '*').
9930///
9931/// \param OpcIn The UnaryOperator::Opcode that describes this
9932/// operator.
9933///
James Dennett40ae6662012-06-22 08:52:37 +00009934/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009935/// considered by overload resolution. The caller needs to build this
9936/// set based on the context using, e.g.,
9937/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9938/// set should not contain any member functions; those will be added
9939/// by CreateOverloadedUnaryOp().
9940///
James Dennett8da16872012-06-22 10:32:46 +00009941/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009942ExprResult
John McCall6e266892010-01-26 03:27:55 +00009943Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9944 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009945 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009946 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009947
9948 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9949 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9950 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009951 // TODO: provide better source location info.
9952 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009953
John McCall5acb0c92011-10-17 18:40:02 +00009954 if (checkPlaceholderForOverload(*this, Input))
9955 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009956
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009957 Expr *Args[2] = { Input, 0 };
9958 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009959
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009960 // For post-increment and post-decrement, add the implicit '0' as
9961 // the second argument, so that we know this is a post-increment or
9962 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009963 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009964 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009965 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9966 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009967 NumArgs = 2;
9968 }
9969
9970 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009971 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009972 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009973 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009974 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009975 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009976 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009977
John McCallc373d482010-01-27 01:50:18 +00009978 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009979 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009980 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009981 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009982 /*ADL*/ true, IsOverloaded(Fns),
9983 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009984 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009985 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009986 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009987 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +00009988 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009989 }
9990
9991 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009992 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009993
9994 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009995 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9996 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009997
9998 // Add operator candidates that are member functions.
9999 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10000
John McCall6e266892010-01-26 03:27:55 +000010001 // Add candidates from ADL.
10002 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010003 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010004 /*ExplicitTemplateArgs*/ 0,
10005 CandidateSet);
10006
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010007 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010008 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010009
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010010 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10011
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010012 // Perform overload resolution.
10013 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010014 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010015 case OR_Success: {
10016 // We found a built-in operator or an overloaded operator.
10017 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010018
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010019 if (FnDecl) {
10020 // We matched an overloaded operator. Build a call to that
10021 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010022
Eli Friedman5f2987c2012-02-02 03:46:19 +000010023 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010024
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010025 // Convert the arguments.
10026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010027 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010028
John Wiegley429bb272011-04-08 18:41:53 +000010029 ExprResult InputRes =
10030 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10031 Best->FoundDecl, Method);
10032 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010033 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010034 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010035 } else {
10036 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010037 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010038 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010039 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010040 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010041 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010042 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010043 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010044 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010045 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010046 }
10047
John McCallb697e082010-05-06 18:15:07 +000010048 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10049
John McCallf89e55a2010-11-18 06:31:45 +000010050 // Determine the result type.
10051 QualType ResultTy = FnDecl->getResultType();
10052 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10053 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010054
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010055 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010056 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010057 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010058 if (FnExpr.isInvalid())
10059 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010060
Eli Friedman4c3b8962009-11-18 03:58:17 +000010061 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010062 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010063 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010064 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010065 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010066
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010067 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010068 FnDecl))
10069 return ExprError();
10070
John McCall9ae2f072010-08-23 23:25:46 +000010071 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010072 } else {
10073 // We matched a built-in operator. Convert the arguments, then
10074 // break out so that we will build the appropriate built-in
10075 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010076 ExprResult InputRes =
10077 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10078 Best->Conversions[0], AA_Passing);
10079 if (InputRes.isInvalid())
10080 return ExprError();
10081 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010082 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010083 }
John Wiegley429bb272011-04-08 18:41:53 +000010084 }
10085
10086 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010087 // This is an erroneous use of an operator which can be overloaded by
10088 // a non-member function. Check for non-member operators which were
10089 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010090 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10091 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010092 // FIXME: Recover by calling the found function.
10093 return ExprError();
10094
John Wiegley429bb272011-04-08 18:41:53 +000010095 // No viable function; fall through to handling this as a
10096 // built-in operator, which will produce an error message for us.
10097 break;
10098
10099 case OR_Ambiguous:
10100 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10101 << UnaryOperator::getOpcodeStr(Opc)
10102 << Input->getType()
10103 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010104 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10105 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010106 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10107 return ExprError();
10108
10109 case OR_Deleted:
10110 Diag(OpLoc, diag::err_ovl_deleted_oper)
10111 << Best->Function->isDeleted()
10112 << UnaryOperator::getOpcodeStr(Opc)
10113 << getDeletedOrUnavailableSuffix(Best->Function)
10114 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010115 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10116 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010117 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010118 return ExprError();
10119 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010120
10121 // Either we found no viable overloaded operator or we matched a
10122 // built-in operator. In either case, fall through to trying to
10123 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010124 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010125}
10126
Douglas Gregor063daf62009-03-13 18:40:31 +000010127/// \brief Create a binary operation that may resolve to an overloaded
10128/// operator.
10129///
10130/// \param OpLoc The location of the operator itself (e.g., '+').
10131///
10132/// \param OpcIn The BinaryOperator::Opcode that describes this
10133/// operator.
10134///
James Dennett40ae6662012-06-22 08:52:37 +000010135/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010136/// considered by overload resolution. The caller needs to build this
10137/// set based on the context using, e.g.,
10138/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10139/// set should not contain any member functions; those will be added
10140/// by CreateOverloadedBinOp().
10141///
10142/// \param LHS Left-hand argument.
10143/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010144ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010145Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010146 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010147 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010148 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010149 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010150 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010151
10152 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10153 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10154 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10155
10156 // If either side is type-dependent, create an appropriate dependent
10157 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010158 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010159 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010160 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010161 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010162 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010163 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010164 Context.DependentTy,
10165 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010166 OpLoc,
10167 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010168
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010169 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10170 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010171 VK_LValue,
10172 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010173 Context.DependentTy,
10174 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010175 OpLoc,
10176 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010177 }
John McCall6e266892010-01-26 03:27:55 +000010178
10179 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010180 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010181 // TODO: provide better source location info in DNLoc component.
10182 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010183 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010184 = UnresolvedLookupExpr::Create(Context, NamingClass,
10185 NestedNameSpecifierLoc(), OpNameInfo,
10186 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010187 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010188 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10189 Context.DependentTy, VK_RValue,
10190 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010191 }
10192
John McCall5acb0c92011-10-17 18:40:02 +000010193 // Always do placeholder-like conversions on the RHS.
10194 if (checkPlaceholderForOverload(*this, Args[1]))
10195 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010196
John McCall3c3b7f92011-10-25 17:37:35 +000010197 // Do placeholder-like conversion on the LHS; note that we should
10198 // not get here with a PseudoObject LHS.
10199 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010200 if (checkPlaceholderForOverload(*this, Args[0]))
10201 return ExprError();
10202
Sebastian Redl275c2b42009-11-18 23:10:33 +000010203 // If this is the assignment operator, we only perform overload resolution
10204 // if the left-hand side is a class or enumeration type. This is actually
10205 // a hack. The standard requires that we do overload resolution between the
10206 // various built-in candidates, but as DR507 points out, this can lead to
10207 // problems. So we do it this way, which pretty much follows what GCC does.
10208 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010209 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010210 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010211
John McCall0e800c92010-12-04 08:14:53 +000010212 // If this is the .* operator, which is not overloadable, just
10213 // create a built-in binary operator.
10214 if (Opc == BO_PtrMemD)
10215 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10216
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010217 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010218 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010219
10220 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010221 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010222
10223 // Add operator candidates that are member functions.
10224 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10225
John McCall6e266892010-01-26 03:27:55 +000010226 // Add candidates from ADL.
10227 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010228 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010229 /*ExplicitTemplateArgs*/ 0,
10230 CandidateSet);
10231
Douglas Gregor063daf62009-03-13 18:40:31 +000010232 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010233 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010234
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010235 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10236
Douglas Gregor063daf62009-03-13 18:40:31 +000010237 // Perform overload resolution.
10238 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010239 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010240 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010241 // We found a built-in operator or an overloaded operator.
10242 FunctionDecl *FnDecl = Best->Function;
10243
10244 if (FnDecl) {
10245 // We matched an overloaded operator. Build a call to that
10246 // operator.
10247
Eli Friedman5f2987c2012-02-02 03:46:19 +000010248 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010249
Douglas Gregor063daf62009-03-13 18:40:31 +000010250 // Convert the arguments.
10251 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010252 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010253 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010254
Chandler Carruth6df868e2010-12-12 08:17:55 +000010255 ExprResult Arg1 =
10256 PerformCopyInitialization(
10257 InitializedEntity::InitializeParameter(Context,
10258 FnDecl->getParamDecl(0)),
10259 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010260 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010261 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010262
John Wiegley429bb272011-04-08 18:41:53 +000010263 ExprResult Arg0 =
10264 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10265 Best->FoundDecl, Method);
10266 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010267 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010268 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010269 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010270 } else {
10271 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010272 ExprResult Arg0 = PerformCopyInitialization(
10273 InitializedEntity::InitializeParameter(Context,
10274 FnDecl->getParamDecl(0)),
10275 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010276 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010277 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010278
Chandler Carruth6df868e2010-12-12 08:17:55 +000010279 ExprResult Arg1 =
10280 PerformCopyInitialization(
10281 InitializedEntity::InitializeParameter(Context,
10282 FnDecl->getParamDecl(1)),
10283 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010284 if (Arg1.isInvalid())
10285 return ExprError();
10286 Args[0] = LHS = Arg0.takeAs<Expr>();
10287 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010288 }
10289
John McCallb697e082010-05-06 18:15:07 +000010290 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10291
John McCallf89e55a2010-11-18 06:31:45 +000010292 // Determine the result type.
10293 QualType ResultTy = FnDecl->getResultType();
10294 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10295 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010296
10297 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010298 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10299 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010300 if (FnExpr.isInvalid())
10301 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010302
John McCall9ae2f072010-08-23 23:25:46 +000010303 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010304 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010305 Args, ResultTy, VK, OpLoc,
10306 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010307
10308 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010309 FnDecl))
10310 return ExprError();
10311
John McCall9ae2f072010-08-23 23:25:46 +000010312 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010313 } else {
10314 // We matched a built-in operator. Convert the arguments, then
10315 // break out so that we will build the appropriate built-in
10316 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010317 ExprResult ArgsRes0 =
10318 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10319 Best->Conversions[0], AA_Passing);
10320 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010321 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010322 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010323
John Wiegley429bb272011-04-08 18:41:53 +000010324 ExprResult ArgsRes1 =
10325 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10326 Best->Conversions[1], AA_Passing);
10327 if (ArgsRes1.isInvalid())
10328 return ExprError();
10329 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010330 break;
10331 }
10332 }
10333
Douglas Gregor33074752009-09-30 21:46:01 +000010334 case OR_No_Viable_Function: {
10335 // C++ [over.match.oper]p9:
10336 // If the operator is the operator , [...] and there are no
10337 // viable functions, then the operator is assumed to be the
10338 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010339 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010340 break;
10341
Chandler Carruth6df868e2010-12-12 08:17:55 +000010342 // For class as left operand for assignment or compound assigment
10343 // operator do not fall through to handling in built-in, but report that
10344 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010345 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010346 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010347 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010348 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10349 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010350 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010351 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010352 // This is an erroneous use of an operator which can be overloaded by
10353 // a non-member function. Check for non-member operators which were
10354 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010355 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010356 // FIXME: Recover by calling the found function.
10357 return ExprError();
10358
Douglas Gregor33074752009-09-30 21:46:01 +000010359 // No viable function; try to create a built-in operation, which will
10360 // produce an error. Then, show the non-viable candidates.
10361 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010363 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010364 "C++ binary operator overloading is missing candidates!");
10365 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010366 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010367 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010368 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010369 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010370
10371 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010372 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010373 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010374 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010375 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010376 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010377 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010378 return ExprError();
10379
10380 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010381 if (isImplicitlyDeleted(Best->Function)) {
10382 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10383 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10384 << getSpecialMember(Method)
10385 << BinaryOperator::getOpcodeStr(Opc)
10386 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010387
10388 if (getSpecialMember(Method) != CXXInvalid) {
10389 // The user probably meant to call this special member. Just
10390 // explain why it's deleted.
10391 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010392 return ExprError();
10393 }
10394 } else {
10395 Diag(OpLoc, diag::err_ovl_deleted_oper)
10396 << Best->Function->isDeleted()
10397 << BinaryOperator::getOpcodeStr(Opc)
10398 << getDeletedOrUnavailableSuffix(Best->Function)
10399 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10400 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010401 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010402 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010403 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010404 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010405
Douglas Gregor33074752009-09-30 21:46:01 +000010406 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010407 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010408}
10409
John McCall60d7b3a2010-08-24 06:29:42 +000010410ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010411Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10412 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010413 Expr *Base, Expr *Idx) {
10414 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010415 DeclarationName OpName =
10416 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10417
10418 // If either side is type-dependent, create an appropriate dependent
10419 // expression.
10420 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10421
John McCallc373d482010-01-27 01:50:18 +000010422 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010423 // CHECKME: no 'operator' keyword?
10424 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10425 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010426 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010427 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010428 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010429 /*ADL*/ true, /*Overloaded*/ false,
10430 UnresolvedSetIterator(),
10431 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010432 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010433
Sebastian Redlf322ed62009-10-29 20:17:01 +000010434 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010435 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010436 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010437 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010438 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010439 }
10440
John McCall5acb0c92011-10-17 18:40:02 +000010441 // Handle placeholders on both operands.
10442 if (checkPlaceholderForOverload(*this, Args[0]))
10443 return ExprError();
10444 if (checkPlaceholderForOverload(*this, Args[1]))
10445 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010446
Sebastian Redlf322ed62009-10-29 20:17:01 +000010447 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010448 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010449
10450 // Subscript can only be overloaded as a member function.
10451
10452 // Add operator candidates that are member functions.
10453 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10454
10455 // Add builtin operator candidates.
10456 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10457
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010458 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10459
Sebastian Redlf322ed62009-10-29 20:17:01 +000010460 // Perform overload resolution.
10461 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010462 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010463 case OR_Success: {
10464 // We found a built-in operator or an overloaded operator.
10465 FunctionDecl *FnDecl = Best->Function;
10466
10467 if (FnDecl) {
10468 // We matched an overloaded operator. Build a call to that
10469 // operator.
10470
Eli Friedman5f2987c2012-02-02 03:46:19 +000010471 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010472
John McCall9aa472c2010-03-19 07:35:19 +000010473 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010474 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010475
Sebastian Redlf322ed62009-10-29 20:17:01 +000010476 // Convert the arguments.
10477 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010478 ExprResult Arg0 =
10479 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10480 Best->FoundDecl, Method);
10481 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010482 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010483 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010484
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010485 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010486 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010487 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010488 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010489 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010490 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010491 Owned(Args[1]));
10492 if (InputInit.isInvalid())
10493 return ExprError();
10494
10495 Args[1] = InputInit.takeAs<Expr>();
10496
Sebastian Redlf322ed62009-10-29 20:17:01 +000010497 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010498 QualType ResultTy = FnDecl->getResultType();
10499 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10500 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010501
10502 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010503 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10504 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010505 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10506 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010507 OpLocInfo.getLoc(),
10508 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010509 if (FnExpr.isInvalid())
10510 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010511
John McCall9ae2f072010-08-23 23:25:46 +000010512 CXXOperatorCallExpr *TheCall =
10513 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010514 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010515 ResultTy, VK, RLoc,
10516 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010517
John McCall9ae2f072010-08-23 23:25:46 +000010518 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010519 FnDecl))
10520 return ExprError();
10521
John McCall9ae2f072010-08-23 23:25:46 +000010522 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010523 } else {
10524 // We matched a built-in operator. Convert the arguments, then
10525 // break out so that we will build the appropriate built-in
10526 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010527 ExprResult ArgsRes0 =
10528 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10529 Best->Conversions[0], AA_Passing);
10530 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010531 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010532 Args[0] = ArgsRes0.take();
10533
10534 ExprResult ArgsRes1 =
10535 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10536 Best->Conversions[1], AA_Passing);
10537 if (ArgsRes1.isInvalid())
10538 return ExprError();
10539 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010540
10541 break;
10542 }
10543 }
10544
10545 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010546 if (CandidateSet.empty())
10547 Diag(LLoc, diag::err_ovl_no_oper)
10548 << Args[0]->getType() << /*subscript*/ 0
10549 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10550 else
10551 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10552 << Args[0]->getType()
10553 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010554 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010555 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010556 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010557 }
10558
10559 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010560 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010561 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010562 << Args[0]->getType() << Args[1]->getType()
10563 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010564 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010565 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010566 return ExprError();
10567
10568 case OR_Deleted:
10569 Diag(LLoc, diag::err_ovl_deleted_oper)
10570 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010571 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010572 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010573 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010574 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010575 return ExprError();
10576 }
10577
10578 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010579 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010580}
10581
Douglas Gregor88a35142008-12-22 05:46:06 +000010582/// BuildCallToMemberFunction - Build a call to a member
10583/// function. MemExpr is the expression that refers to the member
10584/// function (and includes the object parameter), Args/NumArgs are the
10585/// arguments to the function call (not including the object
10586/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010587/// expression refers to a non-static member function or an overloaded
10588/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010589ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010590Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10591 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010592 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010593 assert(MemExprE->getType() == Context.BoundMemberTy ||
10594 MemExprE->getType() == Context.OverloadTy);
10595
Douglas Gregor88a35142008-12-22 05:46:06 +000010596 // Dig out the member expression. This holds both the object
10597 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010598 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010599
John McCall864c0412011-04-26 20:42:42 +000010600 // Determine whether this is a call to a pointer-to-member function.
10601 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10602 assert(op->getType() == Context.BoundMemberTy);
10603 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10604
10605 QualType fnType =
10606 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10607
10608 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10609 QualType resultType = proto->getCallResultType(Context);
10610 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10611
10612 // Check that the object type isn't more qualified than the
10613 // member function we're calling.
10614 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10615
10616 QualType objectType = op->getLHS()->getType();
10617 if (op->getOpcode() == BO_PtrMemI)
10618 objectType = objectType->castAs<PointerType>()->getPointeeType();
10619 Qualifiers objectQuals = objectType.getQualifiers();
10620
10621 Qualifiers difference = objectQuals - funcQuals;
10622 difference.removeObjCGCAttr();
10623 difference.removeAddressSpace();
10624 if (difference) {
10625 std::string qualsString = difference.getAsString();
10626 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10627 << fnType.getUnqualifiedType()
10628 << qualsString
10629 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10630 }
10631
10632 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010633 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10634 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010635 resultType, valueKind, RParenLoc);
10636
10637 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010638 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010639 call, 0))
10640 return ExprError();
10641
10642 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10643 return ExprError();
10644
10645 return MaybeBindToTemporary(call);
10646 }
10647
John McCall5acb0c92011-10-17 18:40:02 +000010648 UnbridgedCastsSet UnbridgedCasts;
10649 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10650 return ExprError();
10651
John McCall129e2df2009-11-30 22:42:35 +000010652 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010653 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010654 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010655 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010656 if (isa<MemberExpr>(NakedMemExpr)) {
10657 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010658 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010659 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010660 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010661 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010662 } else {
10663 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010664 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010665
John McCall701c89e2009-12-03 04:06:58 +000010666 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010667 Expr::Classification ObjectClassification
10668 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10669 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010670
Douglas Gregor88a35142008-12-22 05:46:06 +000010671 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010672 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010673
John McCallaa81e162009-12-01 22:10:20 +000010674 // FIXME: avoid copy.
10675 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10676 if (UnresExpr->hasExplicitTemplateArgs()) {
10677 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10678 TemplateArgs = &TemplateArgsBuffer;
10679 }
10680
John McCall129e2df2009-11-30 22:42:35 +000010681 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10682 E = UnresExpr->decls_end(); I != E; ++I) {
10683
John McCall701c89e2009-12-03 04:06:58 +000010684 NamedDecl *Func = *I;
10685 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10686 if (isa<UsingShadowDecl>(Func))
10687 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10688
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010689
Francois Pichetdbee3412011-01-18 05:04:39 +000010690 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010691 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010692 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10693 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010694 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010695 // If explicit template arguments were provided, we can't call a
10696 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010697 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010698 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010699
John McCall9aa472c2010-03-19 07:35:19 +000010700 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010701 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010702 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010703 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010704 } else {
John McCall129e2df2009-11-30 22:42:35 +000010705 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010706 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010707 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010708 llvm::makeArrayRef(Args, NumArgs),
10709 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010710 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010711 }
Douglas Gregordec06662009-08-21 18:42:58 +000010712 }
Mike Stump1eb44332009-09-09 15:08:12 +000010713
John McCall129e2df2009-11-30 22:42:35 +000010714 DeclarationName DeclName = UnresExpr->getMemberName();
10715
John McCall5acb0c92011-10-17 18:40:02 +000010716 UnbridgedCasts.restore();
10717
Douglas Gregor88a35142008-12-22 05:46:06 +000010718 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010719 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010720 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010721 case OR_Success:
10722 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010723 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010724 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010725 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010726 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010727 break;
10728
10729 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010730 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010731 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010732 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010733 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10734 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010735 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010736 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010737
10738 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010739 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010740 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010741 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10742 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010743 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010744 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010745
10746 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010747 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010748 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010749 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010750 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010751 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010752 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10753 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010754 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010755 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010756 }
10757
John McCall6bb80172010-03-30 21:47:33 +000010758 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010759
John McCallaa81e162009-12-01 22:10:20 +000010760 // If overload resolution picked a static member, build a
10761 // non-member call based on that function.
10762 if (Method->isStatic()) {
10763 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10764 Args, NumArgs, RParenLoc);
10765 }
10766
John McCall129e2df2009-11-30 22:42:35 +000010767 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010768 }
10769
John McCallf89e55a2010-11-18 06:31:45 +000010770 QualType ResultType = Method->getResultType();
10771 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10772 ResultType = ResultType.getNonLValueExprType(Context);
10773
Douglas Gregor88a35142008-12-22 05:46:06 +000010774 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010775 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010776 new (Context) CXXMemberCallExpr(Context, MemExprE,
10777 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010778 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010779
Anders Carlssoneed3e692009-10-10 00:06:20 +000010780 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010781 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010782 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010783 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010784
Douglas Gregor88a35142008-12-22 05:46:06 +000010785 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010786 // We only need to do this if there was actually an overload; otherwise
10787 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010788 if (!Method->isStatic()) {
10789 ExprResult ObjectArg =
10790 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10791 FoundDecl, Method);
10792 if (ObjectArg.isInvalid())
10793 return ExprError();
10794 MemExpr->setBase(ObjectArg.take());
10795 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010796
10797 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010798 const FunctionProtoType *Proto =
10799 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010800 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010801 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010802 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010803
Eli Friedmane61eb042012-02-18 04:48:30 +000010804 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10805
Richard Smith831421f2012-06-25 20:30:08 +000010806 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010807 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010808
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010809 if ((isa<CXXConstructorDecl>(CurContext) ||
10810 isa<CXXDestructorDecl>(CurContext)) &&
10811 TheCall->getMethodDecl()->isPure()) {
10812 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10813
Chandler Carruthae198062011-06-27 08:31:58 +000010814 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010815 Diag(MemExpr->getLocStart(),
10816 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10817 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10818 << MD->getParent()->getDeclName();
10819
10820 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010821 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010822 }
John McCall9ae2f072010-08-23 23:25:46 +000010823 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010824}
10825
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010826/// BuildCallToObjectOfClassType - Build a call to an object of class
10827/// type (C++ [over.call.object]), which can end up invoking an
10828/// overloaded function call operator (@c operator()) or performing a
10829/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010830ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010831Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010832 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010833 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010834 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010835 if (checkPlaceholderForOverload(*this, Obj))
10836 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010837 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010838
10839 UnbridgedCastsSet UnbridgedCasts;
10840 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10841 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010842
John Wiegley429bb272011-04-08 18:41:53 +000010843 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10844 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010845
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010846 // C++ [over.call.object]p1:
10847 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010848 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010849 // candidate functions includes at least the function call
10850 // operators of T. The function call operators of T are obtained by
10851 // ordinary lookup of the name operator() in the context of
10852 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010853 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010854 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010855
John Wiegley429bb272011-04-08 18:41:53 +000010856 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010857 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010858 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010859
John McCalla24dc2e2009-11-17 02:14:36 +000010860 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10861 LookupQualifiedName(R, Record->getDecl());
10862 R.suppressDiagnostics();
10863
Douglas Gregor593564b2009-11-15 07:48:03 +000010864 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010865 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010866 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10867 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010868 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010869 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010870
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010871 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010872 // In addition, for each (non-explicit in C++0x) conversion function
10873 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010874 //
10875 // operator conversion-type-id () cv-qualifier;
10876 //
10877 // where cv-qualifier is the same cv-qualification as, or a
10878 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010879 // denotes the type "pointer to function of (P1,...,Pn) returning
10880 // R", or the type "reference to pointer to function of
10881 // (P1,...,Pn) returning R", or the type "reference to function
10882 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010883 // is also considered as a candidate function. Similarly,
10884 // surrogate call functions are added to the set of candidate
10885 // functions for each conversion function declared in an
10886 // accessible base class provided the function is not hidden
10887 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010888 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010889 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010890 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010891 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010892 NamedDecl *D = *I;
10893 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10894 if (isa<UsingShadowDecl>(D))
10895 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010896
Douglas Gregor4a27d702009-10-21 06:18:39 +000010897 // Skip over templated conversion functions; they aren't
10898 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010899 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010900 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010901
John McCall701c89e2009-12-03 04:06:58 +000010902 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010903 if (!Conv->isExplicit()) {
10904 // Strip the reference type (if any) and then the pointer type (if
10905 // any) to get down to what might be a function type.
10906 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10907 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10908 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010909
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010910 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10911 {
10912 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010913 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10914 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010915 }
10916 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010917 }
Mike Stump1eb44332009-09-09 15:08:12 +000010918
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010919 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10920
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010921 // Perform overload resolution.
10922 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010923 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010924 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010925 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010926 // Overload resolution succeeded; we'll build the appropriate call
10927 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010928 break;
10929
10930 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010931 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010932 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010933 << Object.get()->getType() << /*call*/ 1
10934 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010935 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010936 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010937 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010938 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010939 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10940 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010941 break;
10942
10943 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010944 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010945 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010946 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010947 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10948 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010949 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010950
10951 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010952 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010953 diag::err_ovl_deleted_object_call)
10954 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010955 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010956 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010957 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010958 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10959 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010960 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010961 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010962
Douglas Gregorff331c12010-07-25 18:17:45 +000010963 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010964 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010965
John McCall5acb0c92011-10-17 18:40:02 +000010966 UnbridgedCasts.restore();
10967
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010968 if (Best->Function == 0) {
10969 // Since there is no function declaration, this is one of the
10970 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010971 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010972 = cast<CXXConversionDecl>(
10973 Best->Conversions[0].UserDefined.ConversionFunction);
10974
John Wiegley429bb272011-04-08 18:41:53 +000010975 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010976 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010977
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010978 // We selected one of the surrogate functions that converts the
10979 // object parameter to a function pointer. Perform the conversion
10980 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010981
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010982 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010983 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010984 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10985 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010986 if (Call.isInvalid())
10987 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010988 // Record usage of conversion in an implicit cast.
10989 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10990 CK_UserDefinedConversion,
10991 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010992
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010993 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010994 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010995 }
10996
Eli Friedman5f2987c2012-02-02 03:46:19 +000010997 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010998 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010999 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011000
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011001 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11002 // that calls this method, using Object for the implicit object
11003 // parameter and passing along the remaining arguments.
11004 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000011005 const FunctionProtoType *Proto =
11006 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011007
11008 unsigned NumArgsInProto = Proto->getNumArgs();
11009 unsigned NumArgsToCheck = NumArgs;
11010
11011 // Build the full argument list for the method call (the
11012 // implicit object parameter is placed at the beginning of the
11013 // list).
11014 Expr **MethodArgs;
11015 if (NumArgs < NumArgsInProto) {
11016 NumArgsToCheck = NumArgsInProto;
11017 MethodArgs = new Expr*[NumArgsInProto + 1];
11018 } else {
11019 MethodArgs = new Expr*[NumArgs + 1];
11020 }
John Wiegley429bb272011-04-08 18:41:53 +000011021 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011022 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11023 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011024
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011025 DeclarationNameInfo OpLocInfo(
11026 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11027 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011028 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011029 HadMultipleCandidates,
11030 OpLocInfo.getLoc(),
11031 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011032 if (NewFn.isInvalid())
11033 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011034
11035 // Once we've built TheCall, all of the expressions are properly
11036 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011037 QualType ResultTy = Method->getResultType();
11038 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11039 ResultTy = ResultTy.getNonLValueExprType(Context);
11040
John McCall9ae2f072010-08-23 23:25:46 +000011041 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011042 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011043 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011044 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011045 delete [] MethodArgs;
11046
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011047 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011048 Method))
11049 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011050
Douglas Gregor518fda12009-01-13 05:10:00 +000011051 // We may have default arguments. If so, we need to allocate more
11052 // slots in the call for them.
11053 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011054 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011055 else if (NumArgs > NumArgsInProto)
11056 NumArgsToCheck = NumArgsInProto;
11057
Chris Lattner312531a2009-04-12 08:11:20 +000011058 bool IsError = false;
11059
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011060 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011061 ExprResult ObjRes =
11062 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11063 Best->FoundDecl, Method);
11064 if (ObjRes.isInvalid())
11065 IsError = true;
11066 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011067 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011068 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011069
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011070 // Check the argument types.
11071 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011072 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011073 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011074 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011075
Douglas Gregor518fda12009-01-13 05:10:00 +000011076 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011077
John McCall60d7b3a2010-08-24 06:29:42 +000011078 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011079 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011080 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011081 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011082 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011083
Anders Carlsson3faa4862010-01-29 18:43:53 +000011084 IsError |= InputInit.isInvalid();
11085 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011086 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011087 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011088 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11089 if (DefArg.isInvalid()) {
11090 IsError = true;
11091 break;
11092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011093
Douglas Gregord47c47d2009-11-09 19:27:57 +000011094 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011095 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011096
11097 TheCall->setArg(i + 1, Arg);
11098 }
11099
11100 // If this is a variadic call, handle args passed through "...".
11101 if (Proto->isVariadic()) {
11102 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011103 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011104 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11105 IsError |= Arg.isInvalid();
11106 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011107 }
11108 }
11109
Chris Lattner312531a2009-04-12 08:11:20 +000011110 if (IsError) return true;
11111
Eli Friedmane61eb042012-02-18 04:48:30 +000011112 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11113
Richard Smith831421f2012-06-25 20:30:08 +000011114 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011115 return true;
11116
John McCall182f7092010-08-24 06:09:16 +000011117 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011118}
11119
Douglas Gregor8ba10742008-11-20 16:27:02 +000011120/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011121/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011122/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011123ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011124Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011125 assert(Base->getType()->isRecordType() &&
11126 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011127
John McCall5acb0c92011-10-17 18:40:02 +000011128 if (checkPlaceholderForOverload(*this, Base))
11129 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011130
John McCall5769d612010-02-08 23:07:23 +000011131 SourceLocation Loc = Base->getExprLoc();
11132
Douglas Gregor8ba10742008-11-20 16:27:02 +000011133 // C++ [over.ref]p1:
11134 //
11135 // [...] An expression x->m is interpreted as (x.operator->())->m
11136 // for a class object x of type T if T::operator->() exists and if
11137 // the operator is selected as the best match function by the
11138 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011139 DeclarationName OpName =
11140 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011141 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011142 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011143
John McCall5769d612010-02-08 23:07:23 +000011144 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011145 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011146 return ExprError();
11147
John McCalla24dc2e2009-11-17 02:14:36 +000011148 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11149 LookupQualifiedName(R, BaseRecord->getDecl());
11150 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011151
11152 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011153 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011154 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11155 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011156 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011157
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011158 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11159
Douglas Gregor8ba10742008-11-20 16:27:02 +000011160 // Perform overload resolution.
11161 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011162 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011163 case OR_Success:
11164 // Overload resolution succeeded; we'll build the call below.
11165 break;
11166
11167 case OR_No_Viable_Function:
11168 if (CandidateSet.empty())
11169 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011170 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011171 else
11172 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011173 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011174 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011175 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011176
11177 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011178 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11179 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011180 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011181 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011182
11183 case OR_Deleted:
11184 Diag(OpLoc, diag::err_ovl_deleted_oper)
11185 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011186 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011187 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011188 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011189 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011190 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011191 }
11192
Eli Friedman5f2987c2012-02-02 03:46:19 +000011193 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011194 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011195 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011196
Douglas Gregor8ba10742008-11-20 16:27:02 +000011197 // Convert the object parameter.
11198 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011199 ExprResult BaseResult =
11200 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11201 Best->FoundDecl, Method);
11202 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011203 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011204 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011205
Douglas Gregor8ba10742008-11-20 16:27:02 +000011206 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011207 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011208 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011209 if (FnExpr.isInvalid())
11210 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011211
John McCallf89e55a2010-11-18 06:31:45 +000011212 QualType ResultTy = Method->getResultType();
11213 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11214 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011215 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011216 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011217 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011218
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011219 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011220 Method))
11221 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011222
11223 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011224}
11225
Richard Smith36f5cfe2012-03-09 08:00:36 +000011226/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11227/// a literal operator described by the provided lookup results.
11228ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11229 DeclarationNameInfo &SuffixInfo,
11230 ArrayRef<Expr*> Args,
11231 SourceLocation LitEndLoc,
11232 TemplateArgumentListInfo *TemplateArgs) {
11233 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011234
Richard Smith36f5cfe2012-03-09 08:00:36 +000011235 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11236 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11237 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011238
Richard Smith36f5cfe2012-03-09 08:00:36 +000011239 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11240
Richard Smith36f5cfe2012-03-09 08:00:36 +000011241 // Perform overload resolution. This will usually be trivial, but might need
11242 // to perform substitutions for a literal operator template.
11243 OverloadCandidateSet::iterator Best;
11244 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11245 case OR_Success:
11246 case OR_Deleted:
11247 break;
11248
11249 case OR_No_Viable_Function:
11250 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11251 << R.getLookupName();
11252 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11253 return ExprError();
11254
11255 case OR_Ambiguous:
11256 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11257 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11258 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011259 }
11260
Richard Smith36f5cfe2012-03-09 08:00:36 +000011261 FunctionDecl *FD = Best->Function;
11262 MarkFunctionReferenced(UDSuffixLoc, FD);
11263 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011264
Richard Smith36f5cfe2012-03-09 08:00:36 +000011265 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11266 SuffixInfo.getLoc(),
11267 SuffixInfo.getInfo());
11268 if (Fn.isInvalid())
11269 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011270
11271 // Check the argument types. This should almost always be a no-op, except
11272 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011273 Expr *ConvArgs[2];
11274 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11275 ExprResult InputInit = PerformCopyInitialization(
11276 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11277 SourceLocation(), Args[ArgIdx]);
11278 if (InputInit.isInvalid())
11279 return true;
11280 ConvArgs[ArgIdx] = InputInit.take();
11281 }
11282
Richard Smith9fcce652012-03-07 08:35:16 +000011283 QualType ResultTy = FD->getResultType();
11284 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11285 ResultTy = ResultTy.getNonLValueExprType(Context);
11286
Richard Smith9fcce652012-03-07 08:35:16 +000011287 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011288 new (Context) UserDefinedLiteral(Context, Fn.take(),
11289 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011290 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11291
11292 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11293 return ExprError();
11294
Richard Smith831421f2012-06-25 20:30:08 +000011295 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011296 return ExprError();
11297
11298 return MaybeBindToTemporary(UDL);
11299}
11300
Sam Panzere1715b62012-08-21 00:52:01 +000011301/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11302/// given LookupResult is non-empty, it is assumed to describe a member which
11303/// will be invoked. Otherwise, the function will be found via argument
11304/// dependent lookup.
11305/// CallExpr is set to a valid expression and FRS_Success returned on success,
11306/// otherwise CallExpr is set to ExprError() and some non-success value
11307/// is returned.
11308Sema::ForRangeStatus
11309Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11310 SourceLocation RangeLoc, VarDecl *Decl,
11311 BeginEndFunction BEF,
11312 const DeclarationNameInfo &NameInfo,
11313 LookupResult &MemberLookup,
11314 OverloadCandidateSet *CandidateSet,
11315 Expr *Range, ExprResult *CallExpr) {
11316 CandidateSet->clear();
11317 if (!MemberLookup.empty()) {
11318 ExprResult MemberRef =
11319 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11320 /*IsPtr=*/false, CXXScopeSpec(),
11321 /*TemplateKWLoc=*/SourceLocation(),
11322 /*FirstQualifierInScope=*/0,
11323 MemberLookup,
11324 /*TemplateArgs=*/0);
11325 if (MemberRef.isInvalid()) {
11326 *CallExpr = ExprError();
11327 Diag(Range->getLocStart(), diag::note_in_for_range)
11328 << RangeLoc << BEF << Range->getType();
11329 return FRS_DiagnosticIssued;
11330 }
11331 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11332 if (CallExpr->isInvalid()) {
11333 *CallExpr = ExprError();
11334 Diag(Range->getLocStart(), diag::note_in_for_range)
11335 << RangeLoc << BEF << Range->getType();
11336 return FRS_DiagnosticIssued;
11337 }
11338 } else {
11339 UnresolvedSet<0> FoundNames;
11340 // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace
11341 // std is an associated namespace.
11342 UnresolvedLookupExpr *Fn =
11343 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11344 NestedNameSpecifierLoc(), NameInfo,
11345 /*NeedsADL=*/true, /*Overloaded=*/false,
11346 FoundNames.begin(), FoundNames.end(),
11347 /*LookInStdNamespace=*/true);
11348
11349 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11350 CandidateSet, CallExpr);
11351 if (CandidateSet->empty() || CandidateSetError) {
11352 *CallExpr = ExprError();
11353 return FRS_NoViableFunction;
11354 }
11355 OverloadCandidateSet::iterator Best;
11356 OverloadingResult OverloadResult =
11357 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11358
11359 if (OverloadResult == OR_No_Viable_Function) {
11360 *CallExpr = ExprError();
11361 return FRS_NoViableFunction;
11362 }
11363 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11364 Loc, 0, CandidateSet, &Best,
11365 OverloadResult,
11366 /*AllowTypoCorrection=*/false);
11367 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11368 *CallExpr = ExprError();
11369 Diag(Range->getLocStart(), diag::note_in_for_range)
11370 << RangeLoc << BEF << Range->getType();
11371 return FRS_DiagnosticIssued;
11372 }
11373 }
11374 return FRS_Success;
11375}
11376
11377
Douglas Gregor904eed32008-11-10 20:40:00 +000011378/// FixOverloadedFunctionReference - E is an expression that refers to
11379/// a C++ overloaded function (possibly with some parentheses and
11380/// perhaps a '&' around it). We have resolved the overloaded function
11381/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011382/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011383Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011384 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011385 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011386 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11387 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011388 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011389 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011390
Douglas Gregor699ee522009-11-20 19:42:02 +000011391 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011392 }
11393
Douglas Gregor699ee522009-11-20 19:42:02 +000011394 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011395 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11396 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011397 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011398 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011399 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011400 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011401 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011402 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011403
11404 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011405 ICE->getCastKind(),
11406 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011407 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011408 }
11409
Douglas Gregor699ee522009-11-20 19:42:02 +000011410 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011411 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011412 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011413 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11414 if (Method->isStatic()) {
11415 // Do nothing: static member functions aren't any different
11416 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011417 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011418 // Fix the sub expression, which really has to be an
11419 // UnresolvedLookupExpr holding an overloaded member function
11420 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011421 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11422 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011423 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011424 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011425
John McCallba135432009-11-21 08:51:07 +000011426 assert(isa<DeclRefExpr>(SubExpr)
11427 && "fixed to something other than a decl ref");
11428 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11429 && "fixed to a member ref with no nested name qualifier");
11430
11431 // We have taken the address of a pointer to member
11432 // function. Perform the computation here so that we get the
11433 // appropriate pointer to member type.
11434 QualType ClassType
11435 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11436 QualType MemPtrType
11437 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11438
John McCallf89e55a2010-11-18 06:31:45 +000011439 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11440 VK_RValue, OK_Ordinary,
11441 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011442 }
11443 }
John McCall6bb80172010-03-30 21:47:33 +000011444 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11445 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011446 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011447 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011448
John McCall2de56d12010-08-25 11:45:40 +000011449 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011450 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011451 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011452 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011453 }
John McCallba135432009-11-21 08:51:07 +000011454
11455 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011456 // FIXME: avoid copy.
11457 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011458 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011459 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11460 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011461 }
11462
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011463 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11464 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011465 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011466 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011467 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011468 ULE->getNameLoc(),
11469 Fn->getType(),
11470 VK_LValue,
11471 Found.getDecl(),
11472 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011473 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011474 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11475 return DRE;
John McCallba135432009-11-21 08:51:07 +000011476 }
11477
John McCall129e2df2009-11-30 22:42:35 +000011478 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011479 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011480 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11481 if (MemExpr->hasExplicitTemplateArgs()) {
11482 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11483 TemplateArgs = &TemplateArgsBuffer;
11484 }
John McCalld5532b62009-11-23 01:53:49 +000011485
John McCallaa81e162009-12-01 22:10:20 +000011486 Expr *Base;
11487
John McCallf89e55a2010-11-18 06:31:45 +000011488 // If we're filling in a static method where we used to have an
11489 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011490 if (MemExpr->isImplicitAccess()) {
11491 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011492 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11493 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011494 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011495 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011496 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011497 MemExpr->getMemberLoc(),
11498 Fn->getType(),
11499 VK_LValue,
11500 Found.getDecl(),
11501 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011502 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011503 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11504 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011505 } else {
11506 SourceLocation Loc = MemExpr->getMemberLoc();
11507 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011508 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011509 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011510 Base = new (Context) CXXThisExpr(Loc,
11511 MemExpr->getBaseType(),
11512 /*isImplicit=*/true);
11513 }
John McCallaa81e162009-12-01 22:10:20 +000011514 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011515 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011516
John McCallf5307512011-04-27 00:36:17 +000011517 ExprValueKind valueKind;
11518 QualType type;
11519 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11520 valueKind = VK_LValue;
11521 type = Fn->getType();
11522 } else {
11523 valueKind = VK_RValue;
11524 type = Context.BoundMemberTy;
11525 }
11526
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011527 MemberExpr *ME = MemberExpr::Create(Context, Base,
11528 MemExpr->isArrow(),
11529 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011530 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011531 Fn,
11532 Found,
11533 MemExpr->getMemberNameInfo(),
11534 TemplateArgs,
11535 type, valueKind, OK_Ordinary);
11536 ME->setHadMultipleCandidates(true);
11537 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011538 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011539
John McCall3fa5cae2010-10-26 07:05:15 +000011540 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011541}
11542
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011543ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011544 DeclAccessPair Found,
11545 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011546 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011547}
11548
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011549} // end namespace clang