blob: 29644b40b74db87503f805731af24dc667a9ba5a [file] [log] [blame]
Nick Lewycky5d9484d2013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002//
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
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000038
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000039/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42 bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith82f145d2013-05-04 06:44:46 +000045 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid570a922013-06-15 11:54:37 +000046 return ExprError();
47 // If FoundDecl is different from Fn (such as if one is a template
48 // and the other a specialization), make sure DiagnoseUseOfDecl is
49 // called on both.
50 // FIXME: This would be more comprehensively addressed by modifying
51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
52 // being used.
53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith82f145d2013-05-04 06:44:46 +000054 return ExprError();
John McCallf4b88a42012-03-10 09:33:50 +000055 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000056 VK_LValue, Loc, LocInfo);
57 if (HadMultipleCandidates)
58 DRE->setHadMultipleCandidates(true);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000059
60 S.MarkDeclRefReferenced(DRE);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000061
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000062 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000063 E = S.DefaultFunctionArrayConversion(E.take());
64 if (E.isInvalid())
65 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000066 return E;
John McCallf89e55a2010-11-18 06:31:45 +000067}
68
John McCall120d63c2010-08-24 20:38:10 +000069static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
70 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000071 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000072 bool CStyle,
73 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000074
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000075static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
76 QualType &ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000080static OverloadingResult
81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
82 UserDefinedConversionSequence& User,
83 OverloadCandidateSet& Conversions,
84 bool AllowExplicit);
85
86
87static ImplicitConversionSequence::CompareKind
88CompareStandardConversionSequences(Sema &S,
89 const StandardConversionSequence& SCS1,
90 const StandardConversionSequence& SCS2);
91
92static ImplicitConversionSequence::CompareKind
93CompareQualificationConversions(Sema &S,
94 const StandardConversionSequence& SCS1,
95 const StandardConversionSequence& SCS2);
96
97static ImplicitConversionSequence::CompareKind
98CompareDerivedToBaseConversions(Sema &S,
99 const StandardConversionSequence& SCS1,
100 const StandardConversionSequence& SCS2);
101
102
103
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104/// GetConversionCategory - Retrieve the implicit conversion
105/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +0000106ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107GetConversionCategory(ImplicitConversionKind Kind) {
108 static const ImplicitConversionCategory
109 Category[(int)ICK_Num_Conversion_Kinds] = {
110 ICC_Identity,
111 ICC_Lvalue_Transformation,
112 ICC_Lvalue_Transformation,
113 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000114 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000115 ICC_Qualification_Adjustment,
116 ICC_Promotion,
117 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000118 ICC_Promotion,
119 ICC_Conversion,
120 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000121 ICC_Conversion,
122 ICC_Conversion,
123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000126 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000127 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000128 ICC_Conversion,
129 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000130 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000131 ICC_Conversion
132 };
133 return Category[(int)Kind];
134}
135
136/// GetConversionRank - Retrieve the implicit conversion rank
137/// corresponding to the given implicit conversion kind.
138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
139 static const ImplicitConversionRank
140 Rank[(int)ICK_Num_Conversion_Kinds] = {
141 ICR_Exact_Match,
142 ICR_Exact_Match,
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000146 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 ICR_Promotion,
148 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000149 ICR_Promotion,
150 ICR_Conversion,
151 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000157 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000158 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000159 ICR_Conversion,
160 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000161 ICR_Complex_Real_Conversion,
162 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000163 ICR_Conversion,
164 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165 };
166 return Rank[(int)Kind];
167}
168
169/// GetImplicitConversionName - Return the name of this kind of
170/// implicit conversion.
171const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 "No conversion",
174 "Lvalue-to-rvalue",
175 "Array-to-pointer",
176 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000177 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000178 "Qualification",
179 "Integral promotion",
180 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000181 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 "Integral conversion",
183 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000184 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 "Floating-integral conversion",
186 "Pointer conversion",
187 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000188 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000189 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000190 "Derived-to-base conversion",
191 "Vector conversion",
192 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000193 "Complex-real conversion",
194 "Block Pointer conversion",
195 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000196 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 };
198 return Name[Kind];
199}
200
Douglas Gregor60d62c22008-10-31 16:23:19 +0000201/// StandardConversionSequence - Set the standard conversion
202/// sequence to the identity conversion.
203void StandardConversionSequence::setAsIdentityConversion() {
204 First = ICK_Identity;
205 Second = ICK_Identity;
206 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000207 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000208 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000209 ReferenceBinding = false;
210 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000211 IsLvalueReference = true;
212 BindsToFunctionLvalue = false;
213 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000214 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000215 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000216 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000217}
218
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219/// getRank - Retrieve the rank of this standard conversion sequence
220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
221/// implicit conversions.
222ImplicitConversionRank StandardConversionSequence::getRank() const {
223 ImplicitConversionRank Rank = ICR_Exact_Match;
224 if (GetConversionRank(First) > Rank)
225 Rank = GetConversionRank(First);
226 if (GetConversionRank(Second) > Rank)
227 Rank = GetConversionRank(Second);
228 if (GetConversionRank(Third) > Rank)
229 Rank = GetConversionRank(Third);
230 return Rank;
231}
232
233/// isPointerConversionToBool - Determines whether this conversion is
234/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000235/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000237bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 // Note that FromType has not necessarily been transformed by the
239 // array-to-pointer or function-to-pointer implicit conversions, so
240 // check for their presence as well as checking whether FromType is
241 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000242 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000243 (getFromType()->isPointerType() ||
244 getFromType()->isObjCObjectPointerType() ||
245 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000246 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
248 return true;
249
250 return false;
251}
252
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000253/// isPointerConversionToVoidPointer - Determines whether this
254/// conversion is a conversion of a pointer to a void pointer. This is
255/// used as part of the ranking of standard conversion sequences (C++
256/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000257bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000258StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000259isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000260 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000261 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000262
263 // Note that FromType has not necessarily been transformed by the
264 // array-to-pointer implicit conversion, so check for its presence
265 // and redo the conversion to get a pointer.
266 if (First == ICK_Array_To_Pointer)
267 FromType = Context.getArrayDecayedType(FromType);
268
Douglas Gregorf9af5242011-04-15 20:45:44 +0000269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000271 return ToPtrType->getPointeeType()->isVoidType();
272
273 return false;
274}
275
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000276/// Skip any implicit casts which could be either part of a narrowing conversion
277/// or after one in an implicit conversion.
278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280 switch (ICE->getCastKind()) {
281 case CK_NoOp:
282 case CK_IntegralCast:
283 case CK_IntegralToBoolean:
284 case CK_IntegralToFloating:
285 case CK_FloatingToIntegral:
286 case CK_FloatingToBoolean:
287 case CK_FloatingCast:
288 Converted = ICE->getSubExpr();
289 continue;
290
291 default:
292 return Converted;
293 }
294 }
295
296 return Converted;
297}
298
299/// Check if this standard conversion sequence represents a narrowing
300/// conversion, according to C++11 [dcl.init.list]p7.
301///
302/// \param Ctx The AST context.
303/// \param Converted The result of applying this standard conversion sequence.
304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000308NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
310 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000311 APValue &ConstantValue,
312 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000314
315 // C++11 [dcl.init.list]p7:
316 // A narrowing conversion is an implicit conversion ...
317 QualType FromType = getToType(0);
318 QualType ToType = getToType(1);
319 switch (Second) {
320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332 if (Initializer &&
333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334 // Convert the integer to the floating type.
335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337 llvm::APFloat::rmNearestTiesToEven);
338 // And back.
339 llvm::APSInt ConvertedValue = IntConstantValue;
340 bool ignored;
341 Result.convertToInteger(ConvertedValue,
342 llvm::APFloat::rmTowardZero, &ignored);
343 // If the resulting value is different, this was a narrowing conversion.
344 if (IntConstantValue != ConvertedValue) {
345 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000346 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
348 }
349 } else {
350 // Variables are always narrowings.
351 return NK_Variable_Narrowing;
352 }
353 }
354 return NK_Not_Narrowing;
355
356 // -- from long double to double or float, or from double to float, except
357 // where the source is a constant expression and the actual value after
358 // conversion is within the range of values that can be represented (even
359 // if it cannot be represented exactly), or
360 case ICK_Floating_Conversion:
361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363 // FromType is larger than ToType.
364 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366 // Constant!
367 assert(ConstantValue.isFloat());
368 llvm::APFloat FloatVal = ConstantValue.getFloat();
369 // Convert the source value into the target type.
370 bool ignored;
371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372 Ctx.getFloatTypeSemantics(ToType),
373 llvm::APFloat::rmNearestTiesToEven, &ignored);
374 // If there was no overflow, the source value is within the range of
375 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000376 if (ConvertStatus & llvm::APFloat::opOverflow) {
377 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000378 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000379 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000380 } else {
381 return NK_Variable_Narrowing;
382 }
383 }
384 return NK_Not_Narrowing;
385
386 // -- from an integer type or unscoped enumeration type to an integer type
387 // that cannot represent all the values of the original type, except where
388 // the source is a constant expression and the actual value after
389 // conversion will fit into the target type and will produce the original
390 // value when converted back to the original type.
391 case ICK_Boolean_Conversion: // Bools are integers too.
392 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
393 // Boolean conversions can be from pointers and pointers to members
394 // [conv.bool], and those aren't considered narrowing conversions.
395 return NK_Not_Narrowing;
396 } // Otherwise, fall through to the integral case.
397 case ICK_Integral_Conversion: {
398 assert(FromType->isIntegralOrUnscopedEnumerationType());
399 assert(ToType->isIntegralOrUnscopedEnumerationType());
400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
401 const unsigned FromWidth = Ctx.getIntWidth(FromType);
402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
403 const unsigned ToWidth = Ctx.getIntWidth(ToType);
404
405 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000406 (FromWidth == ToWidth && FromSigned != ToSigned) ||
407 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000408 // Not all values of FromType can be represented in ToType.
409 llvm::APSInt InitializerValue;
410 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
412 // Such conversions on variables are always narrowing.
413 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000414 }
415 bool Narrowing = false;
416 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000417 // Negative -> unsigned is narrowing. Otherwise, more bits is never
418 // narrowing.
419 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000420 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000421 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000422 // Add a bit to the InitializerValue so we don't have to worry about
423 // signed vs. unsigned comparisons.
424 InitializerValue = InitializerValue.extend(
425 InitializerValue.getBitWidth() + 1);
426 // Convert the initializer to and from the target width and signed-ness.
427 llvm::APSInt ConvertedValue = InitializerValue;
428 ConvertedValue = ConvertedValue.trunc(ToWidth);
429 ConvertedValue.setIsSigned(ToSigned);
430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
431 ConvertedValue.setIsSigned(InitializerValue.isSigned());
432 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000433 if (ConvertedValue != InitializerValue)
434 Narrowing = true;
435 }
436 if (Narrowing) {
437 ConstantType = Initializer->getType();
438 ConstantValue = APValue(InitializerValue);
439 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000440 }
441 }
442 return NK_Not_Narrowing;
443 }
444
445 default:
446 // Other kinds of conversions are not narrowings.
447 return NK_Not_Narrowing;
448 }
449}
450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451/// DebugPrint - Print this standard conversion sequence to standard
452/// error. Useful for debugging overloading issues.
453void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000454 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 bool PrintedSomething = false;
456 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (Second != ICK_Identity) {
462 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000466
467 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000468 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000469 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000470 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000471 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000473 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 PrintedSomething = true;
475 }
476
477 if (Third != ICK_Identity) {
478 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000481 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 PrintedSomething = true;
483 }
484
485 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000486 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 }
488}
489
490/// DebugPrint - Print this user-defined conversion sequence to standard
491/// error. Useful for debugging overloading issues.
492void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000493 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000494 if (Before.First || Before.Second || Before.Third) {
495 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000498 if (ConversionFunction)
499 OS << '\'' << *ConversionFunction << '\'';
500 else
501 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000503 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 After.DebugPrint();
505 }
506}
507
508/// DebugPrint - Print this implicit conversion sequence to standard
509/// error. Useful for debugging overloading issues.
510void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000511 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 switch (ConversionKind) {
513 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000514 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 Standard.DebugPrint();
516 break;
517 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 UserDefined.DebugPrint();
520 break;
521 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000522 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 break;
John McCall1d318332010-01-12 00:44:57 +0000524 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000525 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000526 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000528 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 break;
530 }
531
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000532 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533}
534
John McCall1d318332010-01-12 00:44:57 +0000535void AmbiguousConversionSequence::construct() {
536 new (&conversions()) ConversionSet();
537}
538
539void AmbiguousConversionSequence::destruct() {
540 conversions().~ConversionSet();
541}
542
543void
544AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
545 FromTypePtr = O.FromTypePtr;
546 ToTypePtr = O.ToTypePtr;
547 new (&conversions()) ConversionSet(O.conversions());
548}
549
Douglas Gregora9333192010-05-08 17:41:32 +0000550namespace {
551 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000552 // template argument information.
553 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000554 TemplateArgument FirstArg;
555 TemplateArgument SecondArg;
556 };
Richard Smith29805ca2013-01-31 05:19:49 +0000557 // Structure used by OverloadCandidate::DeductionFailureInfo to store
558 // template parameter and template argument information.
559 struct DFIParamWithArguments : DFIArguments {
560 TemplateParameter Param;
561 };
Douglas Gregora9333192010-05-08 17:41:32 +0000562}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564/// \brief Convert from Sema's representation of template deduction information
565/// to the form used in overload-candidate information.
566OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000567static MakeDeductionFailureInfo(ASTContext &Context,
568 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000569 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000570 OverloadCandidate::DeductionFailureInfo Result;
571 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000572 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000573 Result.Data = 0;
574 switch (TDK) {
575 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000576 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000577 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000578 case Sema::TDK_TooManyArguments:
579 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora9333192010-05-08 17:41:32 +0000582 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000583 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000584 Result.Data = Info.Param.getOpaqueValue();
585 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586
Richard Smith29805ca2013-01-31 05:19:49 +0000587 case Sema::TDK_NonDeducedMismatch: {
588 // FIXME: Should allocate from normal heap so that we can free this later.
589 DFIArguments *Saved = new (Context) DFIArguments;
590 Saved->FirstArg = Info.FirstArg;
591 Saved->SecondArg = Info.SecondArg;
592 Result.Data = Saved;
593 break;
594 }
595
Douglas Gregora9333192010-05-08 17:41:32 +0000596 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000597 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000598 // FIXME: Should allocate from normal heap so that we can free this later.
599 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000600 Saved->Param = Info.Param;
601 Saved->FirstArg = Info.FirstArg;
602 Saved->SecondArg = Info.SecondArg;
603 Result.Data = Saved;
604 break;
605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000606
Douglas Gregora9333192010-05-08 17:41:32 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000608 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000609 if (Info.hasSFINAEDiagnostic()) {
610 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
611 SourceLocation(), PartialDiagnostic::NullDiagnostic());
612 Info.takeSFINAEDiagnostic(*Diag);
613 Result.HasDiagnostic = true;
614 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616
Douglas Gregora9333192010-05-08 17:41:32 +0000617 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000618 Result.Data = Info.Expression;
619 break;
620
Richard Smith29805ca2013-01-31 05:19:49 +0000621 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000622 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000623 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregora9333192010-05-08 17:41:32 +0000625 return Result;
626}
John McCall1d318332010-01-12 00:44:57 +0000627
Douglas Gregora9333192010-05-08 17:41:32 +0000628void OverloadCandidate::DeductionFailureInfo::Destroy() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000631 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000632 case Sema::TDK_InstantiationDepth:
633 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000634 case Sema::TDK_TooManyArguments:
635 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000636 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000637 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000638 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639
Douglas Gregora9333192010-05-08 17:41:32 +0000640 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000641 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000642 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000643 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000644 Data = 0;
645 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000646
647 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000648 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000649 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
651 Diag->~PartialDiagnosticAt();
652 HasDiagnostic = false;
653 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000654 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000656 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000657 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000658 break;
659 }
660}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661
Richard Smithb8590f32012-05-07 09:03:25 +0000662PartialDiagnosticAt *
663OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
666 return 0;
667}
668
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000670OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
672 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000673 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000674 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000675 case Sema::TDK_TooManyArguments:
676 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000677 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000680 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000681
Douglas Gregora9333192010-05-08 17:41:32 +0000682 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000685
686 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000687 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000688 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689
Douglas Gregora9333192010-05-08 17:41:32 +0000690 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000691 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000692 break;
693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694
Douglas Gregora9333192010-05-08 17:41:32 +0000695 return TemplateParameter();
696}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Douglas Gregorec20f462010-05-08 20:07:26 +0000698TemplateArgumentList *
699OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000713
Richard Smith29805ca2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716
Richard Smith29805ca2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Douglas Gregora9333192010-05-08 17:41:32 +0000725const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregora9333192010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000742
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747
Douglas Gregora9333192010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000749}
Douglas Gregora9333192010-05-08 17:41:32 +0000750
751const TemplateArgument *
752OverloadCandidate::DeductionFailureInfo::getSecondArg() {
753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000755 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000756 case Sema::TDK_InstantiationDepth:
757 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000758 case Sema::TDK_TooManyArguments:
759 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000760 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000761 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000762 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000763 return 0;
764
Douglas Gregora9333192010-05-08 17:41:32 +0000765 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000766 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000767 case Sema::TDK_NonDeducedMismatch:
768 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000769
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000770 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000771 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000772 break;
773 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774
Douglas Gregora9333192010-05-08 17:41:32 +0000775 return 0;
776}
777
Richard Smith0efa62f2013-01-31 04:03:12 +0000778Expr *
779OverloadCandidate::DeductionFailureInfo::getExpr() {
780 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
781 Sema::TDK_FailedOverloadResolution)
782 return static_cast<Expr*>(Data);
783
784 return 0;
785}
786
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000787void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000788 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000789 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
790 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000791 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
792 i->DeductionFailure.Destroy();
793 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000794}
795
796void OverloadCandidateSet::clear() {
797 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000798 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000799 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000800 Functions.clear();
801}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802
John McCall5acb0c92011-10-17 18:40:02 +0000803namespace {
804 class UnbridgedCastsSet {
805 struct Entry {
806 Expr **Addr;
807 Expr *Saved;
808 };
809 SmallVector<Entry, 2> Entries;
810
811 public:
812 void save(Sema &S, Expr *&E) {
813 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
814 Entry entry = { &E, E };
815 Entries.push_back(entry);
816 E = S.stripARCUnbridgedCast(E);
817 }
818
819 void restore() {
820 for (SmallVectorImpl<Entry>::iterator
821 i = Entries.begin(), e = Entries.end(); i != e; ++i)
822 *i->Addr = i->Saved;
823 }
824 };
825}
826
827/// checkPlaceholderForOverload - Do any interesting placeholder-like
828/// preprocessing on the given expression.
829///
830/// \param unbridgedCasts a collection to which to add unbridged casts;
831/// without this, they will be immediately diagnosed as errors
832///
833/// Return true on unrecoverable error.
834static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
835 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
837 // We can't handle overloaded expressions here because overload
838 // resolution might reasonably tweak them.
839 if (placeholder->getKind() == BuiltinType::Overload) return false;
840
841 // If the context potentially accepts unbridged ARC casts, strip
842 // the unbridged cast and add it to the collection for later restoration.
843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
844 unbridgedCasts) {
845 unbridgedCasts->save(S, E);
846 return false;
847 }
848
849 // Go ahead and check everything else.
850 ExprResult result = S.CheckPlaceholderExpr(E);
851 if (result.isInvalid())
852 return true;
853
854 E = result.take();
855 return false;
856 }
857
858 // Nothing to do.
859 return false;
860}
861
862/// checkArgPlaceholdersForOverload - Check a set of call operands for
863/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000864static bool checkArgPlaceholdersForOverload(Sema &S,
865 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000866 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000867 for (unsigned i = 0, e = Args.size(); i != e; ++i)
868 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000869 return true;
870
871 return false;
872}
873
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000874// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000875// overload of the declarations in Old. This routine returns false if
876// New and Old cannot be overloaded, e.g., if New has the same
877// signature as some function in Old (C++ 1.3.10) or if the Old
878// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000879// it does return false, MatchedDecl will point to the decl that New
880// cannot be overloaded with. This decl may be a UsingShadowDecl on
881// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000882//
883// Example: Given the following input:
884//
885// void f(int, float); // #1
886// void f(int, int); // #2
887// int f(int, int); // #3
888//
889// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000890// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000891//
John McCall51fa86f2009-12-02 08:47:38 +0000892// When we process #2, Old contains only the FunctionDecl for #1. By
893// comparing the parameter types, we see that #1 and #2 are overloaded
894// (since they have different signatures), so this routine returns
895// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000896//
John McCall51fa86f2009-12-02 08:47:38 +0000897// When we process #3, Old is an overload set containing #1 and #2. We
898// compare the signatures of #3 to #1 (they're overloaded, so we do
899// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000901// signature), IsOverload returns false and MatchedDecl will be set to
902// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000903//
904// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905// into a class by a using declaration. The rules for whether to hide
906// shadow declarations ignore some properties which otherwise figure
907// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000908Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000909Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000911 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000912 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000913 NamedDecl *OldD = *I;
914
915 bool OldIsUsingDecl = false;
916 if (isa<UsingShadowDecl>(OldD)) {
917 OldIsUsingDecl = true;
918
919 // We can always introduce two using declarations into the same
920 // context, even if they have identical signatures.
921 if (NewIsUsingDecl) continue;
922
923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
924 }
925
926 // If either declaration was introduced by a using declaration,
927 // we'll need to use slightly different rules for matching.
928 // Essentially, these rules are the normal rules, except that
929 // function templates hide function templates with different
930 // return types or template parameter lists.
931 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000934
John McCall51fa86f2009-12-02 08:47:38 +0000935 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000936 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939 continue;
940 }
941
John McCall871b2e72009-12-09 03:35:25 +0000942 Match = *I;
943 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000944 }
John McCall51fa86f2009-12-02 08:47:38 +0000945 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000946 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
947 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
948 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
949 continue;
950 }
951
Rafael Espindola90cc3902013-04-15 12:49:13 +0000952 if (!shouldLinkPossiblyHiddenDecl(*I, New))
953 continue;
954
John McCall871b2e72009-12-09 03:35:25 +0000955 Match = *I;
956 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000957 }
John McCalld7945c62010-11-10 03:01:53 +0000958 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000959 // We can overload with these, which can show up when doing
960 // redeclaration checks for UsingDecls.
961 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000962 } else if (isa<TagDecl>(OldD)) {
963 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000964 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
965 // Optimistically assume that an unresolved using decl will
966 // overload; if it doesn't, we'll have to diagnose during
967 // template instantiation.
968 } else {
John McCall68263142009-11-18 22:49:29 +0000969 // (C++ 13p1):
970 // Only function declarations can be overloaded; object and type
971 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000972 Match = *I;
973 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000974 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000975 }
John McCall68263142009-11-18 22:49:29 +0000976
John McCall871b2e72009-12-09 03:35:25 +0000977 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000978}
979
Rafael Espindola78eeba82012-12-28 14:21:58 +0000980static bool canBeOverloaded(const FunctionDecl &D) {
981 if (D.getAttr<OverloadableAttr>())
982 return true;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000983 if (D.isExternC())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000984 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000985
986 // Main cannot be overloaded (basic.start.main).
987 if (D.isMain())
988 return false;
989
Rafael Espindola78eeba82012-12-28 14:21:58 +0000990 return true;
991}
992
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000993static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
994 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000995 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
996 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
997
998 // C++ [temp.fct]p2:
999 // A function template can be overloaded with other function templates
1000 // and with normal (non-template) functions.
1001 if ((OldTemplate == 0) != (NewTemplate == 0))
1002 return true;
1003
1004 // Is the function New an overload of the function Old?
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001005 QualType OldQType = S.Context.getCanonicalType(Old->getType());
1006 QualType NewQType = S.Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +00001007
1008 // Compare the signatures (C++ 1.3.10) of the two functions to
1009 // determine whether they are overloads. If we find any mismatch
1010 // in the signature, they are overloads.
1011
1012 // If either of these functions is a K&R-style function (no
1013 // prototype), then we consider them to have matching signatures.
1014 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1015 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1016 return false;
1017
John McCallf4c73712011-01-19 06:33:43 +00001018 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1019 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001020
1021 // The signature of a function includes the types of its
1022 // parameters (C++ 1.3.10), which includes the presence or absence
1023 // of the ellipsis; see C++ DR 357).
1024 if (OldQType != NewQType &&
1025 (OldType->getNumArgs() != NewType->getNumArgs() ||
1026 OldType->isVariadic() != NewType->isVariadic() ||
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001027 !S.FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001028 return true;
1029
1030 // C++ [temp.over.link]p4:
1031 // The signature of a function template consists of its function
1032 // signature, its return type and its template parameter list. The names
1033 // of the template parameters are significant only for establishing the
1034 // relationship between the template parameters and the rest of the
1035 // signature.
1036 //
1037 // We check the return type and template parameter lists for function
1038 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001039 //
1040 // However, we don't consider either of these when deciding whether
1041 // a member introduced by a shadow declaration is hidden.
1042 if (!UseUsingDeclRules && NewTemplate &&
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001043 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1044 OldTemplate->getTemplateParameters(),
1045 false, S.TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001046 OldType->getResultType() != NewType->getResultType()))
1047 return true;
1048
1049 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001050 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001051 //
1052 // As part of this, also check whether one of the member functions
1053 // is static, in which case they are not overloads (C++
1054 // 13.1p2). While not part of the definition of the signature,
1055 // this check is important to determine whether these functions
1056 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001057 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1058 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001059 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001060 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1061 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1062 if (!UseUsingDeclRules &&
1063 (OldMethod->getRefQualifier() == RQ_None ||
1064 NewMethod->getRefQualifier() == RQ_None)) {
1065 // C++0x [over.load]p2:
1066 // - Member function declarations with the same name and the same
1067 // parameter-type-list as well as member function template
1068 // declarations with the same name, the same parameter-type-list, and
1069 // the same template parameter lists cannot be overloaded if any of
1070 // them, but not all, have a ref-qualifier (8.3.5).
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001071 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001072 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001073 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001074 }
1075 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001077
Richard Smith21c8fa82013-01-14 05:37:29 +00001078 // We may not have applied the implicit const for a constexpr member
1079 // function yet (because we haven't yet resolved whether this is a static
1080 // or non-static member function). Add it now, on the assumption that this
1081 // is a redeclaration of OldMethod.
1082 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001083 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001084 NewQuals |= Qualifiers::Const;
1085 if (OldMethod->getTypeQualifiers() != NewQuals)
1086 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001087 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088
John McCall68263142009-11-18 22:49:29 +00001089 // The signatures match; this is not an overload.
1090 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001091}
1092
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001093bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1094 bool UseUsingDeclRules) {
1095 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1096 return false;
1097
1098 // If both of the functions are extern "C", then they are not
1099 // overloads.
1100 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1101 return false;
1102
1103 return true;
1104}
1105
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001106/// \brief Checks availability of the function depending on the current
1107/// function context. Inside an unavailable function, unavailability is ignored.
1108///
1109/// \returns true if \arg FD is unavailable and current context is inside
1110/// an available function, false otherwise.
1111bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1112 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1113}
1114
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001115/// \brief Tries a user-defined conversion from From to ToType.
1116///
1117/// Produces an implicit conversion sequence for when a standard conversion
1118/// is not an option. See TryImplicitConversion for more information.
1119static ImplicitConversionSequence
1120TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1121 bool SuppressUserConversions,
1122 bool AllowExplicit,
1123 bool InOverloadResolution,
1124 bool CStyle,
1125 bool AllowObjCWritebackConversion) {
1126 ImplicitConversionSequence ICS;
1127
1128 if (SuppressUserConversions) {
1129 // We're not in the case above, so there is no conversion that
1130 // we can perform.
1131 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1132 return ICS;
1133 }
1134
1135 // Attempt user-defined conversion.
1136 OverloadCandidateSet Conversions(From->getExprLoc());
1137 OverloadingResult UserDefResult
1138 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1139 AllowExplicit);
1140
1141 if (UserDefResult == OR_Success) {
1142 ICS.setUserDefined();
1143 // C++ [over.ics.user]p4:
1144 // A conversion of an expression of class type to the same class
1145 // type is given Exact Match rank, and a conversion of an
1146 // expression of class type to a base class of that type is
1147 // given Conversion rank, in spite of the fact that a copy
1148 // constructor (i.e., a user-defined conversion function) is
1149 // called for those cases.
1150 if (CXXConstructorDecl *Constructor
1151 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1152 QualType FromCanon
1153 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1154 QualType ToCanon
1155 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1156 if (Constructor->isCopyConstructor() &&
1157 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1158 // Turn this into a "standard" conversion sequence, so that it
1159 // gets ranked with standard conversion sequences.
1160 ICS.setStandard();
1161 ICS.Standard.setAsIdentityConversion();
1162 ICS.Standard.setFromType(From->getType());
1163 ICS.Standard.setAllToTypes(ToType);
1164 ICS.Standard.CopyConstructor = Constructor;
1165 if (ToCanon != FromCanon)
1166 ICS.Standard.Second = ICK_Derived_To_Base;
1167 }
1168 }
1169
1170 // C++ [over.best.ics]p4:
1171 // However, when considering the argument of a user-defined
1172 // conversion function that is a candidate by 13.3.1.3 when
1173 // invoked for the copying of the temporary in the second step
1174 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1175 // 13.3.1.6 in all cases, only standard conversion sequences and
1176 // ellipsis conversion sequences are allowed.
1177 if (SuppressUserConversions && ICS.isUserDefined()) {
1178 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1179 }
1180 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1181 ICS.setAmbiguous();
1182 ICS.Ambiguous.setFromType(From->getType());
1183 ICS.Ambiguous.setToType(ToType);
1184 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1185 Cand != Conversions.end(); ++Cand)
1186 if (Cand->Viable)
1187 ICS.Ambiguous.addConversion(Cand->Function);
1188 } else {
1189 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1190 }
1191
1192 return ICS;
1193}
1194
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001195/// TryImplicitConversion - Attempt to perform an implicit conversion
1196/// from the given expression (Expr) to the given type (ToType). This
1197/// function returns an implicit conversion sequence that can be used
1198/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001199///
1200/// void f(float f);
1201/// void g(int i) { f(i); }
1202///
1203/// this routine would produce an implicit conversion sequence to
1204/// describe the initialization of f from i, which will be a standard
1205/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1206/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1207//
1208/// Note that this routine only determines how the conversion can be
1209/// performed; it does not actually perform the conversion. As such,
1210/// it will not produce any diagnostics if no conversion is available,
1211/// but will instead return an implicit conversion sequence of kind
1212/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001213///
1214/// If @p SuppressUserConversions, then user-defined conversions are
1215/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001216/// If @p AllowExplicit, then explicit user-defined conversions are
1217/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001218///
1219/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1220/// writeback conversion, which allows __autoreleasing id* parameters to
1221/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001222static ImplicitConversionSequence
1223TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1224 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001225 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001226 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001227 bool CStyle,
1228 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001229 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001230 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001231 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001232 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001233 return ICS;
1234 }
1235
David Blaikie4e4d0842012-03-11 07:00:24 +00001236 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001237 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001238 return ICS;
1239 }
1240
Douglas Gregor604eb652010-08-11 02:15:33 +00001241 // C++ [over.ics.user]p4:
1242 // A conversion of an expression of class type to the same class
1243 // type is given Exact Match rank, and a conversion of an
1244 // expression of class type to a base class of that type is
1245 // given Conversion rank, in spite of the fact that a copy/move
1246 // constructor (i.e., a user-defined conversion function) is
1247 // called for those cases.
1248 QualType FromType = From->getType();
1249 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001250 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1251 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001252 ICS.setStandard();
1253 ICS.Standard.setAsIdentityConversion();
1254 ICS.Standard.setFromType(FromType);
1255 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001256
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001257 // We don't actually check at this point whether there is a valid
1258 // copy/move constructor, since overloading just assumes that it
1259 // exists. When we actually perform initialization, we'll find the
1260 // appropriate constructor to copy the returned object, if needed.
1261 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001262
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001263 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001264 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001265 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266
Douglas Gregor604eb652010-08-11 02:15:33 +00001267 return ICS;
1268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001269
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001270 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1271 AllowExplicit, InOverloadResolution, CStyle,
1272 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001273}
1274
John McCallf85e1932011-06-15 23:02:42 +00001275ImplicitConversionSequence
1276Sema::TryImplicitConversion(Expr *From, QualType ToType,
1277 bool SuppressUserConversions,
1278 bool AllowExplicit,
1279 bool InOverloadResolution,
1280 bool CStyle,
1281 bool AllowObjCWritebackConversion) {
1282 return clang::TryImplicitConversion(*this, From, ToType,
1283 SuppressUserConversions, AllowExplicit,
1284 InOverloadResolution, CStyle,
1285 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001286}
1287
Douglas Gregor575c63a2010-04-16 22:27:05 +00001288/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001289/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001290/// converted expression. Flavor is the kind of conversion we're
1291/// performing, used in the error message. If @p AllowExplicit,
1292/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001293ExprResult
1294Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001295 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001296 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001297 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001298}
1299
John Wiegley429bb272011-04-08 18:41:53 +00001300ExprResult
1301Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001302 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001303 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001304 if (checkPlaceholderForOverload(*this, From))
1305 return ExprError();
1306
John McCallf85e1932011-06-15 23:02:42 +00001307 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1308 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001309 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001310 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001311
John McCall120d63c2010-08-24 20:38:10 +00001312 ICS = clang::TryImplicitConversion(*this, From, ToType,
1313 /*SuppressUserConversions=*/false,
1314 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001315 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001316 /*CStyle=*/false,
1317 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001318 return PerformImplicitConversion(From, ToType, ICS, Action);
1319}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001320
1321/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001322/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001323bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1324 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001325 if (Context.hasSameUnqualifiedType(FromType, ToType))
1326 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001327
John McCall00ccbef2010-12-21 00:44:39 +00001328 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1329 // where F adds one of the following at most once:
1330 // - a pointer
1331 // - a member pointer
1332 // - a block pointer
1333 CanQualType CanTo = Context.getCanonicalType(ToType);
1334 CanQualType CanFrom = Context.getCanonicalType(FromType);
1335 Type::TypeClass TyClass = CanTo->getTypeClass();
1336 if (TyClass != CanFrom->getTypeClass()) return false;
1337 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1338 if (TyClass == Type::Pointer) {
1339 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1340 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1341 } else if (TyClass == Type::BlockPointer) {
1342 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1343 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1344 } else if (TyClass == Type::MemberPointer) {
1345 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1346 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1347 } else {
1348 return false;
1349 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001350
John McCall00ccbef2010-12-21 00:44:39 +00001351 TyClass = CanTo->getTypeClass();
1352 if (TyClass != CanFrom->getTypeClass()) return false;
1353 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1354 return false;
1355 }
1356
1357 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1358 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1359 if (!EInfo.getNoReturn()) return false;
1360
1361 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1362 assert(QualType(FromFn, 0).isCanonical());
1363 if (QualType(FromFn, 0) != CanTo) return false;
1364
1365 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001366 return true;
1367}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001368
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001369/// \brief Determine whether the conversion from FromType to ToType is a valid
1370/// vector conversion.
1371///
1372/// \param ICK Will be set to the vector conversion kind, if this is a vector
1373/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001374static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1375 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001376 // We need at least one of these types to be a vector type to have a vector
1377 // conversion.
1378 if (!ToType->isVectorType() && !FromType->isVectorType())
1379 return false;
1380
1381 // Identical types require no conversions.
1382 if (Context.hasSameUnqualifiedType(FromType, ToType))
1383 return false;
1384
1385 // There are no conversions between extended vector types, only identity.
1386 if (ToType->isExtVectorType()) {
1387 // There are no conversions between extended vector types other than the
1388 // identity conversion.
1389 if (FromType->isExtVectorType())
1390 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001391
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001392 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001393 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001394 ICK = ICK_Vector_Splat;
1395 return true;
1396 }
1397 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001398
1399 // We can perform the conversion between vector types in the following cases:
1400 // 1)vector types are equivalent AltiVec and GCC vector types
1401 // 2)lax vector conversions are permitted and the vector types are of the
1402 // same size
1403 if (ToType->isVectorType() && FromType->isVectorType()) {
1404 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001405 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001406 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001407 ICK = ICK_Vector_Conversion;
1408 return true;
1409 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001410 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001411
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001412 return false;
1413}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414
Douglas Gregor7d000652012-04-12 20:48:09 +00001415static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1416 bool InOverloadResolution,
1417 StandardConversionSequence &SCS,
1418 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001419
Douglas Gregor60d62c22008-10-31 16:23:19 +00001420/// IsStandardConversion - Determines whether there is a standard
1421/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1422/// expression From to the type ToType. Standard conversion sequences
1423/// only consider non-class types; for conversions that involve class
1424/// types, use TryImplicitConversion. If a conversion exists, SCS will
1425/// contain the standard conversion sequence required to perform this
1426/// conversion and this routine will return true. Otherwise, this
1427/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001428static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1429 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001430 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001431 bool CStyle,
1432 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001433 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001434
Douglas Gregor60d62c22008-10-31 16:23:19 +00001435 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001436 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001437 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001438 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001439 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001440 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001441
Douglas Gregorf9201e02009-02-11 23:02:49 +00001442 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001443 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001444 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001445 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001446 return false;
1447
Mike Stump1eb44332009-09-09 15:08:12 +00001448 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001449 }
1450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001451 // The first conversion can be an lvalue-to-rvalue conversion,
1452 // array-to-pointer conversion, or function-to-pointer conversion
1453 // (C++ 4p1).
1454
John McCall120d63c2010-08-24 20:38:10 +00001455 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001456 DeclAccessPair AccessPair;
1457 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001458 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001459 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001460 // We were able to resolve the address of the overloaded function,
1461 // so we can convert to the type of that function.
1462 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001463
1464 // we can sometimes resolve &foo<int> regardless of ToType, so check
1465 // if the type matches (identity) or we are converting to bool
1466 if (!S.Context.hasSameUnqualifiedType(
1467 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1468 QualType resultTy;
1469 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001470 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001471 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1472 // otherwise, only a boolean conversion is standard
1473 if (!ToType->isBooleanType())
1474 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001476
Chandler Carruth90434232011-03-29 08:08:18 +00001477 // Check if the "from" expression is taking the address of an overloaded
1478 // function and recompute the FromType accordingly. Take advantage of the
1479 // fact that non-static member functions *must* have such an address-of
1480 // expression.
1481 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1482 if (Method && !Method->isStatic()) {
1483 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1484 "Non-unary operator on non-static member address");
1485 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1486 == UO_AddrOf &&
1487 "Non-address-of operator on non-static member address");
1488 const Type *ClassType
1489 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1490 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001491 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1492 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1493 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001494 "Non-address-of operator for overloaded function expression");
1495 FromType = S.Context.getPointerType(FromType);
1496 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001498 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001499 assert(S.Context.hasSameType(
1500 FromType,
1501 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001502 } else {
1503 return false;
1504 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001505 }
John McCall21480112011-08-30 00:57:29 +00001506 // Lvalue-to-rvalue conversion (C++11 4.1):
1507 // A glvalue (3.10) of a non-function, non-array type T can
1508 // be converted to a prvalue.
1509 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001510 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001511 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001512 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001513 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001514
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001515 // C11 6.3.2.1p2:
1516 // ... if the lvalue has atomic type, the value has the non-atomic version
1517 // of the type of the lvalue ...
1518 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1519 FromType = Atomic->getValueType();
1520
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001521 // If T is a non-class type, the type of the rvalue is the
1522 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001523 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1524 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001525 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001526 } else if (FromType->isArrayType()) {
1527 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001528 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001529
1530 // An lvalue or rvalue of type "array of N T" or "array of unknown
1531 // bound of T" can be converted to an rvalue of type "pointer to
1532 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001533 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001534
John McCall120d63c2010-08-24 20:38:10 +00001535 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001536 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001537 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001538
1539 // For the purpose of ranking in overload resolution
1540 // (13.3.3.1.1), this conversion is considered an
1541 // array-to-pointer conversion followed by a qualification
1542 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001543 SCS.Second = ICK_Identity;
1544 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001545 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001546 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001547 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001548 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001549 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001550 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001551 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552
1553 // An lvalue of function type T can be converted to an rvalue of
1554 // type "pointer to T." The result is a pointer to the
1555 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001556 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001557 } else {
1558 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001559 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001560 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001561 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001562
1563 // The second conversion can be an integral promotion, floating
1564 // point promotion, integral conversion, floating point conversion,
1565 // floating-integral conversion, pointer conversion,
1566 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001567 // For overloading in C, this can also be a "compatible-type"
1568 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001569 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001570 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001571 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001572 // The unqualified versions of the types are the same: there's no
1573 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001574 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001575 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001576 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001577 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001578 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001579 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001580 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001581 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001582 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001583 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001584 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001585 SCS.Second = ICK_Complex_Promotion;
1586 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001587 } else if (ToType->isBooleanType() &&
1588 (FromType->isArithmeticType() ||
1589 FromType->isAnyPointerType() ||
1590 FromType->isBlockPointerType() ||
1591 FromType->isMemberPointerType() ||
1592 FromType->isNullPtrType())) {
1593 // Boolean conversions (C++ 4.12).
1594 SCS.Second = ICK_Boolean_Conversion;
1595 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001596 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001597 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001598 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001599 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001600 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001601 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001602 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001603 SCS.Second = ICK_Complex_Conversion;
1604 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001605 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1606 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001607 // Complex-real conversions (C99 6.3.1.7)
1608 SCS.Second = ICK_Complex_Real;
1609 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001610 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001611 // Floating point conversions (C++ 4.8).
1612 SCS.Second = ICK_Floating_Conversion;
1613 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001614 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001615 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001616 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001617 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001618 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001619 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001620 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001621 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001622 SCS.Second = ICK_Block_Pointer_Conversion;
1623 } else if (AllowObjCWritebackConversion &&
1624 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1625 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001626 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1627 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001628 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001629 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001630 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001631 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001632 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001633 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001634 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001635 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001636 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001637 SCS.Second = SecondICK;
1638 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001639 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001640 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001641 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001642 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001643 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001644 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001645 // Treat a conversion that strips "noreturn" as an identity conversion.
1646 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001647 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1648 InOverloadResolution,
1649 SCS, CStyle)) {
1650 SCS.Second = ICK_TransparentUnionConversion;
1651 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001652 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1653 CStyle)) {
1654 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001655 // appropriately.
1656 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001657 } else if (ToType->isEventT() &&
1658 From->isIntegerConstantExpr(S.getASTContext()) &&
1659 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1660 SCS.Second = ICK_Zero_Event_Conversion;
1661 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001662 } else {
1663 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001664 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001666 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001668 QualType CanonFrom;
1669 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001671 bool ObjCLifetimeConversion;
1672 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1673 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001674 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001675 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001677 CanonFrom = S.Context.getCanonicalType(FromType);
1678 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001679 } else {
1680 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001681 SCS.Third = ICK_Identity;
1682
Mike Stump1eb44332009-09-09 15:08:12 +00001683 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001684 // [...] Any difference in top-level cv-qualification is
1685 // subsumed by the initialization itself and does not constitute
1686 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001687 CanonFrom = S.Context.getCanonicalType(FromType);
1688 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001689 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001690 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001691 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001692 FromType = ToType;
1693 CanonFrom = CanonTo;
1694 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001695 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001696 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001697
1698 // If we have not converted the argument type to the parameter type,
1699 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001700 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001701 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001702
Douglas Gregor60d62c22008-10-31 16:23:19 +00001703 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001704}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001705
1706static bool
1707IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1708 QualType &ToType,
1709 bool InOverloadResolution,
1710 StandardConversionSequence &SCS,
1711 bool CStyle) {
1712
1713 const RecordType *UT = ToType->getAsUnionType();
1714 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1715 return false;
1716 // The field to initialize within the transparent union.
1717 RecordDecl *UD = UT->getDecl();
1718 // It's compatible if the expression matches any of the fields.
1719 for (RecordDecl::field_iterator it = UD->field_begin(),
1720 itend = UD->field_end();
1721 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001722 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1723 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001724 ToType = it->getType();
1725 return true;
1726 }
1727 }
1728 return false;
1729}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001730
1731/// IsIntegralPromotion - Determines whether the conversion from the
1732/// expression From (whose potentially-adjusted type is FromType) to
1733/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1734/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001735bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001736 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001737 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001738 if (!To) {
1739 return false;
1740 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001741
1742 // An rvalue of type char, signed char, unsigned char, short int, or
1743 // unsigned short int can be converted to an rvalue of type int if
1744 // int can represent all the values of the source type; otherwise,
1745 // the source rvalue can be converted to an rvalue of type unsigned
1746 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001747 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1748 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001749 if (// We can promote any signed, promotable integer type to an int
1750 (FromType->isSignedIntegerType() ||
1751 // We can promote any unsigned integer type whose size is
1752 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001753 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001754 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001755 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001756 }
1757
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001758 return To->getKind() == BuiltinType::UInt;
1759 }
1760
Richard Smithe7ff9192012-09-13 21:18:54 +00001761 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001762 // A prvalue of an unscoped enumeration type whose underlying type is not
1763 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1764 // following types that can represent all the values of the enumeration
1765 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1766 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001767 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001768 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001769 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001770 // with lowest integer conversion rank (4.13) greater than the rank of long
1771 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001772 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001773 // C++11 [conv.prom]p4:
1774 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1775 // can be converted to a prvalue of its underlying type. Moreover, if
1776 // integral promotion can be applied to its underlying type, a prvalue of an
1777 // unscoped enumeration type whose underlying type is fixed can also be
1778 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001779 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1780 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1781 // provided for a scoped enumeration.
1782 if (FromEnumType->getDecl()->isScoped())
1783 return false;
1784
Richard Smithe7ff9192012-09-13 21:18:54 +00001785 // We can perform an integral promotion to the underlying type of the enum,
1786 // even if that's not the promoted type.
1787 if (FromEnumType->getDecl()->isFixed()) {
1788 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1789 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1790 IsIntegralPromotion(From, Underlying, ToType);
1791 }
1792
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001793 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001795 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001796 return Context.hasSameUnqualifiedType(ToType,
1797 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001798 }
John McCall842aef82009-12-09 09:09:27 +00001799
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001800 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001801 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1802 // to an rvalue a prvalue of the first of the following types that can
1803 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001804 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001805 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001806 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001807 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001808 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001809 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001810 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001811 // Determine whether the type we're converting from is signed or
1812 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001813 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001814 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001815
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001816 // The types we'll try to promote to, in the appropriate
1817 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001818 QualType PromoteTypes[6] = {
1819 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001820 Context.LongTy, Context.UnsignedLongTy ,
1821 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001822 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001823 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001824 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1825 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001826 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001827 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1828 // We found the type that we can promote to. If this is the
1829 // type we wanted, we have a promotion. Otherwise, no
1830 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001831 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001832 }
1833 }
1834 }
1835
1836 // An rvalue for an integral bit-field (9.6) can be converted to an
1837 // rvalue of type int if int can represent all the values of the
1838 // bit-field; otherwise, it can be converted to unsigned int if
1839 // unsigned int can represent all the values of the bit-field. If
1840 // the bit-field is larger yet, no integral promotion applies to
1841 // it. If the bit-field has an enumerated type, it is treated as any
1842 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001843 // FIXME: We should delay checking of bit-fields until we actually perform the
1844 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001845 using llvm::APSInt;
1846 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001847 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001848 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001849 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001850 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1851 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1852 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Douglas Gregor86f19402008-12-20 23:49:58 +00001854 // Are we promoting to an int from a bitfield that fits in an int?
1855 if (BitWidth < ToSize ||
1856 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1857 return To->getKind() == BuiltinType::Int;
1858 }
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Douglas Gregor86f19402008-12-20 23:49:58 +00001860 // Are we promoting to an unsigned int from an unsigned bitfield
1861 // that fits into an unsigned int?
1862 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1863 return To->getKind() == BuiltinType::UInt;
1864 }
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Douglas Gregor86f19402008-12-20 23:49:58 +00001866 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001867 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001868 }
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001870 // An rvalue of type bool can be converted to an rvalue of type int,
1871 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001872 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001873 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001874 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001875
1876 return false;
1877}
1878
1879/// IsFloatingPointPromotion - Determines whether the conversion from
1880/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1881/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001882bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001883 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1884 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001885 /// An rvalue of type float can be converted to an rvalue of type
1886 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001887 if (FromBuiltin->getKind() == BuiltinType::Float &&
1888 ToBuiltin->getKind() == BuiltinType::Double)
1889 return true;
1890
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001891 // C99 6.3.1.5p1:
1892 // When a float is promoted to double or long double, or a
1893 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001894 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001895 (FromBuiltin->getKind() == BuiltinType::Float ||
1896 FromBuiltin->getKind() == BuiltinType::Double) &&
1897 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1898 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001899
1900 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001901 if (!getLangOpts().NativeHalfType &&
1902 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001903 ToBuiltin->getKind() == BuiltinType::Float)
1904 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001905 }
1906
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001907 return false;
1908}
1909
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001910/// \brief Determine if a conversion is a complex promotion.
1911///
1912/// A complex promotion is defined as a complex -> complex conversion
1913/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001914/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001915bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001916 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001917 if (!FromComplex)
1918 return false;
1919
John McCall183700f2009-09-21 23:43:11 +00001920 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001921 if (!ToComplex)
1922 return false;
1923
1924 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001925 ToComplex->getElementType()) ||
1926 IsIntegralPromotion(0, FromComplex->getElementType(),
1927 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001928}
1929
Douglas Gregorcb7de522008-11-26 23:31:11 +00001930/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1931/// the pointer type FromPtr to a pointer to type ToPointee, with the
1932/// same type qualifiers as FromPtr has on its pointee type. ToType,
1933/// if non-empty, will be a pointer to ToType that may or may not have
1934/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001935///
Mike Stump1eb44332009-09-09 15:08:12 +00001936static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001937BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001938 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001939 ASTContext &Context,
1940 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001941 assert((FromPtr->getTypeClass() == Type::Pointer ||
1942 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1943 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001944
John McCallf85e1932011-06-15 23:02:42 +00001945 /// Conversions to 'id' subsume cv-qualifier conversions.
1946 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001947 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001948
1949 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001950 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001951 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001952 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001953
John McCallf85e1932011-06-15 23:02:42 +00001954 if (StripObjCLifetime)
1955 Quals.removeObjCLifetime();
1956
Mike Stump1eb44332009-09-09 15:08:12 +00001957 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001958 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001959 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001960 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001961 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001962
1963 // Build a pointer to ToPointee. It has the right qualifiers
1964 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001965 if (isa<ObjCObjectPointerType>(ToType))
1966 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001967 return Context.getPointerType(ToPointee);
1968 }
1969
1970 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001971 QualType QualifiedCanonToPointee
1972 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001973
Douglas Gregorda80f742010-12-01 21:43:58 +00001974 if (isa<ObjCObjectPointerType>(ToType))
1975 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1976 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001977}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001978
Mike Stump1eb44332009-09-09 15:08:12 +00001979static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001980 bool InOverloadResolution,
1981 ASTContext &Context) {
1982 // Handle value-dependent integral null pointer constants correctly.
1983 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1984 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001985 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001986 return !InOverloadResolution;
1987
Douglas Gregorce940492009-09-25 04:25:58 +00001988 return Expr->isNullPointerConstant(Context,
1989 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1990 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001991}
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001993/// IsPointerConversion - Determines whether the conversion of the
1994/// expression From, which has the (possibly adjusted) type FromType,
1995/// can be converted to the type ToType via a pointer conversion (C++
1996/// 4.10). If so, returns true and places the converted type (that
1997/// might differ from ToType in its cv-qualifiers at some level) into
1998/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001999///
Douglas Gregor7ca09762008-11-27 01:19:21 +00002000/// This routine also supports conversions to and from block pointers
2001/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2002/// pointers to interfaces. FIXME: Once we've determined the
2003/// appropriate overloading rules for Objective-C, we may want to
2004/// split the Objective-C checks into a different routine; however,
2005/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00002006/// conversions, so for now they live here. IncompatibleObjC will be
2007/// set if the conversion is an allowed Objective-C conversion that
2008/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002009bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00002010 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00002011 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00002012 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002013 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002014 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2015 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002016 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002017
Mike Stump1eb44332009-09-09 15:08:12 +00002018 // Conversion from a null pointer constant to any Objective-C pointer type.
2019 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002020 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002021 ConvertedType = ToType;
2022 return true;
2023 }
2024
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002025 // Blocks: Block pointers can be converted to void*.
2026 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002027 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002028 ConvertedType = ToType;
2029 return true;
2030 }
2031 // Blocks: A null pointer constant can be converted to a block
2032 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002033 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002034 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002035 ConvertedType = ToType;
2036 return true;
2037 }
2038
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002039 // If the left-hand-side is nullptr_t, the right side can be a null
2040 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002041 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002042 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002043 ConvertedType = ToType;
2044 return true;
2045 }
2046
Ted Kremenek6217b802009-07-29 21:53:49 +00002047 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002048 if (!ToTypePtr)
2049 return false;
2050
2051 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002052 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002053 ConvertedType = ToType;
2054 return true;
2055 }
Sebastian Redl07779722008-10-31 14:43:28 +00002056
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002057 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002058 // , including objective-c pointers.
2059 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002060 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002061 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002062 ConvertedType = BuildSimilarlyQualifiedPointerType(
2063 FromType->getAs<ObjCObjectPointerType>(),
2064 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002065 ToType, Context);
2066 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002067 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002068 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002069 if (!FromTypePtr)
2070 return false;
2071
2072 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002073
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002074 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002075 // pointer conversion, so don't do all of the work below.
2076 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2077 return false;
2078
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002079 // An rvalue of type "pointer to cv T," where T is an object type,
2080 // can be converted to an rvalue of type "pointer to cv void" (C++
2081 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002082 if (FromPointeeType->isIncompleteOrObjectType() &&
2083 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002085 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002086 ToType, Context,
2087 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002088 return true;
2089 }
2090
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002091 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002092 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002093 ToPointeeType->isVoidType()) {
2094 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2095 ToPointeeType,
2096 ToType, Context);
2097 return true;
2098 }
2099
Douglas Gregorf9201e02009-02-11 23:02:49 +00002100 // When we're overloading in C, we allow a special kind of pointer
2101 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002102 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002103 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002104 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002105 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002106 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002107 return true;
2108 }
2109
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002110 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002111 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002112 // An rvalue of type "pointer to cv D," where D is a class type,
2113 // can be converted to an rvalue of type "pointer to cv B," where
2114 // B is a base class (clause 10) of D. If B is an inaccessible
2115 // (clause 11) or ambiguous (10.2) base class of D, a program that
2116 // necessitates this conversion is ill-formed. The result of the
2117 // conversion is a pointer to the base class sub-object of the
2118 // derived class object. The null pointer value is converted to
2119 // the null pointer value of the destination type.
2120 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002121 // Note that we do not check for ambiguity or inaccessibility
2122 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002123 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002124 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002125 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002126 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002127 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002128 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002129 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002130 ToType, Context);
2131 return true;
2132 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002133
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002134 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2135 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2137 ToPointeeType,
2138 ToType, Context);
2139 return true;
2140 }
2141
Douglas Gregorc7887512008-12-19 19:13:09 +00002142 return false;
2143}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002144
2145/// \brief Adopt the given qualifiers for the given type.
2146static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2147 Qualifiers TQs = T.getQualifiers();
2148
2149 // Check whether qualifiers already match.
2150 if (TQs == Qs)
2151 return T;
2152
2153 if (Qs.compatiblyIncludes(TQs))
2154 return Context.getQualifiedType(T, Qs);
2155
2156 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2157}
Douglas Gregorc7887512008-12-19 19:13:09 +00002158
2159/// isObjCPointerConversion - Determines whether this is an
2160/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2161/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002162bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002163 QualType& ConvertedType,
2164 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002165 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002166 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002167
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002168 // The set of qualifiers on the type we're converting from.
2169 Qualifiers FromQualifiers = FromType.getQualifiers();
2170
Steve Naroff14108da2009-07-10 23:34:53 +00002171 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002172 const ObjCObjectPointerType* ToObjCPtr =
2173 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002174 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002175 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002176
Steve Naroff14108da2009-07-10 23:34:53 +00002177 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002178 // If the pointee types are the same (ignoring qualifications),
2179 // then this is not a pointer conversion.
2180 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2181 FromObjCPtr->getPointeeType()))
2182 return false;
2183
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002184 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002185 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002186 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002187 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002189 return true;
2190 }
2191 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002192 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002193 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002194 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002195 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002196 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002197 return true;
2198 }
2199 // Objective C++: We're able to convert from a pointer to an
2200 // interface to a pointer to a different interface.
2201 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002202 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2203 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002204 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002205 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2206 FromObjCPtr->getPointeeType()))
2207 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002209 ToObjCPtr->getPointeeType(),
2210 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002211 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002212 return true;
2213 }
2214
2215 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2216 // Okay: this is some kind of implicit downcast of Objective-C
2217 // interfaces, which is permitted. However, we're going to
2218 // complain about it.
2219 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002220 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002221 ToObjCPtr->getPointeeType(),
2222 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002224 return true;
2225 }
Mike Stump1eb44332009-09-09 15:08:12 +00002226 }
Steve Naroff14108da2009-07-10 23:34:53 +00002227 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002228 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002229 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002230 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002231 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002232 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002233 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002234 // to a block pointer type.
2235 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002237 return true;
2238 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002239 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002240 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002241 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002242 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002243 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002244 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002245 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002246 return true;
2247 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002248 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002249 return false;
2250
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002251 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002252 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002253 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002254 else if (const BlockPointerType *FromBlockPtr =
2255 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002256 FromPointeeType = FromBlockPtr->getPointeeType();
2257 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002258 return false;
2259
Douglas Gregorc7887512008-12-19 19:13:09 +00002260 // If we have pointers to pointers, recursively check whether this
2261 // is an Objective-C conversion.
2262 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2263 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2264 IncompatibleObjC)) {
2265 // We always complain about this conversion.
2266 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002267 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002268 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002269 return true;
2270 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002271 // Allow conversion of pointee being objective-c pointer to another one;
2272 // as in I* to id.
2273 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2274 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2275 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2276 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002277
Douglas Gregorda80f742010-12-01 21:43:58 +00002278 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002279 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002280 return true;
2281 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002282
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002283 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002284 // differences in the argument and result types are in Objective-C
2285 // pointer conversions. If so, we permit the conversion (but
2286 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002287 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002288 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002289 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002290 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002291 if (FromFunctionType && ToFunctionType) {
2292 // If the function types are exactly the same, this isn't an
2293 // Objective-C pointer conversion.
2294 if (Context.getCanonicalType(FromPointeeType)
2295 == Context.getCanonicalType(ToPointeeType))
2296 return false;
2297
2298 // Perform the quick checks that will tell us whether these
2299 // function types are obviously different.
2300 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2301 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2302 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2303 return false;
2304
2305 bool HasObjCConversion = false;
2306 if (Context.getCanonicalType(FromFunctionType->getResultType())
2307 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2308 // Okay, the types match exactly. Nothing to do.
2309 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2310 ToFunctionType->getResultType(),
2311 ConvertedType, IncompatibleObjC)) {
2312 // Okay, we have an Objective-C pointer conversion.
2313 HasObjCConversion = true;
2314 } else {
2315 // Function types are too different. Abort.
2316 return false;
2317 }
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Douglas Gregorc7887512008-12-19 19:13:09 +00002319 // Check argument types.
2320 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2321 ArgIdx != NumArgs; ++ArgIdx) {
2322 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2323 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2324 if (Context.getCanonicalType(FromArgType)
2325 == Context.getCanonicalType(ToArgType)) {
2326 // Okay, the types match exactly. Nothing to do.
2327 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2328 ConvertedType, IncompatibleObjC)) {
2329 // Okay, we have an Objective-C pointer conversion.
2330 HasObjCConversion = true;
2331 } else {
2332 // Argument types are too different. Abort.
2333 return false;
2334 }
2335 }
2336
2337 if (HasObjCConversion) {
2338 // We had an Objective-C conversion. Allow this pointer
2339 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002340 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002341 IncompatibleObjC = true;
2342 return true;
2343 }
2344 }
2345
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002346 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002347}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002348
John McCallf85e1932011-06-15 23:02:42 +00002349/// \brief Determine whether this is an Objective-C writeback conversion,
2350/// used for parameter passing when performing automatic reference counting.
2351///
2352/// \param FromType The type we're converting form.
2353///
2354/// \param ToType The type we're converting to.
2355///
2356/// \param ConvertedType The type that will be produced after applying
2357/// this conversion.
2358bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2359 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002360 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002361 Context.hasSameUnqualifiedType(FromType, ToType))
2362 return false;
2363
2364 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2365 QualType ToPointee;
2366 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2367 ToPointee = ToPointer->getPointeeType();
2368 else
2369 return false;
2370
2371 Qualifiers ToQuals = ToPointee.getQualifiers();
2372 if (!ToPointee->isObjCLifetimeType() ||
2373 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002374 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002375 return false;
2376
2377 // Argument must be a pointer to __strong to __weak.
2378 QualType FromPointee;
2379 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2380 FromPointee = FromPointer->getPointeeType();
2381 else
2382 return false;
2383
2384 Qualifiers FromQuals = FromPointee.getQualifiers();
2385 if (!FromPointee->isObjCLifetimeType() ||
2386 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2387 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2388 return false;
2389
2390 // Make sure that we have compatible qualifiers.
2391 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2392 if (!ToQuals.compatiblyIncludes(FromQuals))
2393 return false;
2394
2395 // Remove qualifiers from the pointee type we're converting from; they
2396 // aren't used in the compatibility check belong, and we'll be adding back
2397 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2398 FromPointee = FromPointee.getUnqualifiedType();
2399
2400 // The unqualified form of the pointee types must be compatible.
2401 ToPointee = ToPointee.getUnqualifiedType();
2402 bool IncompatibleObjC;
2403 if (Context.typesAreCompatible(FromPointee, ToPointee))
2404 FromPointee = ToPointee;
2405 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2406 IncompatibleObjC))
2407 return false;
2408
2409 /// \brief Construct the type we're converting to, which is a pointer to
2410 /// __autoreleasing pointee.
2411 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2412 ConvertedType = Context.getPointerType(FromPointee);
2413 return true;
2414}
2415
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002416bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2417 QualType& ConvertedType) {
2418 QualType ToPointeeType;
2419 if (const BlockPointerType *ToBlockPtr =
2420 ToType->getAs<BlockPointerType>())
2421 ToPointeeType = ToBlockPtr->getPointeeType();
2422 else
2423 return false;
2424
2425 QualType FromPointeeType;
2426 if (const BlockPointerType *FromBlockPtr =
2427 FromType->getAs<BlockPointerType>())
2428 FromPointeeType = FromBlockPtr->getPointeeType();
2429 else
2430 return false;
2431 // We have pointer to blocks, check whether the only
2432 // differences in the argument and result types are in Objective-C
2433 // pointer conversions. If so, we permit the conversion.
2434
2435 const FunctionProtoType *FromFunctionType
2436 = FromPointeeType->getAs<FunctionProtoType>();
2437 const FunctionProtoType *ToFunctionType
2438 = ToPointeeType->getAs<FunctionProtoType>();
2439
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002440 if (!FromFunctionType || !ToFunctionType)
2441 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002442
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002443 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002444 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002445
2446 // Perform the quick checks that will tell us whether these
2447 // function types are obviously different.
2448 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2449 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2450 return false;
2451
2452 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2453 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2454 if (FromEInfo != ToEInfo)
2455 return false;
2456
2457 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002458 if (Context.hasSameType(FromFunctionType->getResultType(),
2459 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002460 // Okay, the types match exactly. Nothing to do.
2461 } else {
2462 QualType RHS = FromFunctionType->getResultType();
2463 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002464 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002465 !RHS.hasQualifiers() && LHS.hasQualifiers())
2466 LHS = LHS.getUnqualifiedType();
2467
2468 if (Context.hasSameType(RHS,LHS)) {
2469 // OK exact match.
2470 } else if (isObjCPointerConversion(RHS, LHS,
2471 ConvertedType, IncompatibleObjC)) {
2472 if (IncompatibleObjC)
2473 return false;
2474 // Okay, we have an Objective-C pointer conversion.
2475 }
2476 else
2477 return false;
2478 }
2479
2480 // Check argument types.
2481 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2482 ArgIdx != NumArgs; ++ArgIdx) {
2483 IncompatibleObjC = false;
2484 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2485 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2486 if (Context.hasSameType(FromArgType, ToArgType)) {
2487 // Okay, the types match exactly. Nothing to do.
2488 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2489 ConvertedType, IncompatibleObjC)) {
2490 if (IncompatibleObjC)
2491 return false;
2492 // Okay, we have an Objective-C pointer conversion.
2493 } else
2494 // Argument types are too different. Abort.
2495 return false;
2496 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002497 if (LangOpts.ObjCAutoRefCount &&
2498 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2499 ToFunctionType))
2500 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002501
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002502 ConvertedType = ToType;
2503 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002504}
2505
Richard Trieu6efd4c52011-11-23 22:32:32 +00002506enum {
2507 ft_default,
2508 ft_different_class,
2509 ft_parameter_arity,
2510 ft_parameter_mismatch,
2511 ft_return_type,
2512 ft_qualifer_mismatch
2513};
2514
2515/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2516/// function types. Catches different number of parameter, mismatch in
2517/// parameter types, and different return types.
2518void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2519 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002520 // If either type is not valid, include no extra info.
2521 if (FromType.isNull() || ToType.isNull()) {
2522 PDiag << ft_default;
2523 return;
2524 }
2525
Richard Trieu6efd4c52011-11-23 22:32:32 +00002526 // Get the function type from the pointers.
2527 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2528 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2529 *ToMember = ToType->getAs<MemberPointerType>();
2530 if (FromMember->getClass() != ToMember->getClass()) {
2531 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2532 << QualType(FromMember->getClass(), 0);
2533 return;
2534 }
2535 FromType = FromMember->getPointeeType();
2536 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002537 }
2538
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002539 if (FromType->isPointerType())
2540 FromType = FromType->getPointeeType();
2541 if (ToType->isPointerType())
2542 ToType = ToType->getPointeeType();
2543
2544 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002545 FromType = FromType.getNonReferenceType();
2546 ToType = ToType.getNonReferenceType();
2547
Richard Trieu6efd4c52011-11-23 22:32:32 +00002548 // Don't print extra info for non-specialized template functions.
2549 if (FromType->isInstantiationDependentType() &&
2550 !FromType->getAs<TemplateSpecializationType>()) {
2551 PDiag << ft_default;
2552 return;
2553 }
2554
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002555 // No extra info for same types.
2556 if (Context.hasSameType(FromType, ToType)) {
2557 PDiag << ft_default;
2558 return;
2559 }
2560
Richard Trieu6efd4c52011-11-23 22:32:32 +00002561 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2562 *ToFunction = ToType->getAs<FunctionProtoType>();
2563
2564 // Both types need to be function types.
2565 if (!FromFunction || !ToFunction) {
2566 PDiag << ft_default;
2567 return;
2568 }
2569
2570 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2571 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2572 << FromFunction->getNumArgs();
2573 return;
2574 }
2575
2576 // Handle different parameter types.
2577 unsigned ArgPos;
2578 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2579 PDiag << ft_parameter_mismatch << ArgPos + 1
2580 << ToFunction->getArgType(ArgPos)
2581 << FromFunction->getArgType(ArgPos);
2582 return;
2583 }
2584
2585 // Handle different return type.
2586 if (!Context.hasSameType(FromFunction->getResultType(),
2587 ToFunction->getResultType())) {
2588 PDiag << ft_return_type << ToFunction->getResultType()
2589 << FromFunction->getResultType();
2590 return;
2591 }
2592
2593 unsigned FromQuals = FromFunction->getTypeQuals(),
2594 ToQuals = ToFunction->getTypeQuals();
2595 if (FromQuals != ToQuals) {
2596 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2597 return;
2598 }
2599
2600 // Unable to find a difference, so add no extra info.
2601 PDiag << ft_default;
2602}
2603
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002604/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002605/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002606/// they have same number of arguments. If the parameters are different,
2607/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002608bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002609 const FunctionProtoType *NewType,
2610 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002611 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2612 N = NewType->arg_type_begin(),
2613 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Eli Friedman06017002013-06-18 22:41:37 +00002614 if (!Context.hasSameType(*O, *N)) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002615 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002617 }
2618 }
2619 return true;
2620}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002621
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002622/// CheckPointerConversion - Check the pointer conversion from the
2623/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002624/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002625/// conversions for which IsPointerConversion has already returned
2626/// true. It returns true and produces a diagnostic if there was an
2627/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002628bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002629 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002630 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002631 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002632 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002633 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002634
John McCalldaa8e4e2010-11-15 09:13:47 +00002635 Kind = CK_BitCast;
2636
David Blaikie50800fc2012-08-08 17:33:31 +00002637 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2638 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2639 Expr::NPCK_ZeroExpression) {
2640 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2641 DiagRuntimeBehavior(From->getExprLoc(), From,
2642 PDiag(diag::warn_impcast_bool_to_null_pointer)
2643 << ToType << From->getSourceRange());
2644 else if (!isUnevaluatedContext())
2645 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2646 << ToType << From->getSourceRange();
2647 }
John McCall1d9b3b22011-09-09 05:25:32 +00002648 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2649 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002650 QualType FromPointeeType = FromPtrType->getPointeeType(),
2651 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002652
Douglas Gregor5fccd362010-03-03 23:55:11 +00002653 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2654 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002655 // We must have a derived-to-base conversion. Check an
2656 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002657 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2658 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002659 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002660 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002661 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002662
Anders Carlsson61faec12009-09-12 04:46:44 +00002663 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002664 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002665 }
2666 }
John McCall1d9b3b22011-09-09 05:25:32 +00002667 } else if (const ObjCObjectPointerType *ToPtrType =
2668 ToType->getAs<ObjCObjectPointerType>()) {
2669 if (const ObjCObjectPointerType *FromPtrType =
2670 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002671 // Objective-C++ conversions are always okay.
2672 // FIXME: We should have a different class of conversions for the
2673 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002674 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002675 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002676 } else if (FromType->isBlockPointerType()) {
2677 Kind = CK_BlockPointerToObjCPointerCast;
2678 } else {
2679 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002680 }
John McCall1d9b3b22011-09-09 05:25:32 +00002681 } else if (ToType->isBlockPointerType()) {
2682 if (!FromType->isBlockPointerType())
2683 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002684 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002685
2686 // We shouldn't fall into this case unless it's valid for other
2687 // reasons.
2688 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2689 Kind = CK_NullToPointer;
2690
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002691 return false;
2692}
2693
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002694/// IsMemberPointerConversion - Determines whether the conversion of the
2695/// expression From, which has the (possibly adjusted) type FromType, can be
2696/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2697/// If so, returns true and places the converted type (that might differ from
2698/// ToType in its cv-qualifiers at some level) into ConvertedType.
2699bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002701 bool InOverloadResolution,
2702 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002703 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002704 if (!ToTypePtr)
2705 return false;
2706
2707 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002708 if (From->isNullPointerConstant(Context,
2709 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2710 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002711 ConvertedType = ToType;
2712 return true;
2713 }
2714
2715 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002716 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002717 if (!FromTypePtr)
2718 return false;
2719
2720 // A pointer to member of B can be converted to a pointer to member of D,
2721 // where D is derived from B (C++ 4.11p2).
2722 QualType FromClass(FromTypePtr->getClass(), 0);
2723 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002724
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002725 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002726 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002727 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002728 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2729 ToClass.getTypePtr());
2730 return true;
2731 }
2732
2733 return false;
2734}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002735
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002736/// CheckMemberPointerConversion - Check the member pointer conversion from the
2737/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002738/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002739/// for which IsMemberPointerConversion has already returned true. It returns
2740/// true and produces a diagnostic if there was an error, or returns false
2741/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002742bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002743 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002744 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002745 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002746 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002747 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002748 if (!FromPtrType) {
2749 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002750 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002751 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002752 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002753 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002754 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002755 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002756
Ted Kremenek6217b802009-07-29 21:53:49 +00002757 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002758 assert(ToPtrType && "No member pointer cast has a target type "
2759 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002760
Sebastian Redl21593ac2009-01-28 18:33:18 +00002761 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2762 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002763
Sebastian Redl21593ac2009-01-28 18:33:18 +00002764 // FIXME: What about dependent types?
2765 assert(FromClass->isRecordType() && "Pointer into non-class.");
2766 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002767
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002768 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002769 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002770 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2771 assert(DerivationOkay &&
2772 "Should not have been called if derivation isn't OK.");
2773 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002774
Sebastian Redl21593ac2009-01-28 18:33:18 +00002775 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2776 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002777 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2778 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2779 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2780 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002781 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002782
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002783 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002784 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2785 << FromClass << ToClass << QualType(VBase, 0)
2786 << From->getSourceRange();
2787 return true;
2788 }
2789
John McCall6b2accb2010-02-10 09:31:12 +00002790 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002791 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2792 Paths.front(),
2793 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002794
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002795 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002796 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002797 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002798 return false;
2799}
2800
Douglas Gregor98cd5992008-10-21 23:43:52 +00002801/// IsQualificationConversion - Determines whether the conversion from
2802/// an rvalue of type FromType to ToType is a qualification conversion
2803/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002804///
2805/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2806/// when the qualification conversion involves a change in the Objective-C
2807/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002808bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002809Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002810 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002811 FromType = Context.getCanonicalType(FromType);
2812 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002813 ObjCLifetimeConversion = false;
2814
Douglas Gregor98cd5992008-10-21 23:43:52 +00002815 // If FromType and ToType are the same type, this is not a
2816 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002817 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002818 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002819
Douglas Gregor98cd5992008-10-21 23:43:52 +00002820 // (C++ 4.4p4):
2821 // A conversion can add cv-qualifiers at levels other than the first
2822 // in multi-level pointers, subject to the following rules: [...]
2823 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002824 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002825 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002826 // Within each iteration of the loop, we check the qualifiers to
2827 // determine if this still looks like a qualification
2828 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002829 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002830 // until there are no more pointers or pointers-to-members left to
2831 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002832 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002833
Douglas Gregor621c92a2011-04-25 18:40:17 +00002834 Qualifiers FromQuals = FromType.getQualifiers();
2835 Qualifiers ToQuals = ToType.getQualifiers();
2836
John McCallf85e1932011-06-15 23:02:42 +00002837 // Objective-C ARC:
2838 // Check Objective-C lifetime conversions.
2839 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2840 UnwrappedAnyPointer) {
2841 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2842 ObjCLifetimeConversion = true;
2843 FromQuals.removeObjCLifetime();
2844 ToQuals.removeObjCLifetime();
2845 } else {
2846 // Qualification conversions cannot cast between different
2847 // Objective-C lifetime qualifiers.
2848 return false;
2849 }
2850 }
2851
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002852 // Allow addition/removal of GC attributes but not changing GC attributes.
2853 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2854 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2855 FromQuals.removeObjCGCAttr();
2856 ToQuals.removeObjCGCAttr();
2857 }
2858
Douglas Gregor98cd5992008-10-21 23:43:52 +00002859 // -- for every j > 0, if const is in cv 1,j then const is in cv
2860 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002861 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002862 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002863
Douglas Gregor98cd5992008-10-21 23:43:52 +00002864 // -- if the cv 1,j and cv 2,j are different, then const is in
2865 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002866 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002867 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002868 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Douglas Gregor98cd5992008-10-21 23:43:52 +00002870 // Keep track of whether all prior cv-qualifiers in the "to" type
2871 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002872 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002873 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002874 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002875
2876 // We are left with FromType and ToType being the pointee types
2877 // after unwrapping the original FromType and ToType the same number
2878 // of types. If we unwrapped any pointers, and if FromType and
2879 // ToType have the same unqualified type (since we checked
2880 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002881 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002882}
2883
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002884/// \brief - Determine whether this is a conversion from a scalar type to an
2885/// atomic type.
2886///
2887/// If successful, updates \c SCS's second and third steps in the conversion
2888/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002889static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2890 bool InOverloadResolution,
2891 StandardConversionSequence &SCS,
2892 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002893 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2894 if (!ToAtomic)
2895 return false;
2896
2897 StandardConversionSequence InnerSCS;
2898 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2899 InOverloadResolution, InnerSCS,
2900 CStyle, /*AllowObjCWritebackConversion=*/false))
2901 return false;
2902
2903 SCS.Second = InnerSCS.Second;
2904 SCS.setToType(1, InnerSCS.getToType(1));
2905 SCS.Third = InnerSCS.Third;
2906 SCS.QualificationIncludesObjCLifetime
2907 = InnerSCS.QualificationIncludesObjCLifetime;
2908 SCS.setToType(2, InnerSCS.getToType(2));
2909 return true;
2910}
2911
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002912static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2913 CXXConstructorDecl *Constructor,
2914 QualType Type) {
2915 const FunctionProtoType *CtorType =
2916 Constructor->getType()->getAs<FunctionProtoType>();
2917 if (CtorType->getNumArgs() > 0) {
2918 QualType FirstArg = CtorType->getArgType(0);
2919 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2920 return true;
2921 }
2922 return false;
2923}
2924
Sebastian Redl56a04282012-02-11 23:51:08 +00002925static OverloadingResult
2926IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2927 CXXRecordDecl *To,
2928 UserDefinedConversionSequence &User,
2929 OverloadCandidateSet &CandidateSet,
2930 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002931 DeclContext::lookup_result R = S.LookupConstructors(To);
2932 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002933 Con != ConEnd; ++Con) {
2934 NamedDecl *D = *Con;
2935 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2936
2937 // Find the constructor (which may be a template).
2938 CXXConstructorDecl *Constructor = 0;
2939 FunctionTemplateDecl *ConstructorTmpl
2940 = dyn_cast<FunctionTemplateDecl>(D);
2941 if (ConstructorTmpl)
2942 Constructor
2943 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2944 else
2945 Constructor = cast<CXXConstructorDecl>(D);
2946
2947 bool Usable = !Constructor->isInvalidDecl() &&
2948 S.isInitListConstructor(Constructor) &&
2949 (AllowExplicit || !Constructor->isExplicit());
2950 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002951 // If the first argument is (a reference to) the target type,
2952 // suppress conversions.
2953 bool SuppressUserConversions =
2954 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002955 if (ConstructorTmpl)
2956 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2957 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002958 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002959 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002960 else
2961 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002962 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002963 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002964 }
2965 }
2966
2967 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2968
2969 OverloadCandidateSet::iterator Best;
2970 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2971 case OR_Success: {
2972 // Record the standard conversion we used and the conversion function.
2973 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002974 QualType ThisType = Constructor->getThisType(S.Context);
2975 // Initializer lists don't have conversions as such.
2976 User.Before.setAsIdentityConversion();
2977 User.HadMultipleCandidates = HadMultipleCandidates;
2978 User.ConversionFunction = Constructor;
2979 User.FoundConversionFunction = Best->FoundDecl;
2980 User.After.setAsIdentityConversion();
2981 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2982 User.After.setAllToTypes(ToType);
2983 return OR_Success;
2984 }
2985
2986 case OR_No_Viable_Function:
2987 return OR_No_Viable_Function;
2988 case OR_Deleted:
2989 return OR_Deleted;
2990 case OR_Ambiguous:
2991 return OR_Ambiguous;
2992 }
2993
2994 llvm_unreachable("Invalid OverloadResult!");
2995}
2996
Douglas Gregor734d9862009-01-30 23:27:23 +00002997/// Determines whether there is a user-defined conversion sequence
2998/// (C++ [over.ics.user]) that converts expression From to the type
2999/// ToType. If such a conversion exists, User will contain the
3000/// user-defined conversion sequence that performs such a conversion
3001/// and this routine will return true. Otherwise, this routine returns
3002/// false and User is unspecified.
3003///
Douglas Gregor734d9862009-01-30 23:27:23 +00003004/// \param AllowExplicit true if the conversion should consider C++0x
3005/// "explicit" conversion functions as well as non-explicit conversion
3006/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003007static OverloadingResult
3008IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003009 UserDefinedConversionSequence &User,
3010 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003011 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003012 // Whether we will only visit constructors.
3013 bool ConstructorsOnly = false;
3014
3015 // If the type we are conversion to is a class type, enumerate its
3016 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003017 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003018 // C++ [over.match.ctor]p1:
3019 // When objects of class type are direct-initialized (8.5), or
3020 // copy-initialized from an expression of the same or a
3021 // derived class type (8.5), overload resolution selects the
3022 // constructor. [...] For copy-initialization, the candidate
3023 // functions are all the converting constructors (12.3.1) of
3024 // that class. The argument list is the expression-list within
3025 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003026 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003027 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003028 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003029 ConstructorsOnly = true;
3030
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003031 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003032 // RequireCompleteType may have returned true due to some invalid decl
3033 // during template instantiation, but ToType may be complete enough now
3034 // to try to recover.
3035 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003036 // We're not going to find any constructors.
3037 } else if (CXXRecordDecl *ToRecordDecl
3038 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003039
3040 Expr **Args = &From;
3041 unsigned NumArgs = 1;
3042 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003043 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003044 // But first, see if there is an init-list-contructor that will work.
3045 OverloadingResult Result = IsInitializerListConstructorConversion(
3046 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3047 if (Result != OR_No_Viable_Function)
3048 return Result;
3049 // Never mind.
3050 CandidateSet.clear();
3051
3052 // If we're list-initializing, we pass the individual elements as
3053 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003054 Args = InitList->getInits();
3055 NumArgs = InitList->getNumInits();
3056 ListInitializing = true;
3057 }
3058
David Blaikie3bc93e32012-12-19 00:45:41 +00003059 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3060 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003061 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003062 NamedDecl *D = *Con;
3063 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3064
Douglas Gregordec06662009-08-21 18:42:58 +00003065 // Find the constructor (which may be a template).
3066 CXXConstructorDecl *Constructor = 0;
3067 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003068 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003069 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003070 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003071 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3072 else
John McCall9aa472c2010-03-19 07:35:19 +00003073 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003074
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003075 bool Usable = !Constructor->isInvalidDecl();
3076 if (ListInitializing)
3077 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3078 else
3079 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3080 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003081 bool SuppressUserConversions = !ConstructorsOnly;
3082 if (SuppressUserConversions && ListInitializing) {
3083 SuppressUserConversions = false;
3084 if (NumArgs == 1) {
3085 // If the first argument is (a reference to) the target type,
3086 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003087 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3088 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003089 }
3090 }
Douglas Gregordec06662009-08-21 18:42:58 +00003091 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003092 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3093 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003094 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003095 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003096 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003097 // Allow one user-defined conversion when user specifies a
3098 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003099 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003100 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003101 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003102 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003103 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003104 }
3105 }
3106
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003107 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003108 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003109 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003110 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003111 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003112 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003113 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003114 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3115 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003116 std::pair<CXXRecordDecl::conversion_iterator,
3117 CXXRecordDecl::conversion_iterator>
3118 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3119 for (CXXRecordDecl::conversion_iterator
3120 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003121 DeclAccessPair FoundDecl = I.getPair();
3122 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003123 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3124 if (isa<UsingShadowDecl>(D))
3125 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3126
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003127 CXXConversionDecl *Conv;
3128 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003129 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3130 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003131 else
John McCall32daa422010-03-31 01:36:47 +00003132 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003133
3134 if (AllowExplicit || !Conv->isExplicit()) {
3135 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003136 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3137 ActingContext, From, ToType,
3138 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003139 else
John McCall120d63c2010-08-24 20:38:10 +00003140 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3141 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003142 }
3143 }
3144 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003145 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003146
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003147 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3148
Douglas Gregor60d62c22008-10-31 16:23:19 +00003149 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003150 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003151 case OR_Success:
3152 // Record the standard conversion we used and the conversion function.
3153 if (CXXConstructorDecl *Constructor
3154 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3155 // C++ [over.ics.user]p1:
3156 // If the user-defined conversion is specified by a
3157 // constructor (12.3.1), the initial standard conversion
3158 // sequence converts the source type to the type required by
3159 // the argument of the constructor.
3160 //
3161 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003162 if (isa<InitListExpr>(From)) {
3163 // Initializer lists don't have conversions as such.
3164 User.Before.setAsIdentityConversion();
3165 } else {
3166 if (Best->Conversions[0].isEllipsis())
3167 User.EllipsisConversion = true;
3168 else {
3169 User.Before = Best->Conversions[0].Standard;
3170 User.EllipsisConversion = false;
3171 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003172 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003173 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003174 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003175 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003176 User.After.setAsIdentityConversion();
3177 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3178 User.After.setAllToTypes(ToType);
3179 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003180 }
3181 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003182 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3183 // C++ [over.ics.user]p1:
3184 //
3185 // [...] If the user-defined conversion is specified by a
3186 // conversion function (12.3.2), the initial standard
3187 // conversion sequence converts the source type to the
3188 // implicit object parameter of the conversion function.
3189 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003190 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003191 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003192 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003193 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003194
John McCall120d63c2010-08-24 20:38:10 +00003195 // C++ [over.ics.user]p2:
3196 // The second standard conversion sequence converts the
3197 // result of the user-defined conversion to the target type
3198 // for the sequence. Since an implicit conversion sequence
3199 // is an initialization, the special rules for
3200 // initialization by user-defined conversion apply when
3201 // selecting the best user-defined conversion for a
3202 // user-defined conversion sequence (see 13.3.3 and
3203 // 13.3.3.1).
3204 User.After = Best->FinalConversion;
3205 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003206 }
David Blaikie7530c032012-01-17 06:56:22 +00003207 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003208
John McCall120d63c2010-08-24 20:38:10 +00003209 case OR_No_Viable_Function:
3210 return OR_No_Viable_Function;
3211 case OR_Deleted:
3212 // No conversion here! We're done.
3213 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214
John McCall120d63c2010-08-24 20:38:10 +00003215 case OR_Ambiguous:
3216 return OR_Ambiguous;
3217 }
3218
David Blaikie7530c032012-01-17 06:56:22 +00003219 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003220}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003222bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003223Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003224 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003225 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003226 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003227 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003228 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003229 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003230 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003231 diag::err_typecheck_ambiguous_condition)
3232 << From->getType() << ToType << From->getSourceRange();
3233 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003234 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003235 diag::err_typecheck_nonviable_condition)
3236 << From->getType() << ToType << From->getSourceRange();
3237 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003238 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003239 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003240 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003241}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003242
Douglas Gregorb734e242012-02-22 17:32:19 +00003243/// \brief Compare the user-defined conversion functions or constructors
3244/// of two user-defined conversion sequences to determine whether any ordering
3245/// is possible.
3246static ImplicitConversionSequence::CompareKind
3247compareConversionFunctions(Sema &S,
3248 FunctionDecl *Function1,
3249 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003250 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003251 return ImplicitConversionSequence::Indistinguishable;
3252
3253 // Objective-C++:
3254 // If both conversion functions are implicitly-declared conversions from
3255 // a lambda closure type to a function pointer and a block pointer,
3256 // respectively, always prefer the conversion to a function pointer,
3257 // because the function pointer is more lightweight and is more likely
3258 // to keep code working.
3259 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3260 if (!Conv1)
3261 return ImplicitConversionSequence::Indistinguishable;
3262
3263 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3264 if (!Conv2)
3265 return ImplicitConversionSequence::Indistinguishable;
3266
3267 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3268 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3269 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3270 if (Block1 != Block2)
3271 return Block1? ImplicitConversionSequence::Worse
3272 : ImplicitConversionSequence::Better;
3273 }
3274
3275 return ImplicitConversionSequence::Indistinguishable;
3276}
3277
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003278/// CompareImplicitConversionSequences - Compare two implicit
3279/// conversion sequences to determine whether one is better than the
3280/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003281static ImplicitConversionSequence::CompareKind
3282CompareImplicitConversionSequences(Sema &S,
3283 const ImplicitConversionSequence& ICS1,
3284 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003285{
3286 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3287 // conversion sequences (as defined in 13.3.3.1)
3288 // -- a standard conversion sequence (13.3.3.1.1) is a better
3289 // conversion sequence than a user-defined conversion sequence or
3290 // an ellipsis conversion sequence, and
3291 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3292 // conversion sequence than an ellipsis conversion sequence
3293 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003294 //
John McCall1d318332010-01-12 00:44:57 +00003295 // C++0x [over.best.ics]p10:
3296 // For the purpose of ranking implicit conversion sequences as
3297 // described in 13.3.3.2, the ambiguous conversion sequence is
3298 // treated as a user-defined sequence that is indistinguishable
3299 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003300 if (ICS1.getKindRank() < ICS2.getKindRank())
3301 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003302 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003303 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003304
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003305 // The following checks require both conversion sequences to be of
3306 // the same kind.
3307 if (ICS1.getKind() != ICS2.getKind())
3308 return ImplicitConversionSequence::Indistinguishable;
3309
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003310 ImplicitConversionSequence::CompareKind Result =
3311 ImplicitConversionSequence::Indistinguishable;
3312
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003313 // Two implicit conversion sequences of the same form are
3314 // indistinguishable conversion sequences unless one of the
3315 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003316 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003317 Result = CompareStandardConversionSequences(S,
3318 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003319 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003320 // User-defined conversion sequence U1 is a better conversion
3321 // sequence than another user-defined conversion sequence U2 if
3322 // they contain the same user-defined conversion function or
3323 // constructor and if the second standard conversion sequence of
3324 // U1 is better than the second standard conversion sequence of
3325 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003326 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003327 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003328 Result = CompareStandardConversionSequences(S,
3329 ICS1.UserDefined.After,
3330 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003331 else
3332 Result = compareConversionFunctions(S,
3333 ICS1.UserDefined.ConversionFunction,
3334 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003335 }
3336
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003337 // List-initialization sequence L1 is a better conversion sequence than
3338 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3339 // for some X and L2 does not.
3340 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003341 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003342 ICS1.isListInitializationSequence() &&
3343 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003344 if (ICS1.isStdInitializerListElement() &&
3345 !ICS2.isStdInitializerListElement())
3346 return ImplicitConversionSequence::Better;
3347 if (!ICS1.isStdInitializerListElement() &&
3348 ICS2.isStdInitializerListElement())
3349 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003350 }
3351
3352 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003353}
3354
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003355static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3356 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3357 Qualifiers Quals;
3358 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003359 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003360 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003361
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003362 return Context.hasSameUnqualifiedType(T1, T2);
3363}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364
Douglas Gregorad323a82010-01-27 03:51:04 +00003365// Per 13.3.3.2p3, compare the given standard conversion sequences to
3366// determine if one is a proper subset of the other.
3367static ImplicitConversionSequence::CompareKind
3368compareStandardConversionSubsets(ASTContext &Context,
3369 const StandardConversionSequence& SCS1,
3370 const StandardConversionSequence& SCS2) {
3371 ImplicitConversionSequence::CompareKind Result
3372 = ImplicitConversionSequence::Indistinguishable;
3373
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003375 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003376 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3377 return ImplicitConversionSequence::Better;
3378 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3379 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380
Douglas Gregorad323a82010-01-27 03:51:04 +00003381 if (SCS1.Second != SCS2.Second) {
3382 if (SCS1.Second == ICK_Identity)
3383 Result = ImplicitConversionSequence::Better;
3384 else if (SCS2.Second == ICK_Identity)
3385 Result = ImplicitConversionSequence::Worse;
3386 else
3387 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003388 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003389 return ImplicitConversionSequence::Indistinguishable;
3390
3391 if (SCS1.Third == SCS2.Third) {
3392 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3393 : ImplicitConversionSequence::Indistinguishable;
3394 }
3395
3396 if (SCS1.Third == ICK_Identity)
3397 return Result == ImplicitConversionSequence::Worse
3398 ? ImplicitConversionSequence::Indistinguishable
3399 : ImplicitConversionSequence::Better;
3400
3401 if (SCS2.Third == ICK_Identity)
3402 return Result == ImplicitConversionSequence::Better
3403 ? ImplicitConversionSequence::Indistinguishable
3404 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003405
Douglas Gregorad323a82010-01-27 03:51:04 +00003406 return ImplicitConversionSequence::Indistinguishable;
3407}
3408
Douglas Gregor440a4832011-01-26 14:52:12 +00003409/// \brief Determine whether one of the given reference bindings is better
3410/// than the other based on what kind of bindings they are.
3411static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3412 const StandardConversionSequence &SCS2) {
3413 // C++0x [over.ics.rank]p3b4:
3414 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3415 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003416 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003417 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003418 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003419 // reference*.
3420 //
3421 // FIXME: Rvalue references. We're going rogue with the above edits,
3422 // because the semantics in the current C++0x working paper (N3225 at the
3423 // time of this writing) break the standard definition of std::forward
3424 // and std::reference_wrapper when dealing with references to functions.
3425 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003426 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3427 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3428 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003429
Douglas Gregor440a4832011-01-26 14:52:12 +00003430 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3431 SCS2.IsLvalueReference) ||
3432 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3433 !SCS2.IsLvalueReference);
3434}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003435
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003436/// CompareStandardConversionSequences - Compare two standard
3437/// conversion sequences to determine whether one is better than the
3438/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003439static ImplicitConversionSequence::CompareKind
3440CompareStandardConversionSequences(Sema &S,
3441 const StandardConversionSequence& SCS1,
3442 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003443{
3444 // Standard conversion sequence S1 is a better conversion sequence
3445 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3446
3447 // -- S1 is a proper subsequence of S2 (comparing the conversion
3448 // sequences in the canonical form defined by 13.3.3.1.1,
3449 // excluding any Lvalue Transformation; the identity conversion
3450 // sequence is considered to be a subsequence of any
3451 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003452 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003453 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003454 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003455
3456 // -- the rank of S1 is better than the rank of S2 (by the rules
3457 // defined below), or, if not that,
3458 ImplicitConversionRank Rank1 = SCS1.getRank();
3459 ImplicitConversionRank Rank2 = SCS2.getRank();
3460 if (Rank1 < Rank2)
3461 return ImplicitConversionSequence::Better;
3462 else if (Rank2 < Rank1)
3463 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003464
Douglas Gregor57373262008-10-22 14:17:15 +00003465 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3466 // are indistinguishable unless one of the following rules
3467 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Douglas Gregor57373262008-10-22 14:17:15 +00003469 // A conversion that is not a conversion of a pointer, or
3470 // pointer to member, to bool is better than another conversion
3471 // that is such a conversion.
3472 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3473 return SCS2.isPointerConversionToBool()
3474 ? ImplicitConversionSequence::Better
3475 : ImplicitConversionSequence::Worse;
3476
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003477 // C++ [over.ics.rank]p4b2:
3478 //
3479 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003480 // conversion of B* to A* is better than conversion of B* to
3481 // void*, and conversion of A* to void* is better than conversion
3482 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003483 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003484 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003485 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003486 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003487 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3488 // Exactly one of the conversion sequences is a conversion to
3489 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003490 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3491 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003492 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3493 // Neither conversion sequence converts to a void pointer; compare
3494 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003495 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003496 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003497 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003498 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3499 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003500 // Both conversion sequences are conversions to void
3501 // pointers. Compare the source types to determine if there's an
3502 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003503 QualType FromType1 = SCS1.getFromType();
3504 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003505
3506 // Adjust the types we're converting from via the array-to-pointer
3507 // conversion, if we need to.
3508 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003509 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003510 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003511 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003512
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003513 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3514 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003515
John McCall120d63c2010-08-24 20:38:10 +00003516 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003517 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003518 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003519 return ImplicitConversionSequence::Worse;
3520
3521 // Objective-C++: If one interface is more specific than the
3522 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003523 const ObjCObjectPointerType* FromObjCPtr1
3524 = FromType1->getAs<ObjCObjectPointerType>();
3525 const ObjCObjectPointerType* FromObjCPtr2
3526 = FromType2->getAs<ObjCObjectPointerType>();
3527 if (FromObjCPtr1 && FromObjCPtr2) {
3528 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3529 FromObjCPtr2);
3530 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3531 FromObjCPtr1);
3532 if (AssignLeft != AssignRight) {
3533 return AssignLeft? ImplicitConversionSequence::Better
3534 : ImplicitConversionSequence::Worse;
3535 }
Douglas Gregor01919692009-12-13 21:37:05 +00003536 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003537 }
Douglas Gregor57373262008-10-22 14:17:15 +00003538
3539 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3540 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003541 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003542 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003543 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003544
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003545 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003546 // Check for a better reference binding based on the kind of bindings.
3547 if (isBetterReferenceBindingKind(SCS1, SCS2))
3548 return ImplicitConversionSequence::Better;
3549 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3550 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003551
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003552 // C++ [over.ics.rank]p3b4:
3553 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3554 // which the references refer are the same type except for
3555 // top-level cv-qualifiers, and the type to which the reference
3556 // initialized by S2 refers is more cv-qualified than the type
3557 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003558 QualType T1 = SCS1.getToType(2);
3559 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003560 T1 = S.Context.getCanonicalType(T1);
3561 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003562 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003563 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3564 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003565 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003566 // Objective-C++ ARC: If the references refer to objects with different
3567 // lifetimes, prefer bindings that don't change lifetime.
3568 if (SCS1.ObjCLifetimeConversionBinding !=
3569 SCS2.ObjCLifetimeConversionBinding) {
3570 return SCS1.ObjCLifetimeConversionBinding
3571 ? ImplicitConversionSequence::Worse
3572 : ImplicitConversionSequence::Better;
3573 }
3574
Chandler Carruth6df868e2010-12-12 08:17:55 +00003575 // If the type is an array type, promote the element qualifiers to the
3576 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003577 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003578 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003579 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003580 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003581 if (T2.isMoreQualifiedThan(T1))
3582 return ImplicitConversionSequence::Better;
3583 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003584 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003585 }
3586 }
Douglas Gregor57373262008-10-22 14:17:15 +00003587
Francois Pichet1c98d622011-09-18 21:37:37 +00003588 // In Microsoft mode, prefer an integral conversion to a
3589 // floating-to-integral conversion if the integral conversion
3590 // is between types of the same size.
3591 // For example:
3592 // void f(float);
3593 // void f(int);
3594 // int main {
3595 // long a;
3596 // f(a);
3597 // }
3598 // Here, MSVC will call f(int) instead of generating a compile error
3599 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003600 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003601 SCS1.Second == ICK_Integral_Conversion &&
3602 SCS2.Second == ICK_Floating_Integral &&
3603 S.Context.getTypeSize(SCS1.getFromType()) ==
3604 S.Context.getTypeSize(SCS1.getToType(2)))
3605 return ImplicitConversionSequence::Better;
3606
Douglas Gregor57373262008-10-22 14:17:15 +00003607 return ImplicitConversionSequence::Indistinguishable;
3608}
3609
3610/// CompareQualificationConversions - Compares two standard conversion
3611/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003612/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3613ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003614CompareQualificationConversions(Sema &S,
3615 const StandardConversionSequence& SCS1,
3616 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003617 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003618 // -- S1 and S2 differ only in their qualification conversion and
3619 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3620 // cv-qualification signature of type T1 is a proper subset of
3621 // the cv-qualification signature of type T2, and S1 is not the
3622 // deprecated string literal array-to-pointer conversion (4.2).
3623 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3624 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3625 return ImplicitConversionSequence::Indistinguishable;
3626
3627 // FIXME: the example in the standard doesn't use a qualification
3628 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003629 QualType T1 = SCS1.getToType(2);
3630 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003631 T1 = S.Context.getCanonicalType(T1);
3632 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003633 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003634 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3635 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003636
3637 // If the types are the same, we won't learn anything by unwrapped
3638 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003639 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003640 return ImplicitConversionSequence::Indistinguishable;
3641
Chandler Carruth28e318c2009-12-29 07:16:59 +00003642 // If the type is an array type, promote the element qualifiers to the type
3643 // for comparison.
3644 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003645 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003646 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003647 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003648
Mike Stump1eb44332009-09-09 15:08:12 +00003649 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003650 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003651
3652 // Objective-C++ ARC:
3653 // Prefer qualification conversions not involving a change in lifetime
3654 // to qualification conversions that do not change lifetime.
3655 if (SCS1.QualificationIncludesObjCLifetime !=
3656 SCS2.QualificationIncludesObjCLifetime) {
3657 Result = SCS1.QualificationIncludesObjCLifetime
3658 ? ImplicitConversionSequence::Worse
3659 : ImplicitConversionSequence::Better;
3660 }
3661
John McCall120d63c2010-08-24 20:38:10 +00003662 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003663 // Within each iteration of the loop, we check the qualifiers to
3664 // determine if this still looks like a qualification
3665 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003666 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003667 // until there are no more pointers or pointers-to-members left
3668 // to unwrap. This essentially mimics what
3669 // IsQualificationConversion does, but here we're checking for a
3670 // strict subset of qualifiers.
3671 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3672 // The qualifiers are the same, so this doesn't tell us anything
3673 // about how the sequences rank.
3674 ;
3675 else if (T2.isMoreQualifiedThan(T1)) {
3676 // T1 has fewer qualifiers, so it could be the better sequence.
3677 if (Result == ImplicitConversionSequence::Worse)
3678 // Neither has qualifiers that are a subset of the other's
3679 // qualifiers.
3680 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Douglas Gregor57373262008-10-22 14:17:15 +00003682 Result = ImplicitConversionSequence::Better;
3683 } else if (T1.isMoreQualifiedThan(T2)) {
3684 // T2 has fewer qualifiers, so it could be the better sequence.
3685 if (Result == ImplicitConversionSequence::Better)
3686 // Neither has qualifiers that are a subset of the other's
3687 // qualifiers.
3688 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Douglas Gregor57373262008-10-22 14:17:15 +00003690 Result = ImplicitConversionSequence::Worse;
3691 } else {
3692 // Qualifiers are disjoint.
3693 return ImplicitConversionSequence::Indistinguishable;
3694 }
3695
3696 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003697 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003698 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003699 }
3700
Douglas Gregor57373262008-10-22 14:17:15 +00003701 // Check that the winning standard conversion sequence isn't using
3702 // the deprecated string literal array to pointer conversion.
3703 switch (Result) {
3704 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003705 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003706 Result = ImplicitConversionSequence::Indistinguishable;
3707 break;
3708
3709 case ImplicitConversionSequence::Indistinguishable:
3710 break;
3711
3712 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003713 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003714 Result = ImplicitConversionSequence::Indistinguishable;
3715 break;
3716 }
3717
3718 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003719}
3720
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003721/// CompareDerivedToBaseConversions - Compares two standard conversion
3722/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003723/// various kinds of derived-to-base conversions (C++
3724/// [over.ics.rank]p4b3). As part of these checks, we also look at
3725/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003727CompareDerivedToBaseConversions(Sema &S,
3728 const StandardConversionSequence& SCS1,
3729 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003730 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003731 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003732 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003733 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003734
3735 // Adjust the types we're converting from via the array-to-pointer
3736 // conversion, if we need to.
3737 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003738 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003739 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003740 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003741
3742 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003743 FromType1 = S.Context.getCanonicalType(FromType1);
3744 ToType1 = S.Context.getCanonicalType(ToType1);
3745 FromType2 = S.Context.getCanonicalType(FromType2);
3746 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003747
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003748 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003749 //
3750 // If class B is derived directly or indirectly from class A and
3751 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003752 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003753 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003754 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003755 SCS2.Second == ICK_Pointer_Conversion &&
3756 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3757 FromType1->isPointerType() && FromType2->isPointerType() &&
3758 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003759 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003760 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003761 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003762 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003763 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003764 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003765 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003766 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003767
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003768 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003769 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003770 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003771 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003772 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003773 return ImplicitConversionSequence::Worse;
3774 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003775
3776 // -- conversion of B* to A* is better than conversion of C* to A*,
3777 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003778 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003779 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003780 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003781 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003782 }
3783 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3784 SCS2.Second == ICK_Pointer_Conversion) {
3785 const ObjCObjectPointerType *FromPtr1
3786 = FromType1->getAs<ObjCObjectPointerType>();
3787 const ObjCObjectPointerType *FromPtr2
3788 = FromType2->getAs<ObjCObjectPointerType>();
3789 const ObjCObjectPointerType *ToPtr1
3790 = ToType1->getAs<ObjCObjectPointerType>();
3791 const ObjCObjectPointerType *ToPtr2
3792 = ToType2->getAs<ObjCObjectPointerType>();
3793
3794 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3795 // Apply the same conversion ranking rules for Objective-C pointer types
3796 // that we do for C++ pointers to class types. However, we employ the
3797 // Objective-C pseudo-subtyping relationship used for assignment of
3798 // Objective-C pointer types.
3799 bool FromAssignLeft
3800 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3801 bool FromAssignRight
3802 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3803 bool ToAssignLeft
3804 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3805 bool ToAssignRight
3806 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3807
3808 // A conversion to an a non-id object pointer type or qualified 'id'
3809 // type is better than a conversion to 'id'.
3810 if (ToPtr1->isObjCIdType() &&
3811 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3812 return ImplicitConversionSequence::Worse;
3813 if (ToPtr2->isObjCIdType() &&
3814 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3815 return ImplicitConversionSequence::Better;
3816
3817 // A conversion to a non-id object pointer type is better than a
3818 // conversion to a qualified 'id' type
3819 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3820 return ImplicitConversionSequence::Worse;
3821 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3822 return ImplicitConversionSequence::Better;
3823
3824 // A conversion to an a non-Class object pointer type or qualified 'Class'
3825 // type is better than a conversion to 'Class'.
3826 if (ToPtr1->isObjCClassType() &&
3827 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3828 return ImplicitConversionSequence::Worse;
3829 if (ToPtr2->isObjCClassType() &&
3830 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3831 return ImplicitConversionSequence::Better;
3832
3833 // A conversion to a non-Class object pointer type is better than a
3834 // conversion to a qualified 'Class' type.
3835 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3836 return ImplicitConversionSequence::Worse;
3837 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3838 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003839
Douglas Gregor395cc372011-01-31 18:51:41 +00003840 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3841 if (S.Context.hasSameType(FromType1, FromType2) &&
3842 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3843 (ToAssignLeft != ToAssignRight))
3844 return ToAssignLeft? ImplicitConversionSequence::Worse
3845 : ImplicitConversionSequence::Better;
3846
3847 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3848 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3849 (FromAssignLeft != FromAssignRight))
3850 return FromAssignLeft? ImplicitConversionSequence::Better
3851 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003852 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003853 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003854
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003855 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003856 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3857 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3858 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003859 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003860 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003861 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003862 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003864 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003865 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003866 ToType2->getAs<MemberPointerType>();
3867 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3868 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3869 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3870 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3871 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3872 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3873 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3874 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003875 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003876 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003877 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003878 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003879 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003880 return ImplicitConversionSequence::Better;
3881 }
3882 // conversion of B::* to C::* is better than conversion of A::* to C::*
3883 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003884 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003885 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003886 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003887 return ImplicitConversionSequence::Worse;
3888 }
3889 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003890
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003891 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003892 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003893 // -- binding of an expression of type C to a reference of type
3894 // B& is better than binding an expression of type C to a
3895 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003896 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3897 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3898 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003899 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003900 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003901 return ImplicitConversionSequence::Worse;
3902 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003903
Douglas Gregor225c41e2008-11-03 19:09:14 +00003904 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003905 // -- binding of an expression of type B to a reference of type
3906 // A& is better than binding an expression of type C to a
3907 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003908 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3909 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3910 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003911 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003912 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003913 return ImplicitConversionSequence::Worse;
3914 }
3915 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003916
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003917 return ImplicitConversionSequence::Indistinguishable;
3918}
3919
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003920/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3921/// C++ class.
3922static bool isTypeValid(QualType T) {
3923 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3924 return !Record->isInvalidDecl();
3925
3926 return true;
3927}
3928
Douglas Gregorabe183d2010-04-13 16:31:36 +00003929/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3930/// determine whether they are reference-related,
3931/// reference-compatible, reference-compatible with added
3932/// qualification, or incompatible, for use in C++ initialization by
3933/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3934/// type, and the first type (T1) is the pointee type of the reference
3935/// type being initialized.
3936Sema::ReferenceCompareResult
3937Sema::CompareReferenceRelationship(SourceLocation Loc,
3938 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003939 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003940 bool &ObjCConversion,
3941 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003942 assert(!OrigT1->isReferenceType() &&
3943 "T1 must be the pointee type of the reference type");
3944 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3945
3946 QualType T1 = Context.getCanonicalType(OrigT1);
3947 QualType T2 = Context.getCanonicalType(OrigT2);
3948 Qualifiers T1Quals, T2Quals;
3949 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3950 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3951
3952 // C++ [dcl.init.ref]p4:
3953 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3954 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3955 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003956 DerivedToBase = false;
3957 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003958 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003959 if (UnqualT1 == UnqualT2) {
3960 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003961 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003962 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3963 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003964 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003965 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3966 UnqualT2->isObjCObjectOrInterfaceType() &&
3967 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3968 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003969 else
3970 return Ref_Incompatible;
3971
3972 // At this point, we know that T1 and T2 are reference-related (at
3973 // least).
3974
3975 // If the type is an array type, promote the element qualifiers to the type
3976 // for comparison.
3977 if (isa<ArrayType>(T1) && T1Quals)
3978 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3979 if (isa<ArrayType>(T2) && T2Quals)
3980 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3981
3982 // C++ [dcl.init.ref]p4:
3983 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3984 // reference-related to T2 and cv1 is the same cv-qualification
3985 // as, or greater cv-qualification than, cv2. For purposes of
3986 // overload resolution, cases for which cv1 is greater
3987 // cv-qualification than cv2 are identified as
3988 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003989 //
3990 // Note that we also require equivalence of Objective-C GC and address-space
3991 // qualifiers when performing these computations, so that e.g., an int in
3992 // address space 1 is not reference-compatible with an int in address
3993 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003994 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3995 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3996 T1Quals.removeObjCLifetime();
3997 T2Quals.removeObjCLifetime();
3998 ObjCLifetimeConversion = true;
3999 }
4000
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004001 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004002 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004003 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004004 return Ref_Compatible_With_Added_Qualification;
4005 else
4006 return Ref_Related;
4007}
4008
Douglas Gregor604eb652010-08-11 02:15:33 +00004009/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004010/// with DeclType. Return true if something definite is found.
4011static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004012FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4013 QualType DeclType, SourceLocation DeclLoc,
4014 Expr *Init, QualType T2, bool AllowRvalues,
4015 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004016 assert(T2->isRecordType() && "Can only find conversions of record types.");
4017 CXXRecordDecl *T2RecordDecl
4018 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4019
4020 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004021 std::pair<CXXRecordDecl::conversion_iterator,
4022 CXXRecordDecl::conversion_iterator>
4023 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4024 for (CXXRecordDecl::conversion_iterator
4025 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004026 NamedDecl *D = *I;
4027 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4028 if (isa<UsingShadowDecl>(D))
4029 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4030
4031 FunctionTemplateDecl *ConvTemplate
4032 = dyn_cast<FunctionTemplateDecl>(D);
4033 CXXConversionDecl *Conv;
4034 if (ConvTemplate)
4035 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4036 else
4037 Conv = cast<CXXConversionDecl>(D);
4038
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004039 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004040 // explicit conversions, skip it.
4041 if (!AllowExplicit && Conv->isExplicit())
4042 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004043
Douglas Gregor604eb652010-08-11 02:15:33 +00004044 if (AllowRvalues) {
4045 bool DerivedToBase = false;
4046 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004047 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004048
4049 // If we are initializing an rvalue reference, don't permit conversion
4050 // functions that return lvalues.
4051 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4052 const ReferenceType *RefType
4053 = Conv->getConversionType()->getAs<LValueReferenceType>();
4054 if (RefType && !RefType->getPointeeType()->isFunctionType())
4055 continue;
4056 }
4057
Douglas Gregor604eb652010-08-11 02:15:33 +00004058 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004059 S.CompareReferenceRelationship(
4060 DeclLoc,
4061 Conv->getConversionType().getNonReferenceType()
4062 .getUnqualifiedType(),
4063 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004064 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004065 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004066 continue;
4067 } else {
4068 // If the conversion function doesn't return a reference type,
4069 // it can't be considered for this conversion. An rvalue reference
4070 // is only acceptable if its referencee is a function type.
4071
4072 const ReferenceType *RefType =
4073 Conv->getConversionType()->getAs<ReferenceType>();
4074 if (!RefType ||
4075 (!RefType->isLValueReferenceType() &&
4076 !RefType->getPointeeType()->isFunctionType()))
4077 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004078 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004079
Douglas Gregor604eb652010-08-11 02:15:33 +00004080 if (ConvTemplate)
4081 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004082 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004083 else
4084 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004085 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004086 }
4087
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004088 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4089
Sebastian Redl4680bf22010-06-30 18:13:39 +00004090 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004091 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004092 case OR_Success:
4093 // C++ [over.ics.ref]p1:
4094 //
4095 // [...] If the parameter binds directly to the result of
4096 // applying a conversion function to the argument
4097 // expression, the implicit conversion sequence is a
4098 // user-defined conversion sequence (13.3.3.1.2), with the
4099 // second standard conversion sequence either an identity
4100 // conversion or, if the conversion function returns an
4101 // entity of a type that is a derived class of the parameter
4102 // type, a derived-to-base Conversion.
4103 if (!Best->FinalConversion.DirectBinding)
4104 return false;
4105
4106 ICS.setUserDefined();
4107 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4108 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004109 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004110 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004111 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004112 ICS.UserDefined.EllipsisConversion = false;
4113 assert(ICS.UserDefined.After.ReferenceBinding &&
4114 ICS.UserDefined.After.DirectBinding &&
4115 "Expected a direct reference binding!");
4116 return true;
4117
4118 case OR_Ambiguous:
4119 ICS.setAmbiguous();
4120 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4121 Cand != CandidateSet.end(); ++Cand)
4122 if (Cand->Viable)
4123 ICS.Ambiguous.addConversion(Cand->Function);
4124 return true;
4125
4126 case OR_No_Viable_Function:
4127 case OR_Deleted:
4128 // There was no suitable conversion, or we found a deleted
4129 // conversion; continue with other checks.
4130 return false;
4131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004132
David Blaikie7530c032012-01-17 06:56:22 +00004133 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004134}
4135
Douglas Gregorabe183d2010-04-13 16:31:36 +00004136/// \brief Compute an implicit conversion sequence for reference
4137/// initialization.
4138static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004139TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004140 SourceLocation DeclLoc,
4141 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004142 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004143 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4144
4145 // Most paths end in a failed conversion.
4146 ImplicitConversionSequence ICS;
4147 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4148
4149 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4150 QualType T2 = Init->getType();
4151
4152 // If the initializer is the address of an overloaded function, try
4153 // to resolve the overloaded function. If all goes well, T2 is the
4154 // type of the resulting function.
4155 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4156 DeclAccessPair Found;
4157 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4158 false, Found))
4159 T2 = Fn->getType();
4160 }
4161
4162 // Compute some basic properties of the types and the initializer.
4163 bool isRValRef = DeclType->isRValueReferenceType();
4164 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004165 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004166 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004167 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004168 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004169 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004170 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004171
Douglas Gregorabe183d2010-04-13 16:31:36 +00004172
Sebastian Redl4680bf22010-06-30 18:13:39 +00004173 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004174 // A reference to type "cv1 T1" is initialized by an expression
4175 // of type "cv2 T2" as follows:
4176
Sebastian Redl4680bf22010-06-30 18:13:39 +00004177 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004178 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004179 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4180 // reference-compatible with "cv2 T2," or
4181 //
4182 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4183 if (InitCategory.isLValue() &&
4184 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004185 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004186 // When a parameter of reference type binds directly (8.5.3)
4187 // to an argument expression, the implicit conversion sequence
4188 // is the identity conversion, unless the argument expression
4189 // has a type that is a derived class of the parameter type,
4190 // in which case the implicit conversion sequence is a
4191 // derived-to-base Conversion (13.3.3.1).
4192 ICS.setStandard();
4193 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004194 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4195 : ObjCConversion? ICK_Compatible_Conversion
4196 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004197 ICS.Standard.Third = ICK_Identity;
4198 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4199 ICS.Standard.setToType(0, T2);
4200 ICS.Standard.setToType(1, T1);
4201 ICS.Standard.setToType(2, T1);
4202 ICS.Standard.ReferenceBinding = true;
4203 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004204 ICS.Standard.IsLvalueReference = !isRValRef;
4205 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4206 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004207 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004208 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004209 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004210
Sebastian Redl4680bf22010-06-30 18:13:39 +00004211 // Nothing more to do: the inaccessibility/ambiguity check for
4212 // derived-to-base conversions is suppressed when we're
4213 // computing the implicit conversion sequence (C++
4214 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004215 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004216 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004217
Sebastian Redl4680bf22010-06-30 18:13:39 +00004218 // -- has a class type (i.e., T2 is a class type), where T1 is
4219 // not reference-related to T2, and can be implicitly
4220 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4221 // is reference-compatible with "cv3 T3" 92) (this
4222 // conversion is selected by enumerating the applicable
4223 // conversion functions (13.3.1.6) and choosing the best
4224 // one through overload resolution (13.3)),
4225 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004226 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004227 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004228 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4229 Init, T2, /*AllowRvalues=*/false,
4230 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004231 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004232 }
4233 }
4234
Sebastian Redl4680bf22010-06-30 18:13:39 +00004235 // -- Otherwise, the reference shall be an lvalue reference to a
4236 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004237 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004238 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004239 // We actually handle one oddity of C++ [over.ics.ref] at this
4240 // point, which is that, due to p2 (which short-circuits reference
4241 // binding by only attempting a simple conversion for non-direct
4242 // bindings) and p3's strange wording, we allow a const volatile
4243 // reference to bind to an rvalue. Hence the check for the presence
4244 // of "const" rather than checking for "const" being the only
4245 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004246 // This is also the point where rvalue references and lvalue inits no longer
4247 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004248 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004249 return ICS;
4250
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004251 // -- If the initializer expression
4252 //
4253 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004254 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004255 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4256 (InitCategory.isXValue() ||
4257 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4258 (InitCategory.isLValue() && T2->isFunctionType()))) {
4259 ICS.setStandard();
4260 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004262 : ObjCConversion? ICK_Compatible_Conversion
4263 : ICK_Identity;
4264 ICS.Standard.Third = ICK_Identity;
4265 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4266 ICS.Standard.setToType(0, T2);
4267 ICS.Standard.setToType(1, T1);
4268 ICS.Standard.setToType(2, T1);
4269 ICS.Standard.ReferenceBinding = true;
4270 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4271 // binding unless we're binding to a class prvalue.
4272 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4273 // allow the use of rvalue references in C++98/03 for the benefit of
4274 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004275 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004276 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004277 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004278 ICS.Standard.IsLvalueReference = !isRValRef;
4279 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004280 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004281 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004282 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004283 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004284 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004285 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004286
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004287 // -- has a class type (i.e., T2 is a class type), where T1 is not
4288 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 // an xvalue, class prvalue, or function lvalue of type
4290 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004291 // "cv3 T3",
4292 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004293 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004294 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004295 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004296 // class subobject).
4297 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004298 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004299 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4300 Init, T2, /*AllowRvalues=*/true,
4301 AllowExplicit)) {
4302 // In the second case, if the reference is an rvalue reference
4303 // and the second standard conversion sequence of the
4304 // user-defined conversion sequence includes an lvalue-to-rvalue
4305 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004307 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4308 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4309
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004310 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312
Douglas Gregorabe183d2010-04-13 16:31:36 +00004313 // -- Otherwise, a temporary of type "cv1 T1" is created and
4314 // initialized from the initializer expression using the
4315 // rules for a non-reference copy initialization (8.5). The
4316 // reference is then bound to the temporary. If T1 is
4317 // reference-related to T2, cv1 must be the same
4318 // cv-qualification as, or greater cv-qualification than,
4319 // cv2; otherwise, the program is ill-formed.
4320 if (RefRelationship == Sema::Ref_Related) {
4321 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4322 // we would be reference-compatible or reference-compatible with
4323 // added qualification. But that wasn't the case, so the reference
4324 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004325 //
4326 // Note that we only want to check address spaces and cvr-qualifiers here.
4327 // ObjC GC and lifetime qualifiers aren't important.
4328 Qualifiers T1Quals = T1.getQualifiers();
4329 Qualifiers T2Quals = T2.getQualifiers();
4330 T1Quals.removeObjCGCAttr();
4331 T1Quals.removeObjCLifetime();
4332 T2Quals.removeObjCGCAttr();
4333 T2Quals.removeObjCLifetime();
4334 if (!T1Quals.compatiblyIncludes(T2Quals))
4335 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004336 }
4337
4338 // If at least one of the types is a class type, the types are not
4339 // related, and we aren't allowed any user conversions, the
4340 // reference binding fails. This case is important for breaking
4341 // recursion, since TryImplicitConversion below will attempt to
4342 // create a temporary through the use of a copy constructor.
4343 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4344 (T1->isRecordType() || T2->isRecordType()))
4345 return ICS;
4346
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004347 // If T1 is reference-related to T2 and the reference is an rvalue
4348 // reference, the initializer expression shall not be an lvalue.
4349 if (RefRelationship >= Sema::Ref_Related &&
4350 isRValRef && Init->Classify(S.Context).isLValue())
4351 return ICS;
4352
Douglas Gregorabe183d2010-04-13 16:31:36 +00004353 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004354 // When a parameter of reference type is not bound directly to
4355 // an argument expression, the conversion sequence is the one
4356 // required to convert the argument expression to the
4357 // underlying type of the reference according to
4358 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4359 // to copy-initializing a temporary of the underlying type with
4360 // the argument expression. Any difference in top-level
4361 // cv-qualification is subsumed by the initialization itself
4362 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004363 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4364 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004365 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004366 /*CStyle=*/false,
4367 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004368
4369 // Of course, that's still a reference binding.
4370 if (ICS.isStandard()) {
4371 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004372 ICS.Standard.IsLvalueReference = !isRValRef;
4373 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4374 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004375 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004376 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004377 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004378 // Don't allow rvalue references to bind to lvalues.
4379 if (DeclType->isRValueReferenceType()) {
4380 if (const ReferenceType *RefType
4381 = ICS.UserDefined.ConversionFunction->getResultType()
4382 ->getAs<LValueReferenceType>()) {
4383 if (!RefType->getPointeeType()->isFunctionType()) {
4384 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4385 DeclType);
4386 return ICS;
4387 }
4388 }
4389 }
4390
Douglas Gregorabe183d2010-04-13 16:31:36 +00004391 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004392 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4393 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4394 ICS.UserDefined.After.BindsToRvalue = true;
4395 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4396 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004397 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004398
Douglas Gregorabe183d2010-04-13 16:31:36 +00004399 return ICS;
4400}
4401
Sebastian Redl5405b812011-10-16 18:19:34 +00004402static ImplicitConversionSequence
4403TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4404 bool SuppressUserConversions,
4405 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004406 bool AllowObjCWritebackConversion,
4407 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004408
4409/// TryListConversion - Try to copy-initialize a value of type ToType from the
4410/// initializer list From.
4411static ImplicitConversionSequence
4412TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4413 bool SuppressUserConversions,
4414 bool InOverloadResolution,
4415 bool AllowObjCWritebackConversion) {
4416 // C++11 [over.ics.list]p1:
4417 // When an argument is an initializer list, it is not an expression and
4418 // special rules apply for converting it to a parameter type.
4419
4420 ImplicitConversionSequence Result;
4421 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004422 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004423
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004424 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004425 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004426 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004427 return Result;
4428
Sebastian Redl5405b812011-10-16 18:19:34 +00004429 // C++11 [over.ics.list]p2:
4430 // If the parameter type is std::initializer_list<X> or "array of X" and
4431 // all the elements can be implicitly converted to X, the implicit
4432 // conversion sequence is the worst conversion necessary to convert an
4433 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004434 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004435 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004436 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004437 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004438 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004439 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004440 if (!X.isNull()) {
4441 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4442 Expr *Init = From->getInit(i);
4443 ImplicitConversionSequence ICS =
4444 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4445 InOverloadResolution,
4446 AllowObjCWritebackConversion);
4447 // If a single element isn't convertible, fail.
4448 if (ICS.isBad()) {
4449 Result = ICS;
4450 break;
4451 }
4452 // Otherwise, look for the worst conversion.
4453 if (Result.isBad() ||
4454 CompareImplicitConversionSequences(S, ICS, Result) ==
4455 ImplicitConversionSequence::Worse)
4456 Result = ICS;
4457 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004458
4459 // For an empty list, we won't have computed any conversion sequence.
4460 // Introduce the identity conversion sequence.
4461 if (From->getNumInits() == 0) {
4462 Result.setStandard();
4463 Result.Standard.setAsIdentityConversion();
4464 Result.Standard.setFromType(ToType);
4465 Result.Standard.setAllToTypes(ToType);
4466 }
4467
Sebastian Redlfe592282012-01-17 22:49:48 +00004468 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004469 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004470 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004471 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004472
4473 // C++11 [over.ics.list]p3:
4474 // Otherwise, if the parameter is a non-aggregate class X and overload
4475 // resolution chooses a single best constructor [...] the implicit
4476 // conversion sequence is a user-defined conversion sequence. If multiple
4477 // constructors are viable but none is better than the others, the
4478 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004479 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4480 // This function can deal with initializer lists.
4481 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4482 /*AllowExplicit=*/false,
4483 InOverloadResolution, /*CStyle=*/false,
4484 AllowObjCWritebackConversion);
4485 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004486 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004487 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004488
4489 // C++11 [over.ics.list]p4:
4490 // Otherwise, if the parameter has an aggregate type which can be
4491 // initialized from the initializer list [...] the implicit conversion
4492 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004493 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004494 // Type is an aggregate, argument is an init list. At this point it comes
4495 // down to checking whether the initialization works.
4496 // FIXME: Find out whether this parameter is consumed or not.
4497 InitializedEntity Entity =
4498 InitializedEntity::InitializeParameter(S.Context, ToType,
4499 /*Consumed=*/false);
4500 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4501 Result.setUserDefined();
4502 Result.UserDefined.Before.setAsIdentityConversion();
4503 // Initializer lists don't have a type.
4504 Result.UserDefined.Before.setFromType(QualType());
4505 Result.UserDefined.Before.setAllToTypes(QualType());
4506
4507 Result.UserDefined.After.setAsIdentityConversion();
4508 Result.UserDefined.After.setFromType(ToType);
4509 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004510 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004511 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004512 return Result;
4513 }
4514
4515 // C++11 [over.ics.list]p5:
4516 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004517 if (ToType->isReferenceType()) {
4518 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4519 // mention initializer lists in any way. So we go by what list-
4520 // initialization would do and try to extrapolate from that.
4521
4522 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4523
4524 // If the initializer list has a single element that is reference-related
4525 // to the parameter type, we initialize the reference from that.
4526 if (From->getNumInits() == 1) {
4527 Expr *Init = From->getInit(0);
4528
4529 QualType T2 = Init->getType();
4530
4531 // If the initializer is the address of an overloaded function, try
4532 // to resolve the overloaded function. If all goes well, T2 is the
4533 // type of the resulting function.
4534 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4535 DeclAccessPair Found;
4536 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4537 Init, ToType, false, Found))
4538 T2 = Fn->getType();
4539 }
4540
4541 // Compute some basic properties of the types and the initializer.
4542 bool dummy1 = false;
4543 bool dummy2 = false;
4544 bool dummy3 = false;
4545 Sema::ReferenceCompareResult RefRelationship
4546 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4547 dummy2, dummy3);
4548
4549 if (RefRelationship >= Sema::Ref_Related)
4550 return TryReferenceInit(S, Init, ToType,
4551 /*FIXME:*/From->getLocStart(),
4552 SuppressUserConversions,
4553 /*AllowExplicit=*/false);
4554 }
4555
4556 // Otherwise, we bind the reference to a temporary created from the
4557 // initializer list.
4558 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4559 InOverloadResolution,
4560 AllowObjCWritebackConversion);
4561 if (Result.isFailure())
4562 return Result;
4563 assert(!Result.isEllipsis() &&
4564 "Sub-initialization cannot result in ellipsis conversion.");
4565
4566 // Can we even bind to a temporary?
4567 if (ToType->isRValueReferenceType() ||
4568 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4569 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4570 Result.UserDefined.After;
4571 SCS.ReferenceBinding = true;
4572 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4573 SCS.BindsToRvalue = true;
4574 SCS.BindsToFunctionLvalue = false;
4575 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4576 SCS.ObjCLifetimeConversionBinding = false;
4577 } else
4578 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4579 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004580 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004581 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004582
4583 // C++11 [over.ics.list]p6:
4584 // Otherwise, if the parameter type is not a class:
4585 if (!ToType->isRecordType()) {
4586 // - if the initializer list has one element, the implicit conversion
4587 // sequence is the one required to convert the element to the
4588 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004589 unsigned NumInits = From->getNumInits();
4590 if (NumInits == 1)
4591 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4592 SuppressUserConversions,
4593 InOverloadResolution,
4594 AllowObjCWritebackConversion);
4595 // - if the initializer list has no elements, the implicit conversion
4596 // sequence is the identity conversion.
4597 else if (NumInits == 0) {
4598 Result.setStandard();
4599 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004600 Result.Standard.setFromType(ToType);
4601 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004602 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004603 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004604 return Result;
4605 }
4606
4607 // C++11 [over.ics.list]p7:
4608 // In all cases other than those enumerated above, no conversion is possible
4609 return Result;
4610}
4611
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004612/// TryCopyInitialization - Try to copy-initialize a value of type
4613/// ToType from the expression From. Return the implicit conversion
4614/// sequence required to pass this argument, which may be a bad
4615/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004616/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004617/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004618static ImplicitConversionSequence
4619TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004620 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004621 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004622 bool AllowObjCWritebackConversion,
4623 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004624 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4625 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4626 InOverloadResolution,AllowObjCWritebackConversion);
4627
Douglas Gregorabe183d2010-04-13 16:31:36 +00004628 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004629 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004630 /*FIXME:*/From->getLocStart(),
4631 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004632 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004633
John McCall120d63c2010-08-24 20:38:10 +00004634 return TryImplicitConversion(S, From, ToType,
4635 SuppressUserConversions,
4636 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004637 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004638 /*CStyle=*/false,
4639 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004640}
4641
Anna Zaksf3546ee2011-07-28 19:46:48 +00004642static bool TryCopyInitialization(const CanQualType FromQTy,
4643 const CanQualType ToQTy,
4644 Sema &S,
4645 SourceLocation Loc,
4646 ExprValueKind FromVK) {
4647 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4648 ImplicitConversionSequence ICS =
4649 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4650
4651 return !ICS.isBad();
4652}
4653
Douglas Gregor96176b32008-11-18 23:14:02 +00004654/// TryObjectArgumentInitialization - Try to initialize the object
4655/// parameter of the given member function (@c Method) from the
4656/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004657static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004658TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004659 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004660 CXXMethodDecl *Method,
4661 CXXRecordDecl *ActingContext) {
4662 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004663 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4664 // const volatile object.
4665 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4666 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004667 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004668
4669 // Set up the conversion sequence as a "bad" conversion, to allow us
4670 // to exit early.
4671 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004672
4673 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004674 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004675 FromType = PT->getPointeeType();
4676
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004677 // When we had a pointer, it's implicitly dereferenced, so we
4678 // better have an lvalue.
4679 assert(FromClassification.isLValue());
4680 }
4681
Anders Carlssona552f7c2009-05-01 18:34:30 +00004682 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004683
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004684 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004685 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004686 // parameter is
4687 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004688 // - "lvalue reference to cv X" for functions declared without a
4689 // ref-qualifier or with the & ref-qualifier
4690 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004691 // ref-qualifier
4692 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004693 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004694 // cv-qualification on the member function declaration.
4695 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004696 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004697 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004698 // (C++ [over.match.funcs]p5). We perform a simplified version of
4699 // reference binding here, that allows class rvalues to bind to
4700 // non-constant references.
4701
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004702 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004703 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004704 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004705 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004706 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004707 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004708 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004709 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004710 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004711
4712 // Check that we have either the same type or a derived type. It
4713 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004714 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004715 ImplicitConversionKind SecondKind;
4716 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4717 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004718 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004719 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004720 else {
John McCallb1bdc622010-02-25 01:37:24 +00004721 ICS.setBad(BadConversionSequence::unrelated_class,
4722 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004723 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004724 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004725
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004726 // Check the ref-qualifier.
4727 switch (Method->getRefQualifier()) {
4728 case RQ_None:
4729 // Do nothing; we don't care about lvalueness or rvalueness.
4730 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004731
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004732 case RQ_LValue:
4733 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4734 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004735 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004736 ImplicitParamType);
4737 return ICS;
4738 }
4739 break;
4740
4741 case RQ_RValue:
4742 if (!FromClassification.isRValue()) {
4743 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004744 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004745 ImplicitParamType);
4746 return ICS;
4747 }
4748 break;
4749 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750
Douglas Gregor96176b32008-11-18 23:14:02 +00004751 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004752 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004753 ICS.Standard.setAsIdentityConversion();
4754 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004755 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004756 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004757 ICS.Standard.ReferenceBinding = true;
4758 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004759 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004760 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004761 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4762 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4763 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004764 return ICS;
4765}
4766
4767/// PerformObjectArgumentInitialization - Perform initialization of
4768/// the implicit object parameter for the given Method with the given
4769/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004770ExprResult
4771Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004772 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004773 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004774 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004775 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004776 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004777 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004778
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004779 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004780 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004781 FromRecordType = PT->getPointeeType();
4782 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004783 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004784 } else {
4785 FromRecordType = From->getType();
4786 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004787 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004788 }
4789
John McCall701c89e2009-12-03 04:06:58 +00004790 // Note that we always use the true parent context when performing
4791 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004792 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004793 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4794 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004795 if (ICS.isBad()) {
4796 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4797 Qualifiers FromQs = FromRecordType.getQualifiers();
4798 Qualifiers ToQs = DestType.getQualifiers();
4799 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4800 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004801 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004802 diag::err_member_function_call_bad_cvr)
4803 << Method->getDeclName() << FromRecordType << (CVR - 1)
4804 << From->getSourceRange();
4805 Diag(Method->getLocation(), diag::note_previous_decl)
4806 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004807 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004808 }
4809 }
4810
Daniel Dunbar96a00142012-03-09 18:35:03 +00004811 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004812 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004813 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004814 }
Mike Stump1eb44332009-09-09 15:08:12 +00004815
John Wiegley429bb272011-04-08 18:41:53 +00004816 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4817 ExprResult FromRes =
4818 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4819 if (FromRes.isInvalid())
4820 return ExprError();
4821 From = FromRes.take();
4822 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004823
Douglas Gregor5fccd362010-03-03 23:55:11 +00004824 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004825 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004826 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004827 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004828}
4829
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004830/// TryContextuallyConvertToBool - Attempt to contextually convert the
4831/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004832static ImplicitConversionSequence
4833TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004834 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004835 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004836 // FIXME: Are these flags correct?
4837 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004838 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004839 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004840 /*CStyle=*/false,
4841 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004842}
4843
4844/// PerformContextuallyConvertToBool - Perform a contextual conversion
4845/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004846ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004847 if (checkPlaceholderForOverload(*this, From))
4848 return ExprError();
4849
John McCall120d63c2010-08-24 20:38:10 +00004850 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004851 if (!ICS.isBad())
4852 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004853
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004854 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004855 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004856 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004857 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004858 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004859}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004860
Richard Smith8ef7b202012-01-18 23:55:52 +00004861/// Check that the specified conversion is permitted in a converted constant
4862/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4863/// is acceptable.
4864static bool CheckConvertedConstantConversions(Sema &S,
4865 StandardConversionSequence &SCS) {
4866 // Since we know that the target type is an integral or unscoped enumeration
4867 // type, most conversion kinds are impossible. All possible First and Third
4868 // conversions are fine.
4869 switch (SCS.Second) {
4870 case ICK_Identity:
4871 case ICK_Integral_Promotion:
4872 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004873 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004874 return true;
4875
4876 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004877 // Conversion from an integral or unscoped enumeration type to bool is
4878 // classified as ICK_Boolean_Conversion, but it's also an integral
4879 // conversion, so it's permitted in a converted constant expression.
4880 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4881 SCS.getToType(2)->isBooleanType();
4882
Richard Smith8ef7b202012-01-18 23:55:52 +00004883 case ICK_Floating_Integral:
4884 case ICK_Complex_Real:
4885 return false;
4886
4887 case ICK_Lvalue_To_Rvalue:
4888 case ICK_Array_To_Pointer:
4889 case ICK_Function_To_Pointer:
4890 case ICK_NoReturn_Adjustment:
4891 case ICK_Qualification:
4892 case ICK_Compatible_Conversion:
4893 case ICK_Vector_Conversion:
4894 case ICK_Vector_Splat:
4895 case ICK_Derived_To_Base:
4896 case ICK_Pointer_Conversion:
4897 case ICK_Pointer_Member:
4898 case ICK_Block_Pointer_Conversion:
4899 case ICK_Writeback_Conversion:
4900 case ICK_Floating_Promotion:
4901 case ICK_Complex_Promotion:
4902 case ICK_Complex_Conversion:
4903 case ICK_Floating_Conversion:
4904 case ICK_TransparentUnionConversion:
4905 llvm_unreachable("unexpected second conversion kind");
4906
4907 case ICK_Num_Conversion_Kinds:
4908 break;
4909 }
4910
4911 llvm_unreachable("unknown conversion kind");
4912}
4913
4914/// CheckConvertedConstantExpression - Check that the expression From is a
4915/// converted constant expression of type T, perform the conversion and produce
4916/// the converted expression, per C++11 [expr.const]p3.
4917ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4918 llvm::APSInt &Value,
4919 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004920 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004921 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4922
4923 if (checkPlaceholderForOverload(*this, From))
4924 return ExprError();
4925
4926 // C++11 [expr.const]p3 with proposed wording fixes:
4927 // A converted constant expression of type T is a core constant expression,
4928 // implicitly converted to a prvalue of type T, where the converted
4929 // expression is a literal constant expression and the implicit conversion
4930 // sequence contains only user-defined conversions, lvalue-to-rvalue
4931 // conversions, integral promotions, and integral conversions other than
4932 // narrowing conversions.
4933 ImplicitConversionSequence ICS =
4934 TryImplicitConversion(From, T,
4935 /*SuppressUserConversions=*/false,
4936 /*AllowExplicit=*/false,
4937 /*InOverloadResolution=*/false,
4938 /*CStyle=*/false,
4939 /*AllowObjcWritebackConversion=*/false);
4940 StandardConversionSequence *SCS = 0;
4941 switch (ICS.getKind()) {
4942 case ImplicitConversionSequence::StandardConversion:
4943 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004944 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004945 diag::err_typecheck_converted_constant_expression_disallowed)
4946 << From->getType() << From->getSourceRange() << T;
4947 SCS = &ICS.Standard;
4948 break;
4949 case ImplicitConversionSequence::UserDefinedConversion:
4950 // We are converting from class type to an integral or enumeration type, so
4951 // the Before sequence must be trivial.
4952 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004953 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004954 diag::err_typecheck_converted_constant_expression_disallowed)
4955 << From->getType() << From->getSourceRange() << T;
4956 SCS = &ICS.UserDefined.After;
4957 break;
4958 case ImplicitConversionSequence::AmbiguousConversion:
4959 case ImplicitConversionSequence::BadConversion:
4960 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004961 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004962 diag::err_typecheck_converted_constant_expression)
4963 << From->getType() << From->getSourceRange() << T;
4964 return ExprError();
4965
4966 case ImplicitConversionSequence::EllipsisConversion:
4967 llvm_unreachable("ellipsis conversion in converted constant expression");
4968 }
4969
4970 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4971 if (Result.isInvalid())
4972 return Result;
4973
4974 // Check for a narrowing implicit conversion.
4975 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004976 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004977 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4978 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004979 case NK_Variable_Narrowing:
4980 // Implicit conversion to a narrower type, and the value is not a constant
4981 // expression. We'll diagnose this in a moment.
4982 case NK_Not_Narrowing:
4983 break;
4984
4985 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004986 Diag(From->getLocStart(),
4987 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4988 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004989 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004990 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004991 break;
4992
4993 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004994 Diag(From->getLocStart(),
4995 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4996 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004997 << CCE << /*Constant*/0 << From->getType() << T;
4998 break;
4999 }
5000
5001 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005002 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005003 Expr::EvalResult Eval;
5004 Eval.Diag = &Notes;
5005
Douglas Gregor484f6fa2013-04-08 23:24:07 +00005006 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005007 // The expression can't be folded, so we can't keep it at this position in
5008 // the AST.
5009 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005010 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005011 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005012
5013 if (Notes.empty()) {
5014 // It's a constant expression.
5015 return Result;
5016 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005017 }
5018
5019 // It's not a constant expression. Produce an appropriate diagnostic.
5020 if (Notes.size() == 1 &&
5021 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5022 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5023 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005024 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005025 << CCE << From->getSourceRange();
5026 for (unsigned I = 0; I < Notes.size(); ++I)
5027 Diag(Notes[I].first, Notes[I].second);
5028 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005029 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005030}
5031
John McCall0bcc9bc2011-09-09 06:11:02 +00005032/// dropPointerConversions - If the given standard conversion sequence
5033/// involves any pointer conversions, remove them. This may change
5034/// the result type of the conversion sequence.
5035static void dropPointerConversion(StandardConversionSequence &SCS) {
5036 if (SCS.Second == ICK_Pointer_Conversion) {
5037 SCS.Second = ICK_Identity;
5038 SCS.Third = ICK_Identity;
5039 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5040 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005041}
John McCall120d63c2010-08-24 20:38:10 +00005042
John McCall0bcc9bc2011-09-09 06:11:02 +00005043/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5044/// convert the expression From to an Objective-C pointer type.
5045static ImplicitConversionSequence
5046TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5047 // Do an implicit conversion to 'id'.
5048 QualType Ty = S.Context.getObjCIdType();
5049 ImplicitConversionSequence ICS
5050 = TryImplicitConversion(S, From, Ty,
5051 // FIXME: Are these flags correct?
5052 /*SuppressUserConversions=*/false,
5053 /*AllowExplicit=*/true,
5054 /*InOverloadResolution=*/false,
5055 /*CStyle=*/false,
5056 /*AllowObjCWritebackConversion=*/false);
5057
5058 // Strip off any final conversions to 'id'.
5059 switch (ICS.getKind()) {
5060 case ImplicitConversionSequence::BadConversion:
5061 case ImplicitConversionSequence::AmbiguousConversion:
5062 case ImplicitConversionSequence::EllipsisConversion:
5063 break;
5064
5065 case ImplicitConversionSequence::UserDefinedConversion:
5066 dropPointerConversion(ICS.UserDefined.After);
5067 break;
5068
5069 case ImplicitConversionSequence::StandardConversion:
5070 dropPointerConversion(ICS.Standard);
5071 break;
5072 }
5073
5074 return ICS;
5075}
5076
5077/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5078/// conversion of the expression From to an Objective-C pointer type.
5079ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005080 if (checkPlaceholderForOverload(*this, From))
5081 return ExprError();
5082
John McCallc12c5bb2010-05-15 11:32:37 +00005083 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005084 ImplicitConversionSequence ICS =
5085 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005086 if (!ICS.isBad())
5087 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005088 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005089}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005090
Richard Smithf39aec12012-02-04 07:07:42 +00005091/// Determine whether the provided type is an integral type, or an enumeration
5092/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005093bool Sema::ICEConvertDiagnoser::match(QualType T) {
5094 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5095 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005096}
5097
Larisse Voufo50b60b32013-06-10 06:50:24 +00005098static ExprResult
5099diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5100 Sema::ContextualImplicitConverter &Converter,
5101 QualType T, UnresolvedSetImpl &ViableConversions) {
5102
5103 if (Converter.Suppress)
5104 return ExprError();
5105
5106 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5107 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5108 CXXConversionDecl *Conv =
5109 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5110 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5111 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5112 }
5113 return SemaRef.Owned(From);
5114}
5115
5116static bool
5117diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5118 Sema::ContextualImplicitConverter &Converter,
5119 QualType T, bool HadMultipleCandidates,
5120 UnresolvedSetImpl &ExplicitConversions) {
5121 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5122 DeclAccessPair Found = ExplicitConversions[0];
5123 CXXConversionDecl *Conversion =
5124 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5125
5126 // The user probably meant to invoke the given explicit
5127 // conversion; use it.
5128 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5129 std::string TypeStr;
5130 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5131
5132 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5133 << FixItHint::CreateInsertion(From->getLocStart(),
5134 "static_cast<" + TypeStr + ">(")
5135 << FixItHint::CreateInsertion(
5136 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5137 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5138
5139 // If we aren't in a SFINAE context, build a call to the
5140 // explicit conversion function.
5141 if (SemaRef.isSFINAEContext())
5142 return true;
5143
5144 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5145 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5146 HadMultipleCandidates);
5147 if (Result.isInvalid())
5148 return true;
5149 // Record usage of conversion in an implicit cast.
5150 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5151 CK_UserDefinedConversion, Result.get(), 0,
5152 Result.get()->getValueKind());
5153 }
5154 return false;
5155}
5156
5157static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5158 Sema::ContextualImplicitConverter &Converter,
5159 QualType T, bool HadMultipleCandidates,
5160 DeclAccessPair &Found) {
5161 CXXConversionDecl *Conversion =
5162 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5163 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5164
5165 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5166 if (!Converter.SuppressConversion) {
5167 if (SemaRef.isSFINAEContext())
5168 return true;
5169
5170 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5171 << From->getSourceRange();
5172 }
5173
5174 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5175 HadMultipleCandidates);
5176 if (Result.isInvalid())
5177 return true;
5178 // Record usage of conversion in an implicit cast.
5179 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5180 CK_UserDefinedConversion, Result.get(), 0,
5181 Result.get()->getValueKind());
5182 return false;
5183}
5184
5185static ExprResult finishContextualImplicitConversion(
5186 Sema &SemaRef, SourceLocation Loc, Expr *From,
5187 Sema::ContextualImplicitConverter &Converter) {
5188 if (!Converter.match(From->getType()) && !Converter.Suppress)
5189 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5190 << From->getSourceRange();
5191
5192 return SemaRef.DefaultLvalueConversion(From);
5193}
5194
5195static void
5196collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5197 UnresolvedSetImpl &ViableConversions,
5198 OverloadCandidateSet &CandidateSet) {
5199 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5200 DeclAccessPair FoundDecl = ViableConversions[I];
5201 NamedDecl *D = FoundDecl.getDecl();
5202 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5203 if (isa<UsingShadowDecl>(D))
5204 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5205
5206 CXXConversionDecl *Conv;
5207 FunctionTemplateDecl *ConvTemplate;
5208 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5209 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5210 else
5211 Conv = cast<CXXConversionDecl>(D);
5212
5213 if (ConvTemplate)
5214 SemaRef.AddTemplateConversionCandidate(
5215 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5216 else
5217 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5218 ToType, CandidateSet);
5219 }
5220}
5221
Richard Smith097e0a22013-05-21 19:05:48 +00005222/// \brief Attempt to convert the given expression to a type which is accepted
5223/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005224///
Richard Smith097e0a22013-05-21 19:05:48 +00005225/// This routine will attempt to convert an expression of class type to a
5226/// type accepted by the specified converter. In C++11 and before, the class
5227/// must have a single non-explicit conversion function converting to a matching
5228/// type. In C++1y, there can be multiple such conversion functions, but only
5229/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005230///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005231/// \param Loc The source location of the construct that requires the
5232/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005233///
James Dennett40ae6662012-06-22 08:52:37 +00005234/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005235///
Richard Smith097e0a22013-05-21 19:05:48 +00005236/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005237///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005238/// \returns The expression, converted to an integral or enumeration type if
5239/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005240ExprResult Sema::PerformContextualImplicitConversion(
5241 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005242 // We can't perform any more checking for type-dependent expressions.
5243 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005244 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005245
Eli Friedmanceccab92012-01-26 00:26:18 +00005246 // Process placeholders immediately.
5247 if (From->hasPlaceholderType()) {
5248 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005249 if (result.isInvalid())
5250 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005251 From = result.take();
5252 }
5253
Richard Smith097e0a22013-05-21 19:05:48 +00005254 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005255 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005256 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005257 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005258
5259 // FIXME: Check for missing '()' if T is a function type?
5260
Richard Smith097e0a22013-05-21 19:05:48 +00005261 // We can only perform contextual implicit conversions on objects of class
5262 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005263 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005264 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005265 if (!Converter.Suppress)
5266 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005267 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005269
Douglas Gregorc30614b2010-06-29 23:17:37 +00005270 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005271 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005272 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005273 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005274
5275 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5276 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5277
Douglas Gregord10099e2012-05-04 16:32:21 +00005278 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005279 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005280 }
Richard Smith097e0a22013-05-21 19:05:48 +00005281 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005282
5283 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005284 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005285
Douglas Gregorc30614b2010-06-29 23:17:37 +00005286 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005287 UnresolvedSet<4>
5288 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005289 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005290 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005291 CXXRecordDecl::conversion_iterator> Conversions =
5292 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005293
Larisse Voufo50b60b32013-06-10 06:50:24 +00005294 bool HadMultipleCandidates =
5295 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005296
Larisse Voufo50b60b32013-06-10 06:50:24 +00005297 // To check that there is only one target type, in C++1y:
5298 QualType ToType;
5299 bool HasUniqueTargetType = true;
5300
5301 // Collect explicit or viable (potentially in C++1y) conversions.
5302 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5303 E = Conversions.second;
5304 I != E; ++I) {
5305 NamedDecl *D = (*I)->getUnderlyingDecl();
5306 CXXConversionDecl *Conversion;
5307 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5308 if (ConvTemplate) {
5309 if (getLangOpts().CPlusPlus1y)
5310 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5311 else
5312 continue; // C++11 does not consider conversion operator templates(?).
5313 } else
5314 Conversion = cast<CXXConversionDecl>(D);
5315
5316 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5317 "Conversion operator templates are considered potentially "
5318 "viable in C++1y");
5319
5320 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5321 if (Converter.match(CurToType) || ConvTemplate) {
5322
5323 if (Conversion->isExplicit()) {
5324 // FIXME: For C++1y, do we need this restriction?
5325 // cf. diagnoseNoViableConversion()
5326 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005327 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005328 } else {
5329 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5330 if (ToType.isNull())
5331 ToType = CurToType.getUnqualifiedType();
5332 else if (HasUniqueTargetType &&
5333 (CurToType.getUnqualifiedType() != ToType))
5334 HasUniqueTargetType = false;
5335 }
5336 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005337 }
Richard Smithf39aec12012-02-04 07:07:42 +00005338 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005339 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005340
Larisse Voufo50b60b32013-06-10 06:50:24 +00005341 if (getLangOpts().CPlusPlus1y) {
5342 // C++1y [conv]p6:
5343 // ... An expression e of class type E appearing in such a context
5344 // is said to be contextually implicitly converted to a specified
5345 // type T and is well-formed if and only if e can be implicitly
5346 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005347 // for conversion functions whose return type is cv T or reference to
5348 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005349 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005350
Larisse Voufo50b60b32013-06-10 06:50:24 +00005351 // If no unique T is found:
5352 if (ToType.isNull()) {
5353 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5354 HadMultipleCandidates,
5355 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005356 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005357 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005359
Larisse Voufo50b60b32013-06-10 06:50:24 +00005360 // If more than one unique Ts are found:
5361 if (!HasUniqueTargetType)
5362 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5363 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005364
Larisse Voufo50b60b32013-06-10 06:50:24 +00005365 // If one unique T is found:
5366 // First, build a candidate set from the previously recorded
5367 // potentially viable conversions.
5368 OverloadCandidateSet CandidateSet(Loc);
5369 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5370 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005371
Larisse Voufo50b60b32013-06-10 06:50:24 +00005372 // Then, perform overload resolution over the candidate set.
5373 OverloadCandidateSet::iterator Best;
5374 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5375 case OR_Success: {
5376 // Apply this conversion.
5377 DeclAccessPair Found =
5378 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5379 if (recordConversion(*this, Loc, From, Converter, T,
5380 HadMultipleCandidates, Found))
5381 return ExprError();
5382 break;
5383 }
5384 case OR_Ambiguous:
5385 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5386 ViableConversions);
5387 case OR_No_Viable_Function:
5388 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5389 HadMultipleCandidates,
5390 ExplicitConversions))
5391 return ExprError();
5392 // fall through 'OR_Deleted' case.
5393 case OR_Deleted:
5394 // We'll complain below about a non-integral condition type.
5395 break;
5396 }
5397 } else {
5398 switch (ViableConversions.size()) {
5399 case 0: {
5400 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5401 HadMultipleCandidates,
5402 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005403 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005404
Larisse Voufo50b60b32013-06-10 06:50:24 +00005405 // We'll complain below about a non-integral condition type.
5406 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005407 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005408 case 1: {
5409 // Apply this conversion.
5410 DeclAccessPair Found = ViableConversions[0];
5411 if (recordConversion(*this, Loc, From, Converter, T,
5412 HadMultipleCandidates, Found))
5413 return ExprError();
5414 break;
5415 }
5416 default:
5417 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5418 ViableConversions);
5419 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005420 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005421
Larisse Voufo50b60b32013-06-10 06:50:24 +00005422 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005423}
5424
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005425/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005426/// candidate functions, using the given function call arguments. If
5427/// @p SuppressUserConversions, then don't allow user-defined
5428/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005429///
James Dennett699c9042012-06-15 07:13:21 +00005430/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005431/// based on an incomplete set of function arguments. This feature is used by
5432/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005433void
5434Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005435 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005436 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005437 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005438 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005439 bool PartialOverloading,
5440 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005441 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005442 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005443 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005444 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005445 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005446
Douglas Gregor88a35142008-12-22 05:46:06 +00005447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005448 if (!isa<CXXConstructorDecl>(Method)) {
5449 // If we get here, it's because we're calling a member function
5450 // that is named without a member access expression (e.g.,
5451 // "this->f") that was either written explicitly or created
5452 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005453 // function, e.g., X::f(). We use an empty type for the implied
5454 // object argument (C++ [over.call.func]p3), and the acting context
5455 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005456 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005457 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005458 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005459 return;
5460 }
5461 // We treat a constructor like a non-member function, since its object
5462 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005463 }
5464
Douglas Gregorfd476482009-11-13 23:59:09 +00005465 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005466 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005467
Douglas Gregor7edfb692009-11-23 12:27:39 +00005468 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005469 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005470
Douglas Gregor66724ea2009-11-14 01:20:54 +00005471 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5472 // C++ [class.copy]p3:
5473 // A member function template is never instantiated to perform the copy
5474 // of a class object to an object of its class type.
5475 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005476 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005477 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005478 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5479 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005480 return;
5481 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005482
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005483 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005484 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005485 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005486 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005487 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005488 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005489 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005490 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005491
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005492 unsigned NumArgsInProto = Proto->getNumArgs();
5493
5494 // (C++ 13.3.2p2): A candidate function having fewer than m
5495 // parameters is viable only if it has an ellipsis in its parameter
5496 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005497 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005498 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005499 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005500 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005501 return;
5502 }
5503
5504 // (C++ 13.3.2p2): A candidate function having more than m parameters
5505 // is viable only if the (m+1)st parameter has a default argument
5506 // (8.3.6). For the purposes of overload resolution, the
5507 // parameter list is truncated on the right, so that there are
5508 // exactly m parameters.
5509 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005510 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005511 // Not enough arguments.
5512 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005513 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005514 return;
5515 }
5516
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005517 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005518 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005519 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5520 if (CheckCUDATarget(Caller, Function)) {
5521 Candidate.Viable = false;
5522 Candidate.FailureKind = ovl_fail_bad_target;
5523 return;
5524 }
5525
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005526 // Determine the implicit conversion sequences for each of the
5527 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005528 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005529 if (ArgIdx < NumArgsInProto) {
5530 // (C++ 13.3.2p3): for F to be a viable function, there shall
5531 // exist for each argument an implicit conversion sequence
5532 // (13.3.3.1) that converts that argument to the corresponding
5533 // parameter of F.
5534 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005535 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005536 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005537 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005538 /*InOverloadResolution=*/true,
5539 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005540 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005541 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005542 if (Candidate.Conversions[ArgIdx].isBad()) {
5543 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005544 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005545 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005546 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005547 } else {
5548 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5549 // argument for which there is no corresponding parameter is
5550 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005551 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005552 }
5553 }
5554}
5555
Douglas Gregor063daf62009-03-13 18:40:31 +00005556/// \brief Add all of the function declarations in the given function set to
5557/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005558void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005559 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005560 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005561 bool SuppressUserConversions,
5562 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005563 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005564 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5565 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005566 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005567 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005568 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005569 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005570 Args.slice(1), CandidateSet,
5571 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005572 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005573 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005574 SuppressUserConversions);
5575 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005576 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005577 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5578 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005579 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005580 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005581 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005582 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005583 Args[0]->Classify(Context), Args.slice(1),
5584 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005585 else
John McCall9aa472c2010-03-19 07:35:19 +00005586 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005587 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005588 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005589 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005590 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005591}
5592
John McCall314be4e2009-11-17 07:50:12 +00005593/// AddMethodCandidate - Adds a named decl (which is some kind of
5594/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005595void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005596 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005597 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005598 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005599 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005600 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005601 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005602 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005603
5604 if (isa<UsingShadowDecl>(Decl))
5605 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005606
John McCall314be4e2009-11-17 07:50:12 +00005607 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5608 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5609 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005610 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5611 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005612 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005613 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005614 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005615 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005616 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005617 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005618 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005619 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005620 }
5621}
5622
Douglas Gregor96176b32008-11-18 23:14:02 +00005623/// AddMethodCandidate - Adds the given C++ member function to the set
5624/// of candidate functions, using the given function call arguments
5625/// and the object argument (@c Object). For example, in a call
5626/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5627/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5628/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005629/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005630void
John McCall9aa472c2010-03-19 07:35:19 +00005631Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005632 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005633 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005634 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005635 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005636 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005637 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005638 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005639 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005640 assert(!isa<CXXConstructorDecl>(Method) &&
5641 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005642
Douglas Gregor3f396022009-09-28 04:47:19 +00005643 if (!CandidateSet.isNewCandidate(Method))
5644 return;
5645
Douglas Gregor7edfb692009-11-23 12:27:39 +00005646 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005647 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005648
Douglas Gregor96176b32008-11-18 23:14:02 +00005649 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005650 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005651 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005652 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005653 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005654 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005655 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005656
5657 unsigned NumArgsInProto = Proto->getNumArgs();
5658
5659 // (C++ 13.3.2p2): A candidate function having fewer than m
5660 // parameters is viable only if it has an ellipsis in its parameter
5661 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005662 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005663 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005664 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005665 return;
5666 }
5667
5668 // (C++ 13.3.2p2): A candidate function having more than m parameters
5669 // is viable only if the (m+1)st parameter has a default argument
5670 // (8.3.6). For the purposes of overload resolution, the
5671 // parameter list is truncated on the right, so that there are
5672 // exactly m parameters.
5673 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005674 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005675 // Not enough arguments.
5676 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005677 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005678 return;
5679 }
5680
5681 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005682
John McCall701c89e2009-12-03 04:06:58 +00005683 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005684 // The implicit object argument is ignored.
5685 Candidate.IgnoreObjectArgument = true;
5686 else {
5687 // Determine the implicit conversion sequence for the object
5688 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005689 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005690 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5691 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005692 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005693 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005694 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005695 return;
5696 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005697 }
5698
5699 // Determine the implicit conversion sequences for each of the
5700 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005701 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005702 if (ArgIdx < NumArgsInProto) {
5703 // (C++ 13.3.2p3): for F to be a viable function, there shall
5704 // exist for each argument an implicit conversion sequence
5705 // (13.3.3.1) that converts that argument to the corresponding
5706 // parameter of F.
5707 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005708 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005709 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005710 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005711 /*InOverloadResolution=*/true,
5712 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005713 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005714 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005715 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005716 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005717 break;
5718 }
5719 } else {
5720 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5721 // argument for which there is no corresponding parameter is
5722 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005723 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005724 }
5725 }
5726}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005727
Douglas Gregor6b906862009-08-21 00:16:32 +00005728/// \brief Add a C++ member function template as a candidate to the candidate
5729/// set, using template argument deduction to produce an appropriate member
5730/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005731void
Douglas Gregor6b906862009-08-21 00:16:32 +00005732Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005733 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005734 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005735 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005736 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005737 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005738 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005739 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005740 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005741 if (!CandidateSet.isNewCandidate(MethodTmpl))
5742 return;
5743
Douglas Gregor6b906862009-08-21 00:16:32 +00005744 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005745 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005746 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005747 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005748 // candidate functions in the usual way.113) A given name can refer to one
5749 // or more function templates and also to a set of overloaded non-template
5750 // functions. In such a case, the candidate functions generated from each
5751 // function template are combined with the set of non-template candidate
5752 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005753 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005754 FunctionDecl *Specialization = 0;
5755 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005756 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5757 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005758 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005759 Candidate.FoundDecl = FoundDecl;
5760 Candidate.Function = MethodTmpl->getTemplatedDecl();
5761 Candidate.Viable = false;
5762 Candidate.FailureKind = ovl_fail_bad_deduction;
5763 Candidate.IsSurrogate = false;
5764 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005765 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005766 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005767 Info);
5768 return;
5769 }
Mike Stump1eb44332009-09-09 15:08:12 +00005770
Douglas Gregor6b906862009-08-21 00:16:32 +00005771 // Add the function template specialization produced by template argument
5772 // deduction as a candidate.
5773 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005774 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005775 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005776 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005777 ActingContext, ObjectType, ObjectClassification, Args,
5778 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005779}
5780
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005781/// \brief Add a C++ function template specialization as a candidate
5782/// in the candidate set, using template argument deduction to produce
5783/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005784void
Douglas Gregore53060f2009-06-25 22:08:12 +00005785Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005786 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005787 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005788 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005789 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005790 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005791 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5792 return;
5793
Douglas Gregore53060f2009-06-25 22:08:12 +00005794 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005795 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005796 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005797 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005798 // candidate functions in the usual way.113) A given name can refer to one
5799 // or more function templates and also to a set of overloaded non-template
5800 // functions. In such a case, the candidate functions generated from each
5801 // function template are combined with the set of non-template candidate
5802 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005803 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005804 FunctionDecl *Specialization = 0;
5805 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005806 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5807 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005808 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005809 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005810 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5811 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005812 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005813 Candidate.IsSurrogate = false;
5814 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005815 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005816 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005817 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005818 return;
5819 }
Mike Stump1eb44332009-09-09 15:08:12 +00005820
Douglas Gregore53060f2009-06-25 22:08:12 +00005821 // Add the function template specialization produced by template argument
5822 // deduction as a candidate.
5823 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005824 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005825 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005826}
Mike Stump1eb44332009-09-09 15:08:12 +00005827
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005828/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005829/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005830/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005831/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005832/// (which may or may not be the same type as the type that the
5833/// conversion function produces).
5834void
5835Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005836 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005837 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005838 Expr *From, QualType ToType,
5839 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005840 assert(!Conversion->getDescribedFunctionTemplate() &&
5841 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005842 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005843 if (!CandidateSet.isNewCandidate(Conversion))
5844 return;
5845
Richard Smith60e141e2013-05-04 07:00:32 +00005846 // If the conversion function has an undeduced return type, trigger its
5847 // deduction now.
5848 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5849 if (DeduceReturnType(Conversion, From->getExprLoc()))
5850 return;
5851 ConvType = Conversion->getConversionType().getNonReferenceType();
5852 }
5853
Douglas Gregor7edfb692009-11-23 12:27:39 +00005854 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005855 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005856
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005857 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005858 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005859 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005860 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005861 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005862 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005863 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005864 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005865 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005866 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005867 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005868
Douglas Gregorbca39322010-08-19 15:37:02 +00005869 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005870 // For conversion functions, the function is considered to be a member of
5871 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005872 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005873 //
5874 // Determine the implicit conversion sequence for the implicit
5875 // object parameter.
5876 QualType ImplicitParamType = From->getType();
5877 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5878 ImplicitParamType = FromPtrType->getPointeeType();
5879 CXXRecordDecl *ConversionContext
5880 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005881
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005882 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005883 = TryObjectArgumentInitialization(*this, From->getType(),
5884 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005885 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005886
John McCall1d318332010-01-12 00:44:57 +00005887 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005888 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005889 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005890 return;
5891 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005892
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005893 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005894 // derived to base as such conversions are given Conversion Rank. They only
5895 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5896 QualType FromCanon
5897 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5898 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5899 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5900 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005901 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005902 return;
5903 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005904
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005905 // To determine what the conversion from the result of calling the
5906 // conversion function to the type we're eventually trying to
5907 // convert to (ToType), we need to synthesize a call to the
5908 // conversion function and attempt copy initialization from it. This
5909 // makes sure that we get the right semantics with respect to
5910 // lvalues/rvalues and the type. Fortunately, we can allocate this
5911 // call on the stack and we don't need its arguments to be
5912 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005913 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005914 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005915 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5916 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005917 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005918 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005919
Richard Smith87c1f1f2011-07-13 22:53:21 +00005920 QualType ConversionType = Conversion->getConversionType();
5921 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005922 Candidate.Viable = false;
5923 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5924 return;
5925 }
5926
Richard Smith87c1f1f2011-07-13 22:53:21 +00005927 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005928
Mike Stump1eb44332009-09-09 15:08:12 +00005929 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005930 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5931 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005932 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005933 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005934 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005935 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005936 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005937 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005938 /*InOverloadResolution=*/false,
5939 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005940
John McCall1d318332010-01-12 00:44:57 +00005941 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005942 case ImplicitConversionSequence::StandardConversion:
5943 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005944
Douglas Gregorc520c842010-04-12 23:42:09 +00005945 // C++ [over.ics.user]p3:
5946 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005947 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005948 // shall have exact match rank.
5949 if (Conversion->getPrimaryTemplate() &&
5950 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5951 Candidate.Viable = false;
5952 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5953 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005954
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005955 // C++0x [dcl.init.ref]p5:
5956 // In the second case, if the reference is an rvalue reference and
5957 // the second standard conversion sequence of the user-defined
5958 // conversion sequence includes an lvalue-to-rvalue conversion, the
5959 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005960 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005961 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5962 Candidate.Viable = false;
5963 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5964 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005965 break;
5966
5967 case ImplicitConversionSequence::BadConversion:
5968 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005969 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005970 break;
5971
5972 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005973 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005974 "Can only end up with a standard conversion sequence or failure");
5975 }
5976}
5977
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005978/// \brief Adds a conversion function template specialization
5979/// candidate to the overload set, using template argument deduction
5980/// to deduce the template arguments of the conversion function
5981/// template from the type that we are converting to (C++
5982/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005983void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005984Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005985 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005986 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005987 Expr *From, QualType ToType,
5988 OverloadCandidateSet &CandidateSet) {
5989 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5990 "Only conversion function templates permitted here");
5991
Douglas Gregor3f396022009-09-28 04:47:19 +00005992 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5993 return;
5994
Craig Topper93e45992012-09-19 02:26:47 +00005995 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005996 CXXConversionDecl *Specialization = 0;
5997 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005998 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005999 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006000 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00006001 Candidate.FoundDecl = FoundDecl;
6002 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6003 Candidate.Viable = false;
6004 Candidate.FailureKind = ovl_fail_bad_deduction;
6005 Candidate.IsSurrogate = false;
6006 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006007 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006008 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00006009 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006010 return;
6011 }
Mike Stump1eb44332009-09-09 15:08:12 +00006012
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006013 // Add the conversion function template specialization produced by
6014 // template argument deduction as a candidate.
6015 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00006016 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00006017 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006018}
6019
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006020/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6021/// converts the given @c Object to a function pointer via the
6022/// conversion function @c Conversion, and then attempts to call it
6023/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6024/// the type of function that we'll eventually be calling.
6025void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006026 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006027 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006028 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006029 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006030 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006031 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006032 if (!CandidateSet.isNewCandidate(Conversion))
6033 return;
6034
Douglas Gregor7edfb692009-11-23 12:27:39 +00006035 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006036 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006037
Ahmed Charles13a140c2012-02-25 11:00:22 +00006038 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006039 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006040 Candidate.Function = 0;
6041 Candidate.Surrogate = Conversion;
6042 Candidate.Viable = true;
6043 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006044 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006045 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006046
6047 // Determine the implicit conversion sequence for the implicit
6048 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006049 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006050 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006051 Object->Classify(Context),
6052 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006053 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006054 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006055 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006056 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006057 return;
6058 }
6059
6060 // The first conversion is actually a user-defined conversion whose
6061 // first conversion is ObjectInit's standard conversion (which is
6062 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006063 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006064 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006065 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006066 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006067 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006068 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006069 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006070 = Candidate.Conversions[0].UserDefined.Before;
6071 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6072
Mike Stump1eb44332009-09-09 15:08:12 +00006073 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006074 unsigned NumArgsInProto = Proto->getNumArgs();
6075
6076 // (C++ 13.3.2p2): A candidate function having fewer than m
6077 // parameters is viable only if it has an ellipsis in its parameter
6078 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006079 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006080 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006081 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006082 return;
6083 }
6084
6085 // Function types don't have any default arguments, so just check if
6086 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006087 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006088 // Not enough arguments.
6089 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006090 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006091 return;
6092 }
6093
6094 // Determine the implicit conversion sequences for each of the
6095 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006096 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006097 if (ArgIdx < NumArgsInProto) {
6098 // (C++ 13.3.2p3): for F to be a viable function, there shall
6099 // exist for each argument an implicit conversion sequence
6100 // (13.3.3.1) that converts that argument to the corresponding
6101 // parameter of F.
6102 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006103 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006104 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006105 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006106 /*InOverloadResolution=*/false,
6107 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006108 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006109 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006110 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006111 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006112 break;
6113 }
6114 } else {
6115 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6116 // argument for which there is no corresponding parameter is
6117 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006118 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006119 }
6120 }
6121}
6122
Douglas Gregor063daf62009-03-13 18:40:31 +00006123/// \brief Add overload candidates for overloaded operators that are
6124/// member functions.
6125///
6126/// Add the overloaded operator candidates that are member functions
6127/// for the operator Op that was used in an operator expression such
6128/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6129/// CandidateSet will store the added overload candidates. (C++
6130/// [over.match.oper]).
6131void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6132 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006133 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006134 OverloadCandidateSet& CandidateSet,
6135 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006136 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6137
6138 // C++ [over.match.oper]p3:
6139 // For a unary operator @ with an operand of a type whose
6140 // cv-unqualified version is T1, and for a binary operator @ with
6141 // a left operand of a type whose cv-unqualified version is T1 and
6142 // a right operand of a type whose cv-unqualified version is T2,
6143 // three sets of candidate functions, designated member
6144 // candidates, non-member candidates and built-in candidates, are
6145 // constructed as follows:
6146 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006147
Richard Smithe410be92013-04-20 12:41:22 +00006148 // -- If T1 is a complete class type or a class currently being
6149 // defined, the set of member candidates is the result of the
6150 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6151 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006152 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006153 // Complete the type if it can be completed.
6154 RequireCompleteType(OpLoc, T1, 0);
6155 // If the type is neither complete nor being defined, bail out now.
6156 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006157 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006158
John McCalla24dc2e2009-11-17 02:14:36 +00006159 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6160 LookupQualifiedName(Operators, T1Rec->getDecl());
6161 Operators.suppressDiagnostics();
6162
Mike Stump1eb44332009-09-09 15:08:12 +00006163 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006164 OperEnd = Operators.end();
6165 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006166 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006167 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006168 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006169 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006170 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006171 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006172 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006173}
6174
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006175/// AddBuiltinCandidate - Add a candidate for a built-in
6176/// operator. ResultTy and ParamTys are the result and parameter types
6177/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006178/// arguments being passed to the candidate. IsAssignmentOperator
6179/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006180/// operator. NumContextualBoolArguments is the number of arguments
6181/// (at the beginning of the argument list) that will be contextually
6182/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006183void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006184 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006185 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006186 bool IsAssignmentOperator,
6187 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006188 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006189 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006190
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006191 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006192 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006193 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006194 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006195 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006196 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006197 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006198 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006199 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6200
6201 // Determine the implicit conversion sequences for each of the
6202 // arguments.
6203 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006204 Candidate.ExplicitCallArguments = Args.size();
6205 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006206 // C++ [over.match.oper]p4:
6207 // For the built-in assignment operators, conversions of the
6208 // left operand are restricted as follows:
6209 // -- no temporaries are introduced to hold the left operand, and
6210 // -- no user-defined conversions are applied to the left
6211 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006212 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006213 //
6214 // We block these conversions by turning off user-defined
6215 // conversions, since that is the only way that initialization of
6216 // a reference to a non-class type can occur from something that
6217 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006218 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006219 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006220 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006221 Candidate.Conversions[ArgIdx]
6222 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006223 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006224 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006225 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006226 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006227 /*InOverloadResolution=*/false,
6228 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006229 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006230 }
John McCall1d318332010-01-12 00:44:57 +00006231 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006232 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006233 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006234 break;
6235 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006236 }
6237}
6238
6239/// BuiltinCandidateTypeSet - A set of types that will be used for the
6240/// candidate operator functions for built-in operators (C++
6241/// [over.built]). The types are separated into pointer types and
6242/// enumeration types.
6243class BuiltinCandidateTypeSet {
6244 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006245 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006246
6247 /// PointerTypes - The set of pointer types that will be used in the
6248 /// built-in candidates.
6249 TypeSet PointerTypes;
6250
Sebastian Redl78eb8742009-04-19 21:53:20 +00006251 /// MemberPointerTypes - The set of member pointer types that will be
6252 /// used in the built-in candidates.
6253 TypeSet MemberPointerTypes;
6254
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006255 /// EnumerationTypes - The set of enumeration types that will be
6256 /// used in the built-in candidates.
6257 TypeSet EnumerationTypes;
6258
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006259 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006260 /// candidates.
6261 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006262
6263 /// \brief A flag indicating non-record types are viable candidates
6264 bool HasNonRecordTypes;
6265
6266 /// \brief A flag indicating whether either arithmetic or enumeration types
6267 /// were present in the candidate set.
6268 bool HasArithmeticOrEnumeralTypes;
6269
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006270 /// \brief A flag indicating whether the nullptr type was present in the
6271 /// candidate set.
6272 bool HasNullPtrType;
6273
Douglas Gregor5842ba92009-08-24 15:23:48 +00006274 /// Sema - The semantic analysis instance where we are building the
6275 /// candidate type set.
6276 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006277
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006278 /// Context - The AST context in which we will build the type sets.
6279 ASTContext &Context;
6280
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006281 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6282 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006283 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006284
6285public:
6286 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006287 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006288
Mike Stump1eb44332009-09-09 15:08:12 +00006289 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006290 : HasNonRecordTypes(false),
6291 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006292 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006293 SemaRef(SemaRef),
6294 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006295
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006296 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006297 SourceLocation Loc,
6298 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006299 bool AllowExplicitConversions,
6300 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006301
6302 /// pointer_begin - First pointer type found;
6303 iterator pointer_begin() { return PointerTypes.begin(); }
6304
Sebastian Redl78eb8742009-04-19 21:53:20 +00006305 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006306 iterator pointer_end() { return PointerTypes.end(); }
6307
Sebastian Redl78eb8742009-04-19 21:53:20 +00006308 /// member_pointer_begin - First member pointer type found;
6309 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6310
6311 /// member_pointer_end - Past the last member pointer type found;
6312 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6313
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006314 /// enumeration_begin - First enumeration type found;
6315 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6316
Sebastian Redl78eb8742009-04-19 21:53:20 +00006317 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006318 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006319
Douglas Gregor26bcf672010-05-19 03:21:00 +00006320 iterator vector_begin() { return VectorTypes.begin(); }
6321 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006322
6323 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6324 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006325 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006326};
6327
Sebastian Redl78eb8742009-04-19 21:53:20 +00006328/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006329/// the set of pointer types along with any more-qualified variants of
6330/// that type. For example, if @p Ty is "int const *", this routine
6331/// will add "int const *", "int const volatile *", "int const
6332/// restrict *", and "int const volatile restrict *" to the set of
6333/// pointer types. Returns true if the add of @p Ty itself succeeded,
6334/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006335///
6336/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006337bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006338BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6339 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006340
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006341 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006342 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006343 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006344
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006345 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006346 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006347 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006348 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006349 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6350 PointeeTy = PTy->getPointeeType();
6351 buildObjCPtr = true;
6352 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006353 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006354 }
6355
Sebastian Redla9efada2009-11-18 20:39:26 +00006356 // Don't add qualified variants of arrays. For one, they're not allowed
6357 // (the qualifier would sink to the element type), and for another, the
6358 // only overload situation where it matters is subscript or pointer +- int,
6359 // and those shouldn't have qualifier variants anyway.
6360 if (PointeeTy->isArrayType())
6361 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006362
John McCall0953e762009-09-24 19:53:00 +00006363 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006364 bool hasVolatile = VisibleQuals.hasVolatile();
6365 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006366
John McCall0953e762009-09-24 19:53:00 +00006367 // Iterate through all strict supersets of BaseCVR.
6368 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6369 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006370 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006371 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006372
6373 // Skip over restrict if no restrict found anywhere in the types, or if
6374 // the type cannot be restrict-qualified.
6375 if ((CVR & Qualifiers::Restrict) &&
6376 (!hasRestrict ||
6377 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6378 continue;
6379
6380 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006381 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006382
6383 // Build qualified pointer type.
6384 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006385 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006386 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006387 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006388 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6389
6390 // Insert qualified pointer type.
6391 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006392 }
6393
6394 return true;
6395}
6396
Sebastian Redl78eb8742009-04-19 21:53:20 +00006397/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6398/// to the set of pointer types along with any more-qualified variants of
6399/// that type. For example, if @p Ty is "int const *", this routine
6400/// will add "int const *", "int const volatile *", "int const
6401/// restrict *", and "int const volatile restrict *" to the set of
6402/// pointer types. Returns true if the add of @p Ty itself succeeded,
6403/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006404///
6405/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006406bool
6407BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6408 QualType Ty) {
6409 // Insert this type.
6410 if (!MemberPointerTypes.insert(Ty))
6411 return false;
6412
John McCall0953e762009-09-24 19:53:00 +00006413 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6414 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006415
John McCall0953e762009-09-24 19:53:00 +00006416 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006417 // Don't add qualified variants of arrays. For one, they're not allowed
6418 // (the qualifier would sink to the element type), and for another, the
6419 // only overload situation where it matters is subscript or pointer +- int,
6420 // and those shouldn't have qualifier variants anyway.
6421 if (PointeeTy->isArrayType())
6422 return true;
John McCall0953e762009-09-24 19:53:00 +00006423 const Type *ClassTy = PointerTy->getClass();
6424
6425 // Iterate through all strict supersets of the pointee type's CVR
6426 // qualifiers.
6427 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6428 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6429 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006430
John McCall0953e762009-09-24 19:53:00 +00006431 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006432 MemberPointerTypes.insert(
6433 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006434 }
6435
6436 return true;
6437}
6438
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006439/// AddTypesConvertedFrom - Add each of the types to which the type @p
6440/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006441/// primarily interested in pointer types and enumeration types. We also
6442/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006443/// AllowUserConversions is true if we should look at the conversion
6444/// functions of a class type, and AllowExplicitConversions if we
6445/// should also include the explicit conversion functions of a class
6446/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006447void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006448BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006449 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006450 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006451 bool AllowExplicitConversions,
6452 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006453 // Only deal with canonical types.
6454 Ty = Context.getCanonicalType(Ty);
6455
6456 // Look through reference types; they aren't part of the type of an
6457 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006458 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006459 Ty = RefTy->getPointeeType();
6460
John McCall3b657512011-01-19 10:06:00 +00006461 // If we're dealing with an array type, decay to the pointer.
6462 if (Ty->isArrayType())
6463 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6464
6465 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006466 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006467
Chandler Carruth6a577462010-12-13 01:44:01 +00006468 // Flag if we ever add a non-record type.
6469 const RecordType *TyRec = Ty->getAs<RecordType>();
6470 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6471
Chandler Carruth6a577462010-12-13 01:44:01 +00006472 // Flag if we encounter an arithmetic type.
6473 HasArithmeticOrEnumeralTypes =
6474 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6475
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006476 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6477 PointerTypes.insert(Ty);
6478 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006479 // Insert our type, and its more-qualified variants, into the set
6480 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006481 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006482 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006483 } else if (Ty->isMemberPointerType()) {
6484 // Member pointers are far easier, since the pointee can't be converted.
6485 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6486 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006487 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006488 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006489 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006490 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006491 // We treat vector types as arithmetic types in many contexts as an
6492 // extension.
6493 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006494 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006495 } else if (Ty->isNullPtrType()) {
6496 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006497 } else if (AllowUserConversions && TyRec) {
6498 // No conversion functions in incomplete types.
6499 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6500 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006501
Chandler Carruth6a577462010-12-13 01:44:01 +00006502 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006503 std::pair<CXXRecordDecl::conversion_iterator,
6504 CXXRecordDecl::conversion_iterator>
6505 Conversions = ClassDecl->getVisibleConversionFunctions();
6506 for (CXXRecordDecl::conversion_iterator
6507 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006508 NamedDecl *D = I.getDecl();
6509 if (isa<UsingShadowDecl>(D))
6510 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006511
Chandler Carruth6a577462010-12-13 01:44:01 +00006512 // Skip conversion function templates; they don't tell us anything
6513 // about which builtin types we can convert to.
6514 if (isa<FunctionTemplateDecl>(D))
6515 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006516
Chandler Carruth6a577462010-12-13 01:44:01 +00006517 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6518 if (AllowExplicitConversions || !Conv->isExplicit()) {
6519 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6520 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006521 }
6522 }
6523 }
6524}
6525
Douglas Gregor19b7b152009-08-24 13:43:27 +00006526/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6527/// the volatile- and non-volatile-qualified assignment operators for the
6528/// given type to the candidate set.
6529static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6530 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006531 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006532 OverloadCandidateSet &CandidateSet) {
6533 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006534
Douglas Gregor19b7b152009-08-24 13:43:27 +00006535 // T& operator=(T&, T)
6536 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6537 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006538 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006539 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006540
Douglas Gregor19b7b152009-08-24 13:43:27 +00006541 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6542 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006543 ParamTypes[0]
6544 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006545 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006546 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006547 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006548 }
6549}
Mike Stump1eb44332009-09-09 15:08:12 +00006550
Sebastian Redl9994a342009-10-25 17:03:50 +00006551/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6552/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006553static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6554 Qualifiers VRQuals;
6555 const RecordType *TyRec;
6556 if (const MemberPointerType *RHSMPType =
6557 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006558 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006559 else
6560 TyRec = ArgExpr->getType()->getAs<RecordType>();
6561 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006562 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006563 VRQuals.addVolatile();
6564 VRQuals.addRestrict();
6565 return VRQuals;
6566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006567
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006568 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006569 if (!ClassDecl->hasDefinition())
6570 return VRQuals;
6571
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006572 std::pair<CXXRecordDecl::conversion_iterator,
6573 CXXRecordDecl::conversion_iterator>
6574 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006575
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006576 for (CXXRecordDecl::conversion_iterator
6577 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006578 NamedDecl *D = I.getDecl();
6579 if (isa<UsingShadowDecl>(D))
6580 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6581 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006582 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6583 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6584 CanTy = ResTypeRef->getPointeeType();
6585 // Need to go down the pointer/mempointer chain and add qualifiers
6586 // as see them.
6587 bool done = false;
6588 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006589 if (CanTy.isRestrictQualified())
6590 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006591 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6592 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006593 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006594 CanTy->getAs<MemberPointerType>())
6595 CanTy = ResTypeMPtr->getPointeeType();
6596 else
6597 done = true;
6598 if (CanTy.isVolatileQualified())
6599 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006600 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6601 return VRQuals;
6602 }
6603 }
6604 }
6605 return VRQuals;
6606}
John McCall00071ec2010-11-13 05:51:15 +00006607
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006608namespace {
John McCall00071ec2010-11-13 05:51:15 +00006609
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006610/// \brief Helper class to manage the addition of builtin operator overload
6611/// candidates. It provides shared state and utility methods used throughout
6612/// the process, as well as a helper method to add each group of builtin
6613/// operator overloads from the standard to a candidate set.
6614class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006615 // Common instance state available to all overload candidate addition methods.
6616 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006617 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006618 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006619 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006620 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006621 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006622
Chandler Carruth6d695582010-12-12 10:35:00 +00006623 // Define some constants used to index and iterate over the arithemetic types
6624 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006625 // The "promoted arithmetic types" are the arithmetic
6626 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006627 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006628 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006629 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006630 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006631 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006632 LastPromotedArithmeticType = 11;
6633 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006634
Chandler Carruth6d695582010-12-12 10:35:00 +00006635 /// \brief Get the canonical type for a given arithmetic type index.
6636 CanQualType getArithmeticType(unsigned index) {
6637 assert(index < NumArithmeticTypes);
6638 static CanQualType ASTContext::* const
6639 ArithmeticTypes[NumArithmeticTypes] = {
6640 // Start of promoted types.
6641 &ASTContext::FloatTy,
6642 &ASTContext::DoubleTy,
6643 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006644
Chandler Carruth6d695582010-12-12 10:35:00 +00006645 // Start of integral types.
6646 &ASTContext::IntTy,
6647 &ASTContext::LongTy,
6648 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006649 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006650 &ASTContext::UnsignedIntTy,
6651 &ASTContext::UnsignedLongTy,
6652 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006653 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006654 // End of promoted types.
6655
6656 &ASTContext::BoolTy,
6657 &ASTContext::CharTy,
6658 &ASTContext::WCharTy,
6659 &ASTContext::Char16Ty,
6660 &ASTContext::Char32Ty,
6661 &ASTContext::SignedCharTy,
6662 &ASTContext::ShortTy,
6663 &ASTContext::UnsignedCharTy,
6664 &ASTContext::UnsignedShortTy,
6665 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006666 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006667 };
6668 return S.Context.*ArithmeticTypes[index];
6669 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006670
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006671 /// \brief Gets the canonical type resulting from the usual arithemetic
6672 /// converions for the given arithmetic types.
6673 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6674 // Accelerator table for performing the usual arithmetic conversions.
6675 // The rules are basically:
6676 // - if either is floating-point, use the wider floating-point
6677 // - if same signedness, use the higher rank
6678 // - if same size, use unsigned of the higher rank
6679 // - use the larger type
6680 // These rules, together with the axiom that higher ranks are
6681 // never smaller, are sufficient to precompute all of these results
6682 // *except* when dealing with signed types of higher rank.
6683 // (we could precompute SLL x UI for all known platforms, but it's
6684 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006685 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006686 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006687 Dep=-1,
6688 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006689 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006690 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006691 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006692/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6693/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6694/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6695/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6696/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6697/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6698/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6699/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6700/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6701/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6702/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006703 };
6704
6705 assert(L < LastPromotedArithmeticType);
6706 assert(R < LastPromotedArithmeticType);
6707 int Idx = ConversionsTable[L][R];
6708
6709 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006710 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006711
6712 // Slow path: we need to compare widths.
6713 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006714 CanQualType LT = getArithmeticType(L),
6715 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006716 unsigned LW = S.Context.getIntWidth(LT),
6717 RW = S.Context.getIntWidth(RT);
6718
6719 // If they're different widths, use the signed type.
6720 if (LW > RW) return LT;
6721 else if (LW < RW) return RT;
6722
6723 // Otherwise, use the unsigned type of the signed type's rank.
6724 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6725 assert(L == SLL || R == SLL);
6726 return S.Context.UnsignedLongLongTy;
6727 }
6728
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006729 /// \brief Helper method to factor out the common pattern of adding overloads
6730 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006731 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006732 bool HasVolatile,
6733 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006734 QualType ParamTypes[2] = {
6735 S.Context.getLValueReferenceType(CandidateTy),
6736 S.Context.IntTy
6737 };
6738
6739 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006740 if (Args.size() == 1)
6741 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006742 else
Richard Smith958ba642013-05-05 15:51:06 +00006743 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006744
6745 // Use a heuristic to reduce number of builtin candidates in the set:
6746 // add volatile version only if there are conversions to a volatile type.
6747 if (HasVolatile) {
6748 ParamTypes[0] =
6749 S.Context.getLValueReferenceType(
6750 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006751 if (Args.size() == 1)
6752 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006753 else
Richard Smith958ba642013-05-05 15:51:06 +00006754 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006755 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006756
6757 // Add restrict version only if there are conversions to a restrict type
6758 // and our candidate type is a non-restrict-qualified pointer.
6759 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6760 !CandidateTy.isRestrictQualified()) {
6761 ParamTypes[0]
6762 = S.Context.getLValueReferenceType(
6763 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006764 if (Args.size() == 1)
6765 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006766 else
Richard Smith958ba642013-05-05 15:51:06 +00006767 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006768
6769 if (HasVolatile) {
6770 ParamTypes[0]
6771 = S.Context.getLValueReferenceType(
6772 S.Context.getCVRQualifiedType(CandidateTy,
6773 (Qualifiers::Volatile |
6774 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006775 if (Args.size() == 1)
6776 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006777 else
Richard Smith958ba642013-05-05 15:51:06 +00006778 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006779 }
6780 }
6781
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006782 }
6783
6784public:
6785 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006786 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006787 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006788 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006789 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006790 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006791 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006792 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006793 HasArithmeticOrEnumeralCandidateType(
6794 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006795 CandidateTypes(CandidateTypes),
6796 CandidateSet(CandidateSet) {
6797 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006798 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006799 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006800 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006801 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006802 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006803 assert(getArithmeticType(FirstPromotedArithmeticType)
6804 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006805 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006806 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006807 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006808 "Invalid last promoted arithmetic type");
6809 }
6810
6811 // C++ [over.built]p3:
6812 //
6813 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6814 // is either volatile or empty, there exist candidate operator
6815 // functions of the form
6816 //
6817 // VQ T& operator++(VQ T&);
6818 // T operator++(VQ T&, int);
6819 //
6820 // C++ [over.built]p4:
6821 //
6822 // For every pair (T, VQ), where T is an arithmetic type other
6823 // than bool, and VQ is either volatile or empty, there exist
6824 // candidate operator functions of the form
6825 //
6826 // VQ T& operator--(VQ T&);
6827 // T operator--(VQ T&, int);
6828 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006829 if (!HasArithmeticOrEnumeralCandidateType)
6830 return;
6831
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006832 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6833 Arith < NumArithmeticTypes; ++Arith) {
6834 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006835 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006836 VisibleTypeConversionsQuals.hasVolatile(),
6837 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006838 }
6839 }
6840
6841 // C++ [over.built]p5:
6842 //
6843 // For every pair (T, VQ), where T is a cv-qualified or
6844 // cv-unqualified object type, and VQ is either volatile or
6845 // empty, there exist candidate operator functions of the form
6846 //
6847 // T*VQ& operator++(T*VQ&);
6848 // T*VQ& operator--(T*VQ&);
6849 // T* operator++(T*VQ&, int);
6850 // T* operator--(T*VQ&, int);
6851 void addPlusPlusMinusMinusPointerOverloads() {
6852 for (BuiltinCandidateTypeSet::iterator
6853 Ptr = CandidateTypes[0].pointer_begin(),
6854 PtrEnd = CandidateTypes[0].pointer_end();
6855 Ptr != PtrEnd; ++Ptr) {
6856 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006857 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006858 continue;
6859
6860 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006861 (!(*Ptr).isVolatileQualified() &&
6862 VisibleTypeConversionsQuals.hasVolatile()),
6863 (!(*Ptr).isRestrictQualified() &&
6864 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006865 }
6866 }
6867
6868 // C++ [over.built]p6:
6869 // For every cv-qualified or cv-unqualified object type T, there
6870 // exist candidate operator functions of the form
6871 //
6872 // T& operator*(T*);
6873 //
6874 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006875 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006876 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006877 // T& operator*(T*);
6878 void addUnaryStarPointerOverloads() {
6879 for (BuiltinCandidateTypeSet::iterator
6880 Ptr = CandidateTypes[0].pointer_begin(),
6881 PtrEnd = CandidateTypes[0].pointer_end();
6882 Ptr != PtrEnd; ++Ptr) {
6883 QualType ParamTy = *Ptr;
6884 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006885 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6886 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006887
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006888 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6889 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6890 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006891
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006892 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006893 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006894 }
6895 }
6896
6897 // C++ [over.built]p9:
6898 // For every promoted arithmetic type T, there exist candidate
6899 // operator functions of the form
6900 //
6901 // T operator+(T);
6902 // T operator-(T);
6903 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006904 if (!HasArithmeticOrEnumeralCandidateType)
6905 return;
6906
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006907 for (unsigned Arith = FirstPromotedArithmeticType;
6908 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006909 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006910 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006911 }
6912
6913 // Extension: We also add these operators for vector types.
6914 for (BuiltinCandidateTypeSet::iterator
6915 Vec = CandidateTypes[0].vector_begin(),
6916 VecEnd = CandidateTypes[0].vector_end();
6917 Vec != VecEnd; ++Vec) {
6918 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006919 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006920 }
6921 }
6922
6923 // C++ [over.built]p8:
6924 // For every type T, there exist candidate operator functions of
6925 // the form
6926 //
6927 // T* operator+(T*);
6928 void addUnaryPlusPointerOverloads() {
6929 for (BuiltinCandidateTypeSet::iterator
6930 Ptr = CandidateTypes[0].pointer_begin(),
6931 PtrEnd = CandidateTypes[0].pointer_end();
6932 Ptr != PtrEnd; ++Ptr) {
6933 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006934 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006935 }
6936 }
6937
6938 // C++ [over.built]p10:
6939 // For every promoted integral type T, there exist candidate
6940 // operator functions of the form
6941 //
6942 // T operator~(T);
6943 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006944 if (!HasArithmeticOrEnumeralCandidateType)
6945 return;
6946
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006947 for (unsigned Int = FirstPromotedIntegralType;
6948 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006949 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006950 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006951 }
6952
6953 // Extension: We also add this operator for vector types.
6954 for (BuiltinCandidateTypeSet::iterator
6955 Vec = CandidateTypes[0].vector_begin(),
6956 VecEnd = CandidateTypes[0].vector_end();
6957 Vec != VecEnd; ++Vec) {
6958 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006959 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006960 }
6961 }
6962
6963 // C++ [over.match.oper]p16:
6964 // For every pointer to member type T, there exist candidate operator
6965 // functions of the form
6966 //
6967 // bool operator==(T,T);
6968 // bool operator!=(T,T);
6969 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6970 /// Set of (canonical) types that we've already handled.
6971 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6972
Richard Smith958ba642013-05-05 15:51:06 +00006973 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006974 for (BuiltinCandidateTypeSet::iterator
6975 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6976 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6977 MemPtr != MemPtrEnd;
6978 ++MemPtr) {
6979 // Don't add the same builtin candidate twice.
6980 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6981 continue;
6982
6983 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006984 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006985 }
6986 }
6987 }
6988
6989 // C++ [over.built]p15:
6990 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006991 // For every T, where T is an enumeration type, a pointer type, or
6992 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006993 //
6994 // bool operator<(T, T);
6995 // bool operator>(T, T);
6996 // bool operator<=(T, T);
6997 // bool operator>=(T, T);
6998 // bool operator==(T, T);
6999 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007000 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00007001 // C++ [over.match.oper]p3:
7002 // [...]the built-in candidates include all of the candidate operator
7003 // functions defined in 13.6 that, compared to the given operator, [...]
7004 // do not have the same parameter-type-list as any non-template non-member
7005 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007006 //
Eli Friedman97c67392012-09-18 21:52:24 +00007007 // Note that in practice, this only affects enumeration types because there
7008 // aren't any built-in candidates of record type, and a user-defined operator
7009 // must have an operand of record or enumeration type. Also, the only other
7010 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007011 // cannot be overloaded for enumeration types, so this is the only place
7012 // where we must suppress candidates like this.
7013 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7014 UserDefinedBinaryOperators;
7015
Richard Smith958ba642013-05-05 15:51:06 +00007016 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007017 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7018 CandidateTypes[ArgIdx].enumeration_end()) {
7019 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7020 CEnd = CandidateSet.end();
7021 C != CEnd; ++C) {
7022 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7023 continue;
7024
Eli Friedman97c67392012-09-18 21:52:24 +00007025 if (C->Function->isFunctionTemplateSpecialization())
7026 continue;
7027
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007028 QualType FirstParamType =
7029 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7030 QualType SecondParamType =
7031 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7032
7033 // Skip if either parameter isn't of enumeral type.
7034 if (!FirstParamType->isEnumeralType() ||
7035 !SecondParamType->isEnumeralType())
7036 continue;
7037
7038 // Add this operator to the set of known user-defined operators.
7039 UserDefinedBinaryOperators.insert(
7040 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7041 S.Context.getCanonicalType(SecondParamType)));
7042 }
7043 }
7044 }
7045
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007046 /// Set of (canonical) types that we've already handled.
7047 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7048
Richard Smith958ba642013-05-05 15:51:06 +00007049 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007050 for (BuiltinCandidateTypeSet::iterator
7051 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7052 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7053 Ptr != PtrEnd; ++Ptr) {
7054 // Don't add the same builtin candidate twice.
7055 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7056 continue;
7057
7058 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007059 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007060 }
7061 for (BuiltinCandidateTypeSet::iterator
7062 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7063 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7064 Enum != EnumEnd; ++Enum) {
7065 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7066
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007067 // Don't add the same builtin candidate twice, or if a user defined
7068 // candidate exists.
7069 if (!AddedTypes.insert(CanonType) ||
7070 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7071 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007072 continue;
7073
7074 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007075 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007076 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007077
7078 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7079 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7080 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007081 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007082 NullPtrTy))) {
7083 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007084 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007085 CandidateSet);
7086 }
7087 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007088 }
7089 }
7090
7091 // C++ [over.built]p13:
7092 //
7093 // For every cv-qualified or cv-unqualified object type T
7094 // there exist candidate operator functions of the form
7095 //
7096 // T* operator+(T*, ptrdiff_t);
7097 // T& operator[](T*, ptrdiff_t); [BELOW]
7098 // T* operator-(T*, ptrdiff_t);
7099 // T* operator+(ptrdiff_t, T*);
7100 // T& operator[](ptrdiff_t, T*); [BELOW]
7101 //
7102 // C++ [over.built]p14:
7103 //
7104 // For every T, where T is a pointer to object type, there
7105 // exist candidate operator functions of the form
7106 //
7107 // ptrdiff_t operator-(T, T);
7108 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7109 /// Set of (canonical) types that we've already handled.
7110 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7111
7112 for (int Arg = 0; Arg < 2; ++Arg) {
7113 QualType AsymetricParamTypes[2] = {
7114 S.Context.getPointerDiffType(),
7115 S.Context.getPointerDiffType(),
7116 };
7117 for (BuiltinCandidateTypeSet::iterator
7118 Ptr = CandidateTypes[Arg].pointer_begin(),
7119 PtrEnd = CandidateTypes[Arg].pointer_end();
7120 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007121 QualType PointeeTy = (*Ptr)->getPointeeType();
7122 if (!PointeeTy->isObjectType())
7123 continue;
7124
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007125 AsymetricParamTypes[Arg] = *Ptr;
7126 if (Arg == 0 || Op == OO_Plus) {
7127 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7128 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007129 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007130 }
7131 if (Op == OO_Minus) {
7132 // ptrdiff_t operator-(T, T);
7133 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7134 continue;
7135
7136 QualType ParamTypes[2] = { *Ptr, *Ptr };
7137 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007138 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007139 }
7140 }
7141 }
7142 }
7143
7144 // C++ [over.built]p12:
7145 //
7146 // For every pair of promoted arithmetic types L and R, there
7147 // exist candidate operator functions of the form
7148 //
7149 // LR operator*(L, R);
7150 // LR operator/(L, R);
7151 // LR operator+(L, R);
7152 // LR operator-(L, R);
7153 // bool operator<(L, R);
7154 // bool operator>(L, R);
7155 // bool operator<=(L, R);
7156 // bool operator>=(L, R);
7157 // bool operator==(L, R);
7158 // bool operator!=(L, R);
7159 //
7160 // where LR is the result of the usual arithmetic conversions
7161 // between types L and R.
7162 //
7163 // C++ [over.built]p24:
7164 //
7165 // For every pair of promoted arithmetic types L and R, there exist
7166 // candidate operator functions of the form
7167 //
7168 // LR operator?(bool, L, R);
7169 //
7170 // where LR is the result of the usual arithmetic conversions
7171 // between types L and R.
7172 // Our candidates ignore the first parameter.
7173 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007174 if (!HasArithmeticOrEnumeralCandidateType)
7175 return;
7176
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007177 for (unsigned Left = FirstPromotedArithmeticType;
7178 Left < LastPromotedArithmeticType; ++Left) {
7179 for (unsigned Right = FirstPromotedArithmeticType;
7180 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007181 QualType LandR[2] = { getArithmeticType(Left),
7182 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007183 QualType Result =
7184 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007185 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007186 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007187 }
7188 }
7189
7190 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7191 // conditional operator for vector types.
7192 for (BuiltinCandidateTypeSet::iterator
7193 Vec1 = CandidateTypes[0].vector_begin(),
7194 Vec1End = CandidateTypes[0].vector_end();
7195 Vec1 != Vec1End; ++Vec1) {
7196 for (BuiltinCandidateTypeSet::iterator
7197 Vec2 = CandidateTypes[1].vector_begin(),
7198 Vec2End = CandidateTypes[1].vector_end();
7199 Vec2 != Vec2End; ++Vec2) {
7200 QualType LandR[2] = { *Vec1, *Vec2 };
7201 QualType Result = S.Context.BoolTy;
7202 if (!isComparison) {
7203 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7204 Result = *Vec1;
7205 else
7206 Result = *Vec2;
7207 }
7208
Richard Smith958ba642013-05-05 15:51:06 +00007209 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007210 }
7211 }
7212 }
7213
7214 // C++ [over.built]p17:
7215 //
7216 // For every pair of promoted integral types L and R, there
7217 // exist candidate operator functions of the form
7218 //
7219 // LR operator%(L, R);
7220 // LR operator&(L, R);
7221 // LR operator^(L, R);
7222 // LR operator|(L, R);
7223 // L operator<<(L, R);
7224 // L operator>>(L, R);
7225 //
7226 // where LR is the result of the usual arithmetic conversions
7227 // between types L and R.
7228 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007229 if (!HasArithmeticOrEnumeralCandidateType)
7230 return;
7231
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007232 for (unsigned Left = FirstPromotedIntegralType;
7233 Left < LastPromotedIntegralType; ++Left) {
7234 for (unsigned Right = FirstPromotedIntegralType;
7235 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007236 QualType LandR[2] = { getArithmeticType(Left),
7237 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007238 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7239 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007240 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007241 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007242 }
7243 }
7244 }
7245
7246 // C++ [over.built]p20:
7247 //
7248 // For every pair (T, VQ), where T is an enumeration or
7249 // pointer to member type and VQ is either volatile or
7250 // empty, there exist candidate operator functions of the form
7251 //
7252 // VQ T& operator=(VQ T&, T);
7253 void addAssignmentMemberPointerOrEnumeralOverloads() {
7254 /// Set of (canonical) types that we've already handled.
7255 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7256
7257 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7258 for (BuiltinCandidateTypeSet::iterator
7259 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7260 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7261 Enum != EnumEnd; ++Enum) {
7262 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7263 continue;
7264
Richard Smith958ba642013-05-05 15:51:06 +00007265 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007266 }
7267
7268 for (BuiltinCandidateTypeSet::iterator
7269 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7270 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7271 MemPtr != MemPtrEnd; ++MemPtr) {
7272 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7273 continue;
7274
Richard Smith958ba642013-05-05 15:51:06 +00007275 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007276 }
7277 }
7278 }
7279
7280 // C++ [over.built]p19:
7281 //
7282 // For every pair (T, VQ), where T is any type and VQ is either
7283 // volatile or empty, there exist candidate operator functions
7284 // of the form
7285 //
7286 // T*VQ& operator=(T*VQ&, T*);
7287 //
7288 // C++ [over.built]p21:
7289 //
7290 // For every pair (T, VQ), where T is a cv-qualified or
7291 // cv-unqualified object type and VQ is either volatile or
7292 // empty, there exist candidate operator functions of the form
7293 //
7294 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7295 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7296 void addAssignmentPointerOverloads(bool isEqualOp) {
7297 /// Set of (canonical) types that we've already handled.
7298 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7299
7300 for (BuiltinCandidateTypeSet::iterator
7301 Ptr = CandidateTypes[0].pointer_begin(),
7302 PtrEnd = CandidateTypes[0].pointer_end();
7303 Ptr != PtrEnd; ++Ptr) {
7304 // If this is operator=, keep track of the builtin candidates we added.
7305 if (isEqualOp)
7306 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007307 else if (!(*Ptr)->getPointeeType()->isObjectType())
7308 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007309
7310 // non-volatile version
7311 QualType ParamTypes[2] = {
7312 S.Context.getLValueReferenceType(*Ptr),
7313 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7314 };
Richard Smith958ba642013-05-05 15:51:06 +00007315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007316 /*IsAssigmentOperator=*/ isEqualOp);
7317
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007318 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7319 VisibleTypeConversionsQuals.hasVolatile();
7320 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007321 // volatile version
7322 ParamTypes[0] =
7323 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007324 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007325 /*IsAssigmentOperator=*/isEqualOp);
7326 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007327
7328 if (!(*Ptr).isRestrictQualified() &&
7329 VisibleTypeConversionsQuals.hasRestrict()) {
7330 // restrict version
7331 ParamTypes[0]
7332 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007333 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007334 /*IsAssigmentOperator=*/isEqualOp);
7335
7336 if (NeedVolatile) {
7337 // volatile restrict version
7338 ParamTypes[0]
7339 = S.Context.getLValueReferenceType(
7340 S.Context.getCVRQualifiedType(*Ptr,
7341 (Qualifiers::Volatile |
7342 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007343 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007344 /*IsAssigmentOperator=*/isEqualOp);
7345 }
7346 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007347 }
7348
7349 if (isEqualOp) {
7350 for (BuiltinCandidateTypeSet::iterator
7351 Ptr = CandidateTypes[1].pointer_begin(),
7352 PtrEnd = CandidateTypes[1].pointer_end();
7353 Ptr != PtrEnd; ++Ptr) {
7354 // Make sure we don't add the same candidate twice.
7355 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7356 continue;
7357
Chandler Carruth6df868e2010-12-12 08:17:55 +00007358 QualType ParamTypes[2] = {
7359 S.Context.getLValueReferenceType(*Ptr),
7360 *Ptr,
7361 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007362
7363 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007364 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007365 /*IsAssigmentOperator=*/true);
7366
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007367 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7368 VisibleTypeConversionsQuals.hasVolatile();
7369 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007370 // volatile version
7371 ParamTypes[0] =
7372 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007373 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7374 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007375 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007376
7377 if (!(*Ptr).isRestrictQualified() &&
7378 VisibleTypeConversionsQuals.hasRestrict()) {
7379 // restrict version
7380 ParamTypes[0]
7381 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007382 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7383 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007384
7385 if (NeedVolatile) {
7386 // volatile restrict version
7387 ParamTypes[0]
7388 = S.Context.getLValueReferenceType(
7389 S.Context.getCVRQualifiedType(*Ptr,
7390 (Qualifiers::Volatile |
7391 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007392 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7393 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007394 }
7395 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007396 }
7397 }
7398 }
7399
7400 // C++ [over.built]p18:
7401 //
7402 // For every triple (L, VQ, R), where L is an arithmetic type,
7403 // VQ is either volatile or empty, and R is a promoted
7404 // arithmetic type, there exist candidate operator functions of
7405 // the form
7406 //
7407 // VQ L& operator=(VQ L&, R);
7408 // VQ L& operator*=(VQ L&, R);
7409 // VQ L& operator/=(VQ L&, R);
7410 // VQ L& operator+=(VQ L&, R);
7411 // VQ L& operator-=(VQ L&, R);
7412 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007413 if (!HasArithmeticOrEnumeralCandidateType)
7414 return;
7415
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007416 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7417 for (unsigned Right = FirstPromotedArithmeticType;
7418 Right < LastPromotedArithmeticType; ++Right) {
7419 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007420 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007421
7422 // Add this built-in operator as a candidate (VQ is empty).
7423 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007424 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007425 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007426 /*IsAssigmentOperator=*/isEqualOp);
7427
7428 // Add this built-in operator as a candidate (VQ is 'volatile').
7429 if (VisibleTypeConversionsQuals.hasVolatile()) {
7430 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007431 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007432 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007433 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007434 /*IsAssigmentOperator=*/isEqualOp);
7435 }
7436 }
7437 }
7438
7439 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7440 for (BuiltinCandidateTypeSet::iterator
7441 Vec1 = CandidateTypes[0].vector_begin(),
7442 Vec1End = CandidateTypes[0].vector_end();
7443 Vec1 != Vec1End; ++Vec1) {
7444 for (BuiltinCandidateTypeSet::iterator
7445 Vec2 = CandidateTypes[1].vector_begin(),
7446 Vec2End = CandidateTypes[1].vector_end();
7447 Vec2 != Vec2End; ++Vec2) {
7448 QualType ParamTypes[2];
7449 ParamTypes[1] = *Vec2;
7450 // Add this built-in operator as a candidate (VQ is empty).
7451 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007452 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007453 /*IsAssigmentOperator=*/isEqualOp);
7454
7455 // Add this built-in operator as a candidate (VQ is 'volatile').
7456 if (VisibleTypeConversionsQuals.hasVolatile()) {
7457 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7458 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007459 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007460 /*IsAssigmentOperator=*/isEqualOp);
7461 }
7462 }
7463 }
7464 }
7465
7466 // C++ [over.built]p22:
7467 //
7468 // For every triple (L, VQ, R), where L is an integral type, VQ
7469 // is either volatile or empty, and R is a promoted integral
7470 // type, there exist candidate operator functions of the form
7471 //
7472 // VQ L& operator%=(VQ L&, R);
7473 // VQ L& operator<<=(VQ L&, R);
7474 // VQ L& operator>>=(VQ L&, R);
7475 // VQ L& operator&=(VQ L&, R);
7476 // VQ L& operator^=(VQ L&, R);
7477 // VQ L& operator|=(VQ L&, R);
7478 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007479 if (!HasArithmeticOrEnumeralCandidateType)
7480 return;
7481
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007482 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7483 for (unsigned Right = FirstPromotedIntegralType;
7484 Right < LastPromotedIntegralType; ++Right) {
7485 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007486 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007487
7488 // Add this built-in operator as a candidate (VQ is empty).
7489 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007490 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007491 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007492 if (VisibleTypeConversionsQuals.hasVolatile()) {
7493 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007494 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007495 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7496 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007498 }
7499 }
7500 }
7501 }
7502
7503 // C++ [over.operator]p23:
7504 //
7505 // There also exist candidate operator functions of the form
7506 //
7507 // bool operator!(bool);
7508 // bool operator&&(bool, bool);
7509 // bool operator||(bool, bool);
7510 void addExclaimOverload() {
7511 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007512 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007513 /*IsAssignmentOperator=*/false,
7514 /*NumContextualBoolArguments=*/1);
7515 }
7516 void addAmpAmpOrPipePipeOverload() {
7517 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007518 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007519 /*IsAssignmentOperator=*/false,
7520 /*NumContextualBoolArguments=*/2);
7521 }
7522
7523 // C++ [over.built]p13:
7524 //
7525 // For every cv-qualified or cv-unqualified object type T there
7526 // exist candidate operator functions of the form
7527 //
7528 // T* operator+(T*, ptrdiff_t); [ABOVE]
7529 // T& operator[](T*, ptrdiff_t);
7530 // T* operator-(T*, ptrdiff_t); [ABOVE]
7531 // T* operator+(ptrdiff_t, T*); [ABOVE]
7532 // T& operator[](ptrdiff_t, T*);
7533 void addSubscriptOverloads() {
7534 for (BuiltinCandidateTypeSet::iterator
7535 Ptr = CandidateTypes[0].pointer_begin(),
7536 PtrEnd = CandidateTypes[0].pointer_end();
7537 Ptr != PtrEnd; ++Ptr) {
7538 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7539 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007540 if (!PointeeType->isObjectType())
7541 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007542
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007543 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7544
7545 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007546 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007547 }
7548
7549 for (BuiltinCandidateTypeSet::iterator
7550 Ptr = CandidateTypes[1].pointer_begin(),
7551 PtrEnd = CandidateTypes[1].pointer_end();
7552 Ptr != PtrEnd; ++Ptr) {
7553 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7554 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007555 if (!PointeeType->isObjectType())
7556 continue;
7557
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007558 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7559
7560 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007561 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007562 }
7563 }
7564
7565 // C++ [over.built]p11:
7566 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7567 // C1 is the same type as C2 or is a derived class of C2, T is an object
7568 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7569 // there exist candidate operator functions of the form
7570 //
7571 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7572 //
7573 // where CV12 is the union of CV1 and CV2.
7574 void addArrowStarOverloads() {
7575 for (BuiltinCandidateTypeSet::iterator
7576 Ptr = CandidateTypes[0].pointer_begin(),
7577 PtrEnd = CandidateTypes[0].pointer_end();
7578 Ptr != PtrEnd; ++Ptr) {
7579 QualType C1Ty = (*Ptr);
7580 QualType C1;
7581 QualifierCollector Q1;
7582 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7583 if (!isa<RecordType>(C1))
7584 continue;
7585 // heuristic to reduce number of builtin candidates in the set.
7586 // Add volatile/restrict version only if there are conversions to a
7587 // volatile/restrict type.
7588 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7589 continue;
7590 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7591 continue;
7592 for (BuiltinCandidateTypeSet::iterator
7593 MemPtr = CandidateTypes[1].member_pointer_begin(),
7594 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7595 MemPtr != MemPtrEnd; ++MemPtr) {
7596 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7597 QualType C2 = QualType(mptr->getClass(), 0);
7598 C2 = C2.getUnqualifiedType();
7599 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7600 break;
7601 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7602 // build CV12 T&
7603 QualType T = mptr->getPointeeType();
7604 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7605 T.isVolatileQualified())
7606 continue;
7607 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7608 T.isRestrictQualified())
7609 continue;
7610 T = Q1.apply(S.Context, T);
7611 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007612 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007613 }
7614 }
7615 }
7616
7617 // Note that we don't consider the first argument, since it has been
7618 // contextually converted to bool long ago. The candidates below are
7619 // therefore added as binary.
7620 //
7621 // C++ [over.built]p25:
7622 // For every type T, where T is a pointer, pointer-to-member, or scoped
7623 // enumeration type, there exist candidate operator functions of the form
7624 //
7625 // T operator?(bool, T, T);
7626 //
7627 void addConditionalOperatorOverloads() {
7628 /// Set of (canonical) types that we've already handled.
7629 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7630
7631 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7632 for (BuiltinCandidateTypeSet::iterator
7633 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7634 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7635 Ptr != PtrEnd; ++Ptr) {
7636 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7637 continue;
7638
7639 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007640 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007641 }
7642
7643 for (BuiltinCandidateTypeSet::iterator
7644 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7645 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7646 MemPtr != MemPtrEnd; ++MemPtr) {
7647 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7648 continue;
7649
7650 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007651 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007652 }
7653
Richard Smith80ad52f2013-01-02 11:42:31 +00007654 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007655 for (BuiltinCandidateTypeSet::iterator
7656 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7657 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7658 Enum != EnumEnd; ++Enum) {
7659 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7660 continue;
7661
7662 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7663 continue;
7664
7665 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007666 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007667 }
7668 }
7669 }
7670 }
7671};
7672
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007673} // end anonymous namespace
7674
7675/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7676/// operator overloads to the candidate set (C++ [over.built]), based
7677/// on the operator @p Op and the arguments given. For example, if the
7678/// operator is a binary '+', this routine might add "int
7679/// operator+(int, int)" to cover integer addition.
7680void
7681Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7682 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00007683 llvm::ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007684 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007685 // Find all of the types that the arguments can convert to, but only
7686 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007687 // that make use of these types. Also record whether we encounter non-record
7688 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007689 Qualifiers VisibleTypeConversionsQuals;
7690 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007691 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007692 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007693
7694 bool HasNonRecordCandidateType = false;
7695 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007696 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007697 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007698 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7699 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7700 OpLoc,
7701 true,
7702 (Op == OO_Exclaim ||
7703 Op == OO_AmpAmp ||
7704 Op == OO_PipePipe),
7705 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007706 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7707 CandidateTypes[ArgIdx].hasNonRecordTypes();
7708 HasArithmeticOrEnumeralCandidateType =
7709 HasArithmeticOrEnumeralCandidateType ||
7710 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007711 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007712
Chandler Carruth6a577462010-12-13 01:44:01 +00007713 // Exit early when no non-record types have been added to the candidate set
7714 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007715 //
7716 // We can't exit early for !, ||, or &&, since there we have always have
7717 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007718 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007719 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007720 return;
7721
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007722 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007723 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007724 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007725 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007726 CandidateTypes, CandidateSet);
7727
7728 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007729 switch (Op) {
7730 case OO_None:
7731 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007732 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007733
Chandler Carruthabb71842010-12-12 08:51:33 +00007734 case OO_New:
7735 case OO_Delete:
7736 case OO_Array_New:
7737 case OO_Array_Delete:
7738 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007739 llvm_unreachable(
7740 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007741
7742 case OO_Comma:
7743 case OO_Arrow:
7744 // C++ [over.match.oper]p3:
7745 // -- For the operator ',', the unary operator '&', or the
7746 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007747 break;
7748
7749 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007750 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007751 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007752 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007753
7754 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007755 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007756 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007757 } else {
7758 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7759 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7760 }
Douglas Gregor74253732008-11-19 15:42:04 +00007761 break;
7762
Chandler Carruthabb71842010-12-12 08:51:33 +00007763 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007764 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007765 OpBuilder.addUnaryStarPointerOverloads();
7766 else
7767 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7768 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007769
Chandler Carruthabb71842010-12-12 08:51:33 +00007770 case OO_Slash:
7771 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007772 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007773
7774 case OO_PlusPlus:
7775 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007776 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7777 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007778 break;
7779
Douglas Gregor19b7b152009-08-24 13:43:27 +00007780 case OO_EqualEqual:
7781 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007782 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007783 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007784
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007785 case OO_Less:
7786 case OO_Greater:
7787 case OO_LessEqual:
7788 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007789 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007790 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7791 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007792
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007793 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007794 case OO_Caret:
7795 case OO_Pipe:
7796 case OO_LessLess:
7797 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007798 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007799 break;
7800
Chandler Carruthabb71842010-12-12 08:51:33 +00007801 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007802 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007803 // C++ [over.match.oper]p3:
7804 // -- For the operator ',', the unary operator '&', or the
7805 // operator '->', the built-in candidates set is empty.
7806 break;
7807
7808 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7809 break;
7810
7811 case OO_Tilde:
7812 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7813 break;
7814
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007815 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007816 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007817 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007818
7819 case OO_PlusEqual:
7820 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007821 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007822 // Fall through.
7823
7824 case OO_StarEqual:
7825 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007826 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007827 break;
7828
7829 case OO_PercentEqual:
7830 case OO_LessLessEqual:
7831 case OO_GreaterGreaterEqual:
7832 case OO_AmpEqual:
7833 case OO_CaretEqual:
7834 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007835 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007836 break;
7837
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007838 case OO_Exclaim:
7839 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007840 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007841
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007842 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007843 case OO_PipePipe:
7844 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007845 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007846
7847 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007848 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007849 break;
7850
7851 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007852 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007853 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007854
7855 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007856 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007857 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7858 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007859 }
7860}
7861
Douglas Gregorfa047642009-02-04 00:32:51 +00007862/// \brief Add function candidates found via argument-dependent lookup
7863/// to the set of overloading candidates.
7864///
7865/// This routine performs argument-dependent name lookup based on the
7866/// given function name (which may also be an operator name) and adds
7867/// all of the overload candidates found by ADL to the overload
7868/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007869void
Douglas Gregorfa047642009-02-04 00:32:51 +00007870Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007871 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007872 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007873 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007874 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007875 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007876 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007877
John McCalla113e722010-01-26 06:04:06 +00007878 // FIXME: This approach for uniquing ADL results (and removing
7879 // redundant candidates from the set) relies on pointer-equality,
7880 // which means we need to key off the canonical decl. However,
7881 // always going back to the canonical decl might not get us the
7882 // right set of default arguments. What default arguments are
7883 // we supposed to consider on ADL candidates, anyway?
7884
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007885 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007886 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007887
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007888 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007889 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7890 CandEnd = CandidateSet.end();
7891 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007892 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007893 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007894 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007895 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007896 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007897
7898 // For each of the ADL candidates we found, add it to the overload
7899 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007900 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007901 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007902 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007903 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007904 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007905
Ahmed Charles13a140c2012-02-25 11:00:22 +00007906 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7907 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007908 } else
John McCall6e266892010-01-26 03:27:55 +00007909 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007910 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007911 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007912 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007913}
7914
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007915/// isBetterOverloadCandidate - Determines whether the first overload
7916/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007917bool
John McCall120d63c2010-08-24 20:38:10 +00007918isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007919 const OverloadCandidate &Cand1,
7920 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007921 SourceLocation Loc,
7922 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007923 // Define viable functions to be better candidates than non-viable
7924 // functions.
7925 if (!Cand2.Viable)
7926 return Cand1.Viable;
7927 else if (!Cand1.Viable)
7928 return false;
7929
Douglas Gregor88a35142008-12-22 05:46:06 +00007930 // C++ [over.match.best]p1:
7931 //
7932 // -- if F is a static member function, ICS1(F) is defined such
7933 // that ICS1(F) is neither better nor worse than ICS1(G) for
7934 // any function G, and, symmetrically, ICS1(G) is neither
7935 // better nor worse than ICS1(F).
7936 unsigned StartArg = 0;
7937 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7938 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007939
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007940 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007941 // A viable function F1 is defined to be a better function than another
7942 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007943 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007944 unsigned NumArgs = Cand1.NumConversions;
7945 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007946 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007947 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007948 switch (CompareImplicitConversionSequences(S,
7949 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007950 Cand2.Conversions[ArgIdx])) {
7951 case ImplicitConversionSequence::Better:
7952 // Cand1 has a better conversion sequence.
7953 HasBetterConversion = true;
7954 break;
7955
7956 case ImplicitConversionSequence::Worse:
7957 // Cand1 can't be better than Cand2.
7958 return false;
7959
7960 case ImplicitConversionSequence::Indistinguishable:
7961 // Do nothing.
7962 break;
7963 }
7964 }
7965
Mike Stump1eb44332009-09-09 15:08:12 +00007966 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007967 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007968 if (HasBetterConversion)
7969 return true;
7970
Mike Stump1eb44332009-09-09 15:08:12 +00007971 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007972 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007973 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007974 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7975 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007976
7977 // -- F1 and F2 are function template specializations, and the function
7978 // template for F1 is more specialized than the template for F2
7979 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007980 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007981 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007982 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007983 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007984 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7985 Cand2.Function->getPrimaryTemplate(),
7986 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007987 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007988 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007989 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007990 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007991 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007992
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007993 // -- the context is an initialization by user-defined conversion
7994 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7995 // from the return type of F1 to the destination type (i.e.,
7996 // the type of the entity being initialized) is a better
7997 // conversion sequence than the standard conversion sequence
7998 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007999 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00008000 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008001 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00008002 // First check whether we prefer one of the conversion functions over the
8003 // other. This only distinguishes the results in non-standard, extension
8004 // cases such as the conversion from a lambda closure type to a function
8005 // pointer or block.
8006 ImplicitConversionSequence::CompareKind FuncResult
8007 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8008 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8009 return FuncResult;
8010
John McCall120d63c2010-08-24 20:38:10 +00008011 switch (CompareStandardConversionSequences(S,
8012 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008013 Cand2.FinalConversion)) {
8014 case ImplicitConversionSequence::Better:
8015 // Cand1 has a better conversion sequence.
8016 return true;
8017
8018 case ImplicitConversionSequence::Worse:
8019 // Cand1 can't be better than Cand2.
8020 return false;
8021
8022 case ImplicitConversionSequence::Indistinguishable:
8023 // Do nothing
8024 break;
8025 }
8026 }
8027
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008028 return false;
8029}
8030
Mike Stump1eb44332009-09-09 15:08:12 +00008031/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008032/// within an overload candidate set.
8033///
James Dennettefce31f2012-06-22 08:10:18 +00008034/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008035/// which overload resolution occurs.
8036///
James Dennettefce31f2012-06-22 08:10:18 +00008037/// \param Best If overload resolution was successful or found a deleted
8038/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008039///
8040/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008041OverloadingResult
8042OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008043 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008044 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008045 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008046 Best = end();
8047 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8048 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008049 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008050 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008051 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008052 }
8053
8054 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008055 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008056 return OR_No_Viable_Function;
8057
8058 // Make sure that this function is better than every other viable
8059 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008060 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008061 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008062 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008063 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008064 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008065 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008066 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008067 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008068 }
Mike Stump1eb44332009-09-09 15:08:12 +00008069
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008070 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008071 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008072 (Best->Function->isDeleted() ||
8073 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008074 return OR_Deleted;
8075
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008076 return OR_Success;
8077}
8078
John McCall3c80f572010-01-12 02:15:36 +00008079namespace {
8080
8081enum OverloadCandidateKind {
8082 oc_function,
8083 oc_method,
8084 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008085 oc_function_template,
8086 oc_method_template,
8087 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008088 oc_implicit_default_constructor,
8089 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008090 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008091 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008092 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008093 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008094};
8095
John McCall220ccbf2010-01-13 00:25:19 +00008096OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8097 FunctionDecl *Fn,
8098 std::string &Description) {
8099 bool isTemplate = false;
8100
8101 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8102 isTemplate = true;
8103 Description = S.getTemplateArgumentBindingsText(
8104 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8105 }
John McCallb1622a12010-01-06 09:43:14 +00008106
8107 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008108 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008109 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008110
Sebastian Redlf677ea32011-02-05 19:23:19 +00008111 if (Ctor->getInheritedConstructor())
8112 return oc_implicit_inherited_constructor;
8113
Sean Hunt82713172011-05-25 23:16:36 +00008114 if (Ctor->isDefaultConstructor())
8115 return oc_implicit_default_constructor;
8116
8117 if (Ctor->isMoveConstructor())
8118 return oc_implicit_move_constructor;
8119
8120 assert(Ctor->isCopyConstructor() &&
8121 "unexpected sort of implicit constructor");
8122 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008123 }
8124
8125 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8126 // This actually gets spelled 'candidate function' for now, but
8127 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008128 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008129 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008130
Sean Hunt82713172011-05-25 23:16:36 +00008131 if (Meth->isMoveAssignmentOperator())
8132 return oc_implicit_move_assignment;
8133
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008134 if (Meth->isCopyAssignmentOperator())
8135 return oc_implicit_copy_assignment;
8136
8137 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8138 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008139 }
8140
John McCall220ccbf2010-01-13 00:25:19 +00008141 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008142}
8143
Sebastian Redlf677ea32011-02-05 19:23:19 +00008144void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8145 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8146 if (!Ctor) return;
8147
8148 Ctor = Ctor->getInheritedConstructor();
8149 if (!Ctor) return;
8150
8151 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8152}
8153
John McCall3c80f572010-01-12 02:15:36 +00008154} // end anonymous namespace
8155
8156// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008157void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008158 std::string FnDesc;
8159 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008160 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8161 << (unsigned) K << FnDesc;
8162 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8163 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008164 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008165}
8166
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008167//Notes the location of all overload candidates designated through
8168// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008169void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008170 assert(OverloadedExpr->getType() == Context.OverloadTy);
8171
8172 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8173 OverloadExpr *OvlExpr = Ovl.Expression;
8174
8175 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8176 IEnd = OvlExpr->decls_end();
8177 I != IEnd; ++I) {
8178 if (FunctionTemplateDecl *FunTmpl =
8179 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008180 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008181 } else if (FunctionDecl *Fun
8182 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008183 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008184 }
8185 }
8186}
8187
John McCall1d318332010-01-12 00:44:57 +00008188/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8189/// "lead" diagnostic; it will be given two arguments, the source and
8190/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008191void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8192 Sema &S,
8193 SourceLocation CaretLoc,
8194 const PartialDiagnostic &PDiag) const {
8195 S.Diag(CaretLoc, PDiag)
8196 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008197 // FIXME: The note limiting machinery is borrowed from
8198 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8199 // refactoring here.
8200 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8201 unsigned CandsShown = 0;
8202 AmbiguousConversionSequence::const_iterator I, E;
8203 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8204 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8205 break;
8206 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008207 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008208 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008209 if (I != E)
8210 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008211}
8212
John McCall1d318332010-01-12 00:44:57 +00008213namespace {
8214
John McCalladbb8f82010-01-13 09:16:55 +00008215void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8216 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8217 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008218 assert(Cand->Function && "for now, candidate must be a function");
8219 FunctionDecl *Fn = Cand->Function;
8220
8221 // There's a conversion slot for the object argument if this is a
8222 // non-constructor method. Note that 'I' corresponds the
8223 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008224 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008225 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008226 if (I == 0)
8227 isObjectArgument = true;
8228 else
8229 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008230 }
8231
John McCall220ccbf2010-01-13 00:25:19 +00008232 std::string FnDesc;
8233 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8234
John McCalladbb8f82010-01-13 09:16:55 +00008235 Expr *FromExpr = Conv.Bad.FromExpr;
8236 QualType FromTy = Conv.Bad.getFromType();
8237 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008238
John McCall5920dbb2010-02-02 02:42:52 +00008239 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008240 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008241 Expr *E = FromExpr->IgnoreParens();
8242 if (isa<UnaryOperator>(E))
8243 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008244 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008245
8246 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8247 << (unsigned) FnKind << FnDesc
8248 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8249 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008250 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008251 return;
8252 }
8253
John McCall258b2032010-01-23 08:10:49 +00008254 // Do some hand-waving analysis to see if the non-viability is due
8255 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008256 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8257 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8258 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8259 CToTy = RT->getPointeeType();
8260 else {
8261 // TODO: detect and diagnose the full richness of const mismatches.
8262 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8263 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8264 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8265 }
8266
8267 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8268 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008269 Qualifiers FromQs = CFromTy.getQualifiers();
8270 Qualifiers ToQs = CToTy.getQualifiers();
8271
8272 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8274 << (unsigned) FnKind << FnDesc
8275 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8276 << FromTy
8277 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8278 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008279 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008280 return;
8281 }
8282
John McCallf85e1932011-06-15 23:02:42 +00008283 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008284 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008285 << (unsigned) FnKind << FnDesc
8286 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8287 << FromTy
8288 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8289 << (unsigned) isObjectArgument << I+1;
8290 MaybeEmitInheritedConstructorNote(S, Fn);
8291 return;
8292 }
8293
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008294 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8296 << (unsigned) FnKind << FnDesc
8297 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8298 << FromTy
8299 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8300 << (unsigned) isObjectArgument << I+1;
8301 MaybeEmitInheritedConstructorNote(S, Fn);
8302 return;
8303 }
8304
John McCall651f3ee2010-01-14 03:28:57 +00008305 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8306 assert(CVR && "unexpected qualifiers mismatch");
8307
8308 if (isObjectArgument) {
8309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8310 << (unsigned) FnKind << FnDesc
8311 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8312 << FromTy << (CVR - 1);
8313 } else {
8314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8315 << (unsigned) FnKind << FnDesc
8316 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8317 << FromTy << (CVR - 1) << I+1;
8318 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008319 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008320 return;
8321 }
8322
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008323 // Special diagnostic for failure to convert an initializer list, since
8324 // telling the user that it has type void is not useful.
8325 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8326 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8327 << (unsigned) FnKind << FnDesc
8328 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8329 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8330 MaybeEmitInheritedConstructorNote(S, Fn);
8331 return;
8332 }
8333
John McCall258b2032010-01-23 08:10:49 +00008334 // Diagnose references or pointers to incomplete types differently,
8335 // since it's far from impossible that the incompleteness triggered
8336 // the failure.
8337 QualType TempFromTy = FromTy.getNonReferenceType();
8338 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8339 TempFromTy = PTy->getPointeeType();
8340 if (TempFromTy->isIncompleteType()) {
8341 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8342 << (unsigned) FnKind << FnDesc
8343 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8344 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008345 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008346 return;
8347 }
8348
Douglas Gregor85789812010-06-30 23:01:39 +00008349 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008350 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008351 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8352 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8353 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8354 FromPtrTy->getPointeeType()) &&
8355 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8356 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008357 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008358 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008359 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008360 }
8361 } else if (const ObjCObjectPointerType *FromPtrTy
8362 = FromTy->getAs<ObjCObjectPointerType>()) {
8363 if (const ObjCObjectPointerType *ToPtrTy
8364 = ToTy->getAs<ObjCObjectPointerType>())
8365 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8366 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8367 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8368 FromPtrTy->getPointeeType()) &&
8369 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008370 BaseToDerivedConversion = 2;
8371 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008372 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8373 !FromTy->isIncompleteType() &&
8374 !ToRefTy->getPointeeType()->isIncompleteType() &&
8375 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8376 BaseToDerivedConversion = 3;
8377 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8378 ToTy.getNonReferenceType().getCanonicalType() ==
8379 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8381 << (unsigned) FnKind << FnDesc
8382 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8383 << (unsigned) isObjectArgument << I + 1;
8384 MaybeEmitInheritedConstructorNote(S, Fn);
8385 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008386 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008387 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008388
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008389 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008390 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008391 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008392 << (unsigned) FnKind << FnDesc
8393 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008394 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008395 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008396 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008397 return;
8398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008399
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008400 if (isa<ObjCObjectPointerType>(CFromTy) &&
8401 isa<PointerType>(CToTy)) {
8402 Qualifiers FromQs = CFromTy.getQualifiers();
8403 Qualifiers ToQs = CToTy.getQualifiers();
8404 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8405 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8406 << (unsigned) FnKind << FnDesc
8407 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8408 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8409 MaybeEmitInheritedConstructorNote(S, Fn);
8410 return;
8411 }
8412 }
8413
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008414 // Emit the generic diagnostic and, optionally, add the hints to it.
8415 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8416 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008417 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008418 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8419 << (unsigned) (Cand->Fix.Kind);
8420
8421 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008422 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8423 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008424 FDiag << *HI;
8425 S.Diag(Fn->getLocation(), FDiag);
8426
Sebastian Redlf677ea32011-02-05 19:23:19 +00008427 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008428}
8429
8430void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8431 unsigned NumFormalArgs) {
8432 // TODO: treat calls to a missing default constructor as a special case
8433
8434 FunctionDecl *Fn = Cand->Function;
8435 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8436
8437 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008438
Douglas Gregor439d3c32011-05-05 00:13:13 +00008439 // With invalid overloaded operators, it's possible that we think we
8440 // have an arity mismatch when it fact it looks like we have the
8441 // right number of arguments, because only overloaded operators have
8442 // the weird behavior of overloading member and non-member functions.
8443 // Just don't report anything.
8444 if (Fn->isInvalidDecl() &&
8445 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8446 return;
8447
John McCalladbb8f82010-01-13 09:16:55 +00008448 // at least / at most / exactly
8449 unsigned mode, modeCount;
8450 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008451 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8452 (Cand->FailureKind == ovl_fail_bad_deduction &&
8453 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008454 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008455 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008456 mode = 0; // "at least"
8457 else
8458 mode = 2; // "exactly"
8459 modeCount = MinParams;
8460 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008461 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8462 (Cand->FailureKind == ovl_fail_bad_deduction &&
8463 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008464 if (MinParams != FnTy->getNumArgs())
8465 mode = 1; // "at most"
8466 else
8467 mode = 2; // "exactly"
8468 modeCount = FnTy->getNumArgs();
8469 }
8470
8471 std::string Description;
8472 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8473
Richard Smithf7b80562012-05-11 05:16:41 +00008474 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8475 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8476 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8477 << Fn->getParamDecl(0) << NumFormalArgs;
8478 else
8479 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8480 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8481 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008482 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008483}
8484
John McCall342fec42010-02-01 18:53:26 +00008485/// Diagnose a failed template-argument deduction.
8486void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008487 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008488 FunctionDecl *Fn = Cand->Function; // pattern
8489
Douglas Gregora9333192010-05-08 17:41:32 +00008490 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008491 NamedDecl *ParamD;
8492 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8493 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8494 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008495 switch (Cand->DeductionFailure.Result) {
8496 case Sema::TDK_Success:
8497 llvm_unreachable("TDK_success while diagnosing bad deduction");
8498
8499 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008500 assert(ParamD && "no parameter found for incomplete deduction result");
8501 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8502 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008503 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008504 return;
8505 }
8506
John McCall57e97782010-08-05 09:05:08 +00008507 case Sema::TDK_Underqualified: {
8508 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8509 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8510
8511 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8512
8513 // Param will have been canonicalized, but it should just be a
8514 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008515 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008516 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008517 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008518 assert(S.Context.hasSameType(Param, NonCanonParam));
8519
8520 // Arg has also been canonicalized, but there's nothing we can do
8521 // about that. It also doesn't matter as much, because it won't
8522 // have any template parameters in it (because deduction isn't
8523 // done on dependent types).
8524 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8525
8526 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8527 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008528 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008529 return;
8530 }
8531
8532 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008533 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008534 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008535 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008536 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008537 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008538 which = 1;
8539 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008540 which = 2;
8541 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008542
Douglas Gregora9333192010-05-08 17:41:32 +00008543 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008544 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008545 << *Cand->DeductionFailure.getFirstArg()
8546 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008547 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008548 return;
8549 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008550
Douglas Gregorf1a84452010-05-08 19:15:54 +00008551 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008552 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008553 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008554 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008555 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8556 << ParamD->getDeclName();
8557 else {
8558 int index = 0;
8559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8560 index = TTP->getIndex();
8561 else if (NonTypeTemplateParmDecl *NTTP
8562 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8563 index = NTTP->getIndex();
8564 else
8565 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008566 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008567 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8568 << (index + 1);
8569 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008570 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008571 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008572
Douglas Gregora18592e2010-05-08 18:13:28 +00008573 case Sema::TDK_TooManyArguments:
8574 case Sema::TDK_TooFewArguments:
8575 DiagnoseArityMismatch(S, Cand, NumArgs);
8576 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008577
8578 case Sema::TDK_InstantiationDepth:
8579 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008580 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008581 return;
8582
8583 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008584 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008585 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008586 if (TemplateArgumentList *Args =
8587 Cand->DeductionFailure.getTemplateArgumentList()) {
8588 TemplateArgString = " ";
8589 TemplateArgString += S.getTemplateArgumentBindingsText(
8590 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8591 }
8592
Richard Smith4493c0a2012-05-09 05:17:00 +00008593 // If this candidate was disabled by enable_if, say so.
8594 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8595 if (PDiag && PDiag->second.getDiagID() ==
8596 diag::err_typename_nested_not_found_enable_if) {
8597 // FIXME: Use the source range of the condition, and the fully-qualified
8598 // name of the enable_if template. These are both present in PDiag.
8599 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8600 << "'enable_if'" << TemplateArgString;
8601 return;
8602 }
8603
Richard Smithb8590f32012-05-07 09:03:25 +00008604 // Format the SFINAE diagnostic into the argument string.
8605 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8606 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008607 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008608 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008609 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008610 SFINAEArgString = ": ";
8611 R = SourceRange(PDiag->first, PDiag->first);
8612 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8613 }
8614
Douglas Gregorec20f462010-05-08 20:07:26 +00008615 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008616 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008617 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008618 return;
8619 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008620
Richard Smith0efa62f2013-01-31 04:03:12 +00008621 case Sema::TDK_FailedOverloadResolution: {
8622 OverloadExpr::FindResult R =
8623 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8624 S.Diag(Fn->getLocation(),
8625 diag::note_ovl_candidate_failed_overload_resolution)
8626 << R.Expression->getName();
8627 return;
8628 }
8629
Richard Trieueef35f82013-04-08 21:11:40 +00008630 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008631 // FIXME: Provide a source location to indicate what we couldn't match.
Richard Trieueef35f82013-04-08 21:11:40 +00008632 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8633 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
8634 if (FirstTA.getKind() == TemplateArgument::Template &&
8635 SecondTA.getKind() == TemplateArgument::Template) {
8636 TemplateName FirstTN = FirstTA.getAsTemplate();
8637 TemplateName SecondTN = SecondTA.getAsTemplate();
8638 if (FirstTN.getKind() == TemplateName::Template &&
8639 SecondTN.getKind() == TemplateName::Template) {
8640 if (FirstTN.getAsTemplateDecl()->getName() ==
8641 SecondTN.getAsTemplateDecl()->getName()) {
8642 // FIXME: This fixes a bad diagnostic where both templates are named
8643 // the same. This particular case is a bit difficult since:
8644 // 1) It is passed as a string to the diagnostic printer.
8645 // 2) The diagnostic printer only attempts to find a better
8646 // name for types, not decls.
8647 // Ideally, this should folded into the diagnostic printer.
8648 S.Diag(Fn->getLocation(),
8649 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8650 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8651 return;
8652 }
8653 }
8654 }
Richard Smith29805ca2013-01-31 05:19:49 +00008655 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
Richard Trieueef35f82013-04-08 21:11:40 +00008656 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008657 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008658 }
John McCall342fec42010-02-01 18:53:26 +00008659 // TODO: diagnose these individually, then kill off
8660 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008661 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008662 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008663 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008664 return;
8665 }
8666}
8667
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008668/// CUDA: diagnose an invalid call across targets.
8669void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8670 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8671 FunctionDecl *Callee = Cand->Function;
8672
8673 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8674 CalleeTarget = S.IdentifyCUDATarget(Callee);
8675
8676 std::string FnDesc;
8677 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8678
8679 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8680 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8681}
8682
John McCall342fec42010-02-01 18:53:26 +00008683/// Generates a 'note' diagnostic for an overload candidate. We've
8684/// already generated a primary error at the call site.
8685///
8686/// It really does need to be a single diagnostic with its caret
8687/// pointed at the candidate declaration. Yes, this creates some
8688/// major challenges of technical writing. Yes, this makes pointing
8689/// out problems with specific arguments quite awkward. It's still
8690/// better than generating twenty screens of text for every failed
8691/// overload.
8692///
8693/// It would be great to be able to express per-candidate problems
8694/// more richly for those diagnostic clients that cared, but we'd
8695/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008696void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008697 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008698 FunctionDecl *Fn = Cand->Function;
8699
John McCall81201622010-01-08 04:41:39 +00008700 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008701 if (Cand->Viable && (Fn->isDeleted() ||
8702 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008703 std::string FnDesc;
8704 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008705
8706 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008707 << FnKind << FnDesc
8708 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008709 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008710 return;
John McCall81201622010-01-08 04:41:39 +00008711 }
8712
John McCall220ccbf2010-01-13 00:25:19 +00008713 // We don't really have anything else to say about viable candidates.
8714 if (Cand->Viable) {
8715 S.NoteOverloadCandidate(Fn);
8716 return;
8717 }
John McCall1d318332010-01-12 00:44:57 +00008718
John McCalladbb8f82010-01-13 09:16:55 +00008719 switch (Cand->FailureKind) {
8720 case ovl_fail_too_many_arguments:
8721 case ovl_fail_too_few_arguments:
8722 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008723
John McCalladbb8f82010-01-13 09:16:55 +00008724 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008725 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008726
John McCall717e8912010-01-23 05:17:32 +00008727 case ovl_fail_trivial_conversion:
8728 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008729 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008730 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008731
John McCallb1bdc622010-02-25 01:37:24 +00008732 case ovl_fail_bad_conversion: {
8733 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008734 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008735 if (Cand->Conversions[I].isBad())
8736 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008737
John McCalladbb8f82010-01-13 09:16:55 +00008738 // FIXME: this currently happens when we're called from SemaInit
8739 // when user-conversion overload fails. Figure out how to handle
8740 // those conditions and diagnose them well.
8741 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008742 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008743
8744 case ovl_fail_bad_target:
8745 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008746 }
John McCalla1d7d622010-01-08 00:58:21 +00008747}
8748
8749void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8750 // Desugar the type of the surrogate down to a function type,
8751 // retaining as many typedefs as possible while still showing
8752 // the function type (and, therefore, its parameter types).
8753 QualType FnType = Cand->Surrogate->getConversionType();
8754 bool isLValueReference = false;
8755 bool isRValueReference = false;
8756 bool isPointer = false;
8757 if (const LValueReferenceType *FnTypeRef =
8758 FnType->getAs<LValueReferenceType>()) {
8759 FnType = FnTypeRef->getPointeeType();
8760 isLValueReference = true;
8761 } else if (const RValueReferenceType *FnTypeRef =
8762 FnType->getAs<RValueReferenceType>()) {
8763 FnType = FnTypeRef->getPointeeType();
8764 isRValueReference = true;
8765 }
8766 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8767 FnType = FnTypePtr->getPointeeType();
8768 isPointer = true;
8769 }
8770 // Desugar down to a function type.
8771 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8772 // Reconstruct the pointer/reference as appropriate.
8773 if (isPointer) FnType = S.Context.getPointerType(FnType);
8774 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8775 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8776
8777 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8778 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008779 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008780}
8781
8782void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008783 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008784 SourceLocation OpLoc,
8785 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008786 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008787 std::string TypeStr("operator");
8788 TypeStr += Opc;
8789 TypeStr += "(";
8790 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008791 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008792 TypeStr += ")";
8793 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8794 } else {
8795 TypeStr += ", ";
8796 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8797 TypeStr += ")";
8798 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8799 }
8800}
8801
8802void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8803 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008804 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008805 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8806 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008807 if (ICS.isBad()) break; // all meaningless after first invalid
8808 if (!ICS.isAmbiguous()) continue;
8809
John McCall120d63c2010-08-24 20:38:10 +00008810 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008811 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008812 }
8813}
8814
John McCall1b77e732010-01-15 23:32:50 +00008815SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8816 if (Cand->Function)
8817 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008818 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008819 return Cand->Surrogate->getLocation();
8820 return SourceLocation();
8821}
8822
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008823static unsigned
8824RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008825 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008826 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008827 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008828
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008829 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008830 case Sema::TDK_Incomplete:
8831 return 1;
8832
8833 case Sema::TDK_Underqualified:
8834 case Sema::TDK_Inconsistent:
8835 return 2;
8836
8837 case Sema::TDK_SubstitutionFailure:
8838 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008839 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008840 return 3;
8841
8842 case Sema::TDK_InstantiationDepth:
8843 case Sema::TDK_FailedOverloadResolution:
8844 return 4;
8845
8846 case Sema::TDK_InvalidExplicitArguments:
8847 return 5;
8848
8849 case Sema::TDK_TooManyArguments:
8850 case Sema::TDK_TooFewArguments:
8851 return 6;
8852 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008853 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008854}
8855
John McCallbf65c0b2010-01-12 00:48:53 +00008856struct CompareOverloadCandidatesForDisplay {
8857 Sema &S;
8858 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008859
8860 bool operator()(const OverloadCandidate *L,
8861 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008862 // Fast-path this check.
8863 if (L == R) return false;
8864
John McCall81201622010-01-08 04:41:39 +00008865 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008866 if (L->Viable) {
8867 if (!R->Viable) return true;
8868
8869 // TODO: introduce a tri-valued comparison for overload
8870 // candidates. Would be more worthwhile if we had a sort
8871 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008872 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8873 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008874 } else if (R->Viable)
8875 return false;
John McCall81201622010-01-08 04:41:39 +00008876
John McCall1b77e732010-01-15 23:32:50 +00008877 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008878
John McCall1b77e732010-01-15 23:32:50 +00008879 // Criteria by which we can sort non-viable candidates:
8880 if (!L->Viable) {
8881 // 1. Arity mismatches come after other candidates.
8882 if (L->FailureKind == ovl_fail_too_many_arguments ||
8883 L->FailureKind == ovl_fail_too_few_arguments)
8884 return false;
8885 if (R->FailureKind == ovl_fail_too_many_arguments ||
8886 R->FailureKind == ovl_fail_too_few_arguments)
8887 return true;
John McCall81201622010-01-08 04:41:39 +00008888
John McCall717e8912010-01-23 05:17:32 +00008889 // 2. Bad conversions come first and are ordered by the number
8890 // of bad conversions and quality of good conversions.
8891 if (L->FailureKind == ovl_fail_bad_conversion) {
8892 if (R->FailureKind != ovl_fail_bad_conversion)
8893 return true;
8894
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008895 // The conversion that can be fixed with a smaller number of changes,
8896 // comes first.
8897 unsigned numLFixes = L->Fix.NumConversionsFixed;
8898 unsigned numRFixes = R->Fix.NumConversionsFixed;
8899 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8900 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008901 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008902 if (numLFixes < numRFixes)
8903 return true;
8904 else
8905 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008906 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008907
John McCall717e8912010-01-23 05:17:32 +00008908 // If there's any ordering between the defined conversions...
8909 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008910 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008911
8912 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008913 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008914 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008915 switch (CompareImplicitConversionSequences(S,
8916 L->Conversions[I],
8917 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008918 case ImplicitConversionSequence::Better:
8919 leftBetter++;
8920 break;
8921
8922 case ImplicitConversionSequence::Worse:
8923 leftBetter--;
8924 break;
8925
8926 case ImplicitConversionSequence::Indistinguishable:
8927 break;
8928 }
8929 }
8930 if (leftBetter > 0) return true;
8931 if (leftBetter < 0) return false;
8932
8933 } else if (R->FailureKind == ovl_fail_bad_conversion)
8934 return false;
8935
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008936 if (L->FailureKind == ovl_fail_bad_deduction) {
8937 if (R->FailureKind != ovl_fail_bad_deduction)
8938 return true;
8939
8940 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8941 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008942 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008943 } else if (R->FailureKind == ovl_fail_bad_deduction)
8944 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008945
John McCall1b77e732010-01-15 23:32:50 +00008946 // TODO: others?
8947 }
8948
8949 // Sort everything else by location.
8950 SourceLocation LLoc = GetLocationForCandidate(L);
8951 SourceLocation RLoc = GetLocationForCandidate(R);
8952
8953 // Put candidates without locations (e.g. builtins) at the end.
8954 if (LLoc.isInvalid()) return false;
8955 if (RLoc.isInvalid()) return true;
8956
8957 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008958 }
8959};
8960
John McCall717e8912010-01-23 05:17:32 +00008961/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008962/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008963void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008964 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008965 assert(!Cand->Viable);
8966
8967 // Don't do anything on failures other than bad conversion.
8968 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8969
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008970 // We only want the FixIts if all the arguments can be corrected.
8971 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008972 // Use a implicit copy initialization to check conversion fixes.
8973 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008974
John McCall717e8912010-01-23 05:17:32 +00008975 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008976 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008977 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008978 while (true) {
8979 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8980 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008981 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008982 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008983 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008984 }
John McCall717e8912010-01-23 05:17:32 +00008985 }
8986
8987 if (ConvIdx == ConvCount)
8988 return;
8989
John McCallb1bdc622010-02-25 01:37:24 +00008990 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8991 "remaining conversion is initialized?");
8992
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008993 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008994 // operation somehow.
8995 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008996
8997 const FunctionProtoType* Proto;
8998 unsigned ArgIdx = ConvIdx;
8999
9000 if (Cand->IsSurrogate) {
9001 QualType ConvType
9002 = Cand->Surrogate->getConversionType().getNonReferenceType();
9003 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9004 ConvType = ConvPtrType->getPointeeType();
9005 Proto = ConvType->getAs<FunctionProtoType>();
9006 ArgIdx--;
9007 } else if (Cand->Function) {
9008 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9009 if (isa<CXXMethodDecl>(Cand->Function) &&
9010 !isa<CXXConstructorDecl>(Cand->Function))
9011 ArgIdx--;
9012 } else {
9013 // Builtin binary operator with a bad first conversion.
9014 assert(ConvCount <= 3);
9015 for (; ConvIdx != ConvCount; ++ConvIdx)
9016 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009017 = TryCopyInitialization(S, Args[ConvIdx],
9018 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009019 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009020 /*InOverloadResolution*/ true,
9021 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009022 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009023 return;
9024 }
9025
9026 // Fill in the rest of the conversions.
9027 unsigned NumArgsInProto = Proto->getNumArgs();
9028 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009029 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009030 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009031 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009032 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009033 /*InOverloadResolution=*/true,
9034 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009035 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009036 // Store the FixIt in the candidate if it exists.
9037 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009038 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009039 }
John McCall717e8912010-01-23 05:17:32 +00009040 else
9041 Cand->Conversions[ConvIdx].setEllipsis();
9042 }
9043}
9044
John McCalla1d7d622010-01-08 00:58:21 +00009045} // end anonymous namespace
9046
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009047/// PrintOverloadCandidates - When overload resolution fails, prints
9048/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009049/// set.
John McCall120d63c2010-08-24 20:38:10 +00009050void OverloadCandidateSet::NoteCandidates(Sema &S,
9051 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009052 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009053 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009054 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009055 // Sort the candidates by viability and position. Sorting directly would
9056 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009057 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009058 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9059 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009060 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009061 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009062 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009063 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009064 if (Cand->Function || Cand->IsSurrogate)
9065 Cands.push_back(Cand);
9066 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9067 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009068 }
9069 }
9070
John McCallbf65c0b2010-01-12 00:48:53 +00009071 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009072 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009073
John McCall1d318332010-01-12 00:44:57 +00009074 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009075
Chris Lattner5f9e2722011-07-23 10:55:15 +00009076 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009077 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009078 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009079 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9080 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009081
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009082 // Set an arbitrary limit on the number of candidate functions we'll spam
9083 // the user with. FIXME: This limit should depend on details of the
9084 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009085 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009086 break;
9087 }
9088 ++CandsShown;
9089
John McCalla1d7d622010-01-08 00:58:21 +00009090 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009091 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009092 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009093 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009094 else {
9095 assert(Cand->Viable &&
9096 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009097 // Generally we only see ambiguities including viable builtin
9098 // operators if overload resolution got screwed up by an
9099 // ambiguous user-defined conversion.
9100 //
9101 // FIXME: It's quite possible for different conversions to see
9102 // different ambiguities, though.
9103 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009104 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009105 ReportedAmbiguousConversions = true;
9106 }
John McCalla1d7d622010-01-08 00:58:21 +00009107
John McCall1d318332010-01-12 00:44:57 +00009108 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009109 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009110 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009111 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009112
9113 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009114 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009115}
9116
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009117// [PossiblyAFunctionType] --> [Return]
9118// NonFunctionType --> NonFunctionType
9119// R (A) --> R(A)
9120// R (*)(A) --> R (A)
9121// R (&)(A) --> R (A)
9122// R (S::*)(A) --> R (A)
9123QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9124 QualType Ret = PossiblyAFunctionType;
9125 if (const PointerType *ToTypePtr =
9126 PossiblyAFunctionType->getAs<PointerType>())
9127 Ret = ToTypePtr->getPointeeType();
9128 else if (const ReferenceType *ToTypeRef =
9129 PossiblyAFunctionType->getAs<ReferenceType>())
9130 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009131 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009132 PossiblyAFunctionType->getAs<MemberPointerType>())
9133 Ret = MemTypePtr->getPointeeType();
9134 Ret =
9135 Context.getCanonicalType(Ret).getUnqualifiedType();
9136 return Ret;
9137}
Douglas Gregor904eed32008-11-10 20:40:00 +00009138
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009139// A helper class to help with address of function resolution
9140// - allows us to avoid passing around all those ugly parameters
9141class AddressOfFunctionResolver
9142{
9143 Sema& S;
9144 Expr* SourceExpr;
9145 const QualType& TargetType;
9146 QualType TargetFunctionType; // Extracted function type from target type
9147
9148 bool Complain;
9149 //DeclAccessPair& ResultFunctionAccessPair;
9150 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009151
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009152 bool TargetTypeIsNonStaticMemberFunction;
9153 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009154
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009155 OverloadExpr::FindResult OvlExprInfo;
9156 OverloadExpr *OvlExpr;
9157 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009158 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009159
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009160public:
9161 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9162 const QualType& TargetType, bool Complain)
9163 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9164 Complain(Complain), Context(S.getASTContext()),
9165 TargetTypeIsNonStaticMemberFunction(
9166 !!TargetType->getAs<MemberPointerType>()),
9167 FoundNonTemplateFunction(false),
9168 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9169 OvlExpr(OvlExprInfo.Expression)
9170 {
9171 ExtractUnqualifiedFunctionTypeFromTargetType();
9172
9173 if (!TargetFunctionType->isFunctionType()) {
9174 if (OvlExpr->hasExplicitTemplateArgs()) {
9175 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009176 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009177 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009178
9179 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9180 if (!Method->isStatic()) {
9181 // If the target type is a non-function type and the function
9182 // found is a non-static member function, pretend as if that was
9183 // the target, it's the only possible type to end up with.
9184 TargetTypeIsNonStaticMemberFunction = true;
9185
9186 // And skip adding the function if its not in the proper form.
9187 // We'll diagnose this due to an empty set of functions.
9188 if (!OvlExprInfo.HasFormOfMemberPointer)
9189 return;
9190 }
9191 }
9192
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009193 Matches.push_back(std::make_pair(dap,Fn));
9194 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009195 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009196 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009197 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009198
9199 if (OvlExpr->hasExplicitTemplateArgs())
9200 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009201
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009202 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9203 // C++ [over.over]p4:
9204 // If more than one function is selected, [...]
9205 if (Matches.size() > 1) {
9206 if (FoundNonTemplateFunction)
9207 EliminateAllTemplateMatches();
9208 else
9209 EliminateAllExceptMostSpecializedTemplate();
9210 }
9211 }
9212 }
9213
9214private:
9215 bool isTargetTypeAFunction() const {
9216 return TargetFunctionType->isFunctionType();
9217 }
9218
9219 // [ToType] [Return]
9220
9221 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9222 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9223 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9224 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9225 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9226 }
9227
9228 // return true if any matching specializations were found
9229 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9230 const DeclAccessPair& CurAccessFunPair) {
9231 if (CXXMethodDecl *Method
9232 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9233 // Skip non-static function templates when converting to pointer, and
9234 // static when converting to member pointer.
9235 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9236 return false;
9237 }
9238 else if (TargetTypeIsNonStaticMemberFunction)
9239 return false;
9240
9241 // C++ [over.over]p2:
9242 // If the name is a function template, template argument deduction is
9243 // done (14.8.2.2), and if the argument deduction succeeds, the
9244 // resulting template argument list is used to generate a single
9245 // function template specialization, which is added to the set of
9246 // overloaded functions considered.
9247 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009248 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009249 if (Sema::TemplateDeductionResult Result
9250 = S.DeduceTemplateArguments(FunctionTemplate,
9251 &OvlExplicitTemplateArgs,
9252 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009253 Info, /*InOverloadResolution=*/true)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009254 // FIXME: make a note of the failed deduction for diagnostics.
9255 (void)Result;
9256 return false;
9257 }
9258
Douglas Gregor092140a2013-04-17 08:45:07 +00009259 // Template argument deduction ensures that we have an exact match or
9260 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009261 // This function template specicalization works.
9262 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009263 assert(S.isSameOrCompatibleFunctionType(
9264 Context.getCanonicalType(Specialization->getType()),
9265 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009266 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9267 return true;
9268 }
9269
9270 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9271 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009273 // Skip non-static functions when converting to pointer, and static
9274 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009275 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9276 return false;
9277 }
9278 else if (TargetTypeIsNonStaticMemberFunction)
9279 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009280
Chandler Carruthbd647292009-12-29 06:17:27 +00009281 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009282 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009283 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9284 if (S.CheckCUDATarget(Caller, FunDecl))
9285 return false;
9286
Richard Smith60e141e2013-05-04 07:00:32 +00009287 // If any candidate has a placeholder return type, trigger its deduction
9288 // now.
9289 if (S.getLangOpts().CPlusPlus1y &&
9290 FunDecl->getResultType()->isUndeducedType() &&
9291 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9292 return false;
9293
Douglas Gregor43c79c22009-12-09 00:47:37 +00009294 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009295 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9296 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009297 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9298 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009299 Matches.push_back(std::make_pair(CurAccessFunPair,
9300 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009301 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009302 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009303 }
Mike Stump1eb44332009-09-09 15:08:12 +00009304 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009305
9306 return false;
9307 }
9308
9309 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9310 bool Ret = false;
9311
9312 // If the overload expression doesn't have the form of a pointer to
9313 // member, don't try to convert it to a pointer-to-member type.
9314 if (IsInvalidFormOfPointerToMemberFunction())
9315 return false;
9316
9317 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9318 E = OvlExpr->decls_end();
9319 I != E; ++I) {
9320 // Look through any using declarations to find the underlying function.
9321 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9322
9323 // C++ [over.over]p3:
9324 // Non-member functions and static member functions match
9325 // targets of type "pointer-to-function" or "reference-to-function."
9326 // Nonstatic member functions match targets of
9327 // type "pointer-to-member-function."
9328 // Note that according to DR 247, the containing class does not matter.
9329 if (FunctionTemplateDecl *FunctionTemplate
9330 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9331 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9332 Ret = true;
9333 }
9334 // If we have explicit template arguments supplied, skip non-templates.
9335 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9336 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9337 Ret = true;
9338 }
9339 assert(Ret || Matches.empty());
9340 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009341 }
9342
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009343 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009344 // [...] and any given function template specialization F1 is
9345 // eliminated if the set contains a second function template
9346 // specialization whose function template is more specialized
9347 // than the function template of F1 according to the partial
9348 // ordering rules of 14.5.5.2.
9349
9350 // The algorithm specified above is quadratic. We instead use a
9351 // two-pass algorithm (similar to the one used to identify the
9352 // best viable function in an overload set) that identifies the
9353 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009354
9355 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9356 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9357 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009358
John McCallc373d482010-01-27 01:50:18 +00009359 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009360 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9361 TPOC_Other, 0, SourceExpr->getLocStart(),
9362 S.PDiag(),
9363 S.PDiag(diag::err_addr_ovl_ambiguous)
9364 << Matches[0].second->getDeclName(),
9365 S.PDiag(diag::note_ovl_candidate)
9366 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009367 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009368
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009369 if (Result != MatchesCopy.end()) {
9370 // Make it the first and only element
9371 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9372 Matches[0].second = cast<FunctionDecl>(*Result);
9373 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009374 }
9375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009376
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009377 void EliminateAllTemplateMatches() {
9378 // [...] any function template specializations in the set are
9379 // eliminated if the set also contains a non-template function, [...]
9380 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9381 if (Matches[I].second->getPrimaryTemplate() == 0)
9382 ++I;
9383 else {
9384 Matches[I] = Matches[--N];
9385 Matches.set_size(N);
9386 }
9387 }
9388 }
9389
9390public:
9391 void ComplainNoMatchesFound() const {
9392 assert(Matches.empty());
9393 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9394 << OvlExpr->getName() << TargetFunctionType
9395 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009396 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009397 }
9398
9399 bool IsInvalidFormOfPointerToMemberFunction() const {
9400 return TargetTypeIsNonStaticMemberFunction &&
9401 !OvlExprInfo.HasFormOfMemberPointer;
9402 }
9403
9404 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9405 // TODO: Should we condition this on whether any functions might
9406 // have matched, or is it more appropriate to do that in callers?
9407 // TODO: a fixit wouldn't hurt.
9408 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9409 << TargetType << OvlExpr->getSourceRange();
9410 }
9411
9412 void ComplainOfInvalidConversion() const {
9413 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9414 << OvlExpr->getName() << TargetType;
9415 }
9416
9417 void ComplainMultipleMatchesFound() const {
9418 assert(Matches.size() > 1);
9419 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9420 << OvlExpr->getName()
9421 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009422 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009423 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009424
9425 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9426
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009427 int getNumMatches() const { return Matches.size(); }
9428
9429 FunctionDecl* getMatchingFunctionDecl() const {
9430 if (Matches.size() != 1) return 0;
9431 return Matches[0].second;
9432 }
9433
9434 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9435 if (Matches.size() != 1) return 0;
9436 return &Matches[0].first;
9437 }
9438};
9439
9440/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9441/// an overloaded function (C++ [over.over]), where @p From is an
9442/// expression with overloaded function type and @p ToType is the type
9443/// we're trying to resolve to. For example:
9444///
9445/// @code
9446/// int f(double);
9447/// int f(int);
9448///
9449/// int (*pfd)(double) = f; // selects f(double)
9450/// @endcode
9451///
9452/// This routine returns the resulting FunctionDecl if it could be
9453/// resolved, and NULL otherwise. When @p Complain is true, this
9454/// routine will emit diagnostics if there is an error.
9455FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009456Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9457 QualType TargetType,
9458 bool Complain,
9459 DeclAccessPair &FoundResult,
9460 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009461 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009462
9463 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9464 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009465 int NumMatches = Resolver.getNumMatches();
9466 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009467 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009468 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9469 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9470 else
9471 Resolver.ComplainNoMatchesFound();
9472 }
9473 else if (NumMatches > 1 && Complain)
9474 Resolver.ComplainMultipleMatchesFound();
9475 else if (NumMatches == 1) {
9476 Fn = Resolver.getMatchingFunctionDecl();
9477 assert(Fn);
9478 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009479 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009480 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009481 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009482
9483 if (pHadMultipleCandidates)
9484 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009485 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009486}
9487
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009488/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009489/// resolve that overloaded function expression down to a single function.
9490///
9491/// This routine can only resolve template-ids that refer to a single function
9492/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009493/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009494/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009495FunctionDecl *
9496Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9497 bool Complain,
9498 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009499 // C++ [over.over]p1:
9500 // [...] [Note: any redundant set of parentheses surrounding the
9501 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009502 // C++ [over.over]p1:
9503 // [...] The overloaded function name can be preceded by the &
9504 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009505
Douglas Gregor4b52e252009-12-21 23:17:24 +00009506 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009507 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009508 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009509
9510 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009511 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009512
Douglas Gregor4b52e252009-12-21 23:17:24 +00009513 // Look through all of the overloaded functions, searching for one
9514 // whose type matches exactly.
9515 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009516 for (UnresolvedSetIterator I = ovl->decls_begin(),
9517 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009518 // C++0x [temp.arg.explicit]p3:
9519 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009520 // where deduction is not done, if a template argument list is
9521 // specified and it, along with any default template arguments,
9522 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009523 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009524 FunctionTemplateDecl *FunctionTemplate
9525 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009526
Douglas Gregor4b52e252009-12-21 23:17:24 +00009527 // C++ [over.over]p2:
9528 // If the name is a function template, template argument deduction is
9529 // done (14.8.2.2), and if the argument deduction succeeds, the
9530 // resulting template argument list is used to generate a single
9531 // function template specialization, which is added to the set of
9532 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009533 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009534 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009535 if (TemplateDeductionResult Result
9536 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009537 Specialization, Info,
9538 /*InOverloadResolution=*/true)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009539 // FIXME: make a note of the failed deduction for diagnostics.
9540 (void)Result;
9541 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009542 }
9543
John McCall864c0412011-04-26 20:42:42 +00009544 assert(Specialization && "no specialization and no error?");
9545
Douglas Gregor4b52e252009-12-21 23:17:24 +00009546 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009547 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009548 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009549 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9550 << ovl->getName();
9551 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009552 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009553 return 0;
John McCall864c0412011-04-26 20:42:42 +00009554 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009555
John McCall864c0412011-04-26 20:42:42 +00009556 Matched = Specialization;
9557 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009558 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009559
Richard Smith60e141e2013-05-04 07:00:32 +00009560 if (Matched && getLangOpts().CPlusPlus1y &&
9561 Matched->getResultType()->isUndeducedType() &&
9562 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9563 return 0;
9564
Douglas Gregor4b52e252009-12-21 23:17:24 +00009565 return Matched;
9566}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009567
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009568
9569
9570
John McCall6dbba4f2011-10-11 23:14:30 +00009571// Resolve and fix an overloaded expression that can be resolved
9572// because it identifies a single function template specialization.
9573//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009574// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009575//
9576// Return true if it was logically possible to so resolve the
9577// expression, regardless of whether or not it succeeded. Always
9578// returns true if 'complain' is set.
9579bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9580 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9581 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009582 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009583 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009584 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009585
John McCall6dbba4f2011-10-11 23:14:30 +00009586 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009587
John McCall864c0412011-04-26 20:42:42 +00009588 DeclAccessPair found;
9589 ExprResult SingleFunctionExpression;
9590 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9591 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009592 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009593 SrcExpr = ExprError();
9594 return true;
9595 }
John McCall864c0412011-04-26 20:42:42 +00009596
9597 // It is only correct to resolve to an instance method if we're
9598 // resolving a form that's permitted to be a pointer to member.
9599 // Otherwise we'll end up making a bound member expression, which
9600 // is illegal in all the contexts we resolve like this.
9601 if (!ovl.HasFormOfMemberPointer &&
9602 isa<CXXMethodDecl>(fn) &&
9603 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009604 if (!complain) return false;
9605
9606 Diag(ovl.Expression->getExprLoc(),
9607 diag::err_bound_member_function)
9608 << 0 << ovl.Expression->getSourceRange();
9609
9610 // TODO: I believe we only end up here if there's a mix of
9611 // static and non-static candidates (otherwise the expression
9612 // would have 'bound member' type, not 'overload' type).
9613 // Ideally we would note which candidate was chosen and why
9614 // the static candidates were rejected.
9615 SrcExpr = ExprError();
9616 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009617 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009618
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009619 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009620 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009621 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009622
9623 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009624 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009625 SingleFunctionExpression =
9626 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009627 if (SingleFunctionExpression.isInvalid()) {
9628 SrcExpr = ExprError();
9629 return true;
9630 }
9631 }
John McCall864c0412011-04-26 20:42:42 +00009632 }
9633
9634 if (!SingleFunctionExpression.isUsable()) {
9635 if (complain) {
9636 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9637 << ovl.Expression->getName()
9638 << DestTypeForComplaining
9639 << OpRangeForComplaining
9640 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009641 NoteAllOverloadCandidates(SrcExpr.get());
9642
9643 SrcExpr = ExprError();
9644 return true;
9645 }
9646
9647 return false;
John McCall864c0412011-04-26 20:42:42 +00009648 }
9649
John McCall6dbba4f2011-10-11 23:14:30 +00009650 SrcExpr = SingleFunctionExpression;
9651 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009652}
9653
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009654/// \brief Add a single candidate to the overload set.
9655static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009656 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009657 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009658 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009659 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009660 bool PartialOverloading,
9661 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009662 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009663 if (isa<UsingShadowDecl>(Callee))
9664 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9665
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009666 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009667 if (ExplicitTemplateArgs) {
9668 assert(!KnownValid && "Explicit template arguments?");
9669 return;
9670 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009671 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9672 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009673 return;
John McCallba135432009-11-21 08:51:07 +00009674 }
9675
9676 if (FunctionTemplateDecl *FuncTemplate
9677 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009678 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009679 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009680 return;
9681 }
9682
Richard Smith2ced0442011-06-26 22:19:54 +00009683 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009684}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009685
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009686/// \brief Add the overload candidates named by callee and/or found by argument
9687/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009688void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009689 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009690 OverloadCandidateSet &CandidateSet,
9691 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009692
9693#ifndef NDEBUG
9694 // Verify that ArgumentDependentLookup is consistent with the rules
9695 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009696 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009697 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9698 // and let Y be the lookup set produced by argument dependent
9699 // lookup (defined as follows). If X contains
9700 //
9701 // -- a declaration of a class member, or
9702 //
9703 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009704 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009705 //
9706 // -- a declaration that is neither a function or a function
9707 // template
9708 //
9709 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009710
John McCall3b4294e2009-12-16 12:17:52 +00009711 if (ULE->requiresADL()) {
9712 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9713 E = ULE->decls_end(); I != E; ++I) {
9714 assert(!(*I)->getDeclContext()->isRecord());
9715 assert(isa<UsingShadowDecl>(*I) ||
9716 !(*I)->getDeclContext()->isFunctionOrMethod());
9717 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009718 }
9719 }
9720#endif
9721
John McCall3b4294e2009-12-16 12:17:52 +00009722 // It would be nice to avoid this copy.
9723 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009724 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009725 if (ULE->hasExplicitTemplateArgs()) {
9726 ULE->copyTemplateArgumentsInto(TABuffer);
9727 ExplicitTemplateArgs = &TABuffer;
9728 }
9729
9730 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9731 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009732 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9733 CandidateSet, PartialOverloading,
9734 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009735
John McCall3b4294e2009-12-16 12:17:52 +00009736 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009737 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009738 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009739 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009740 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009741}
John McCall578b69b2009-12-16 08:11:27 +00009742
Richard Smithd3ff3252013-06-12 22:56:54 +00009743/// Determine whether a declaration with the specified name could be moved into
9744/// a different namespace.
9745static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9746 switch (Name.getCXXOverloadedOperator()) {
9747 case OO_New: case OO_Array_New:
9748 case OO_Delete: case OO_Array_Delete:
9749 return false;
9750
9751 default:
9752 return true;
9753 }
9754}
9755
Richard Smithf50e88a2011-06-05 22:42:48 +00009756/// Attempt to recover from an ill-formed use of a non-dependent name in a
9757/// template, where the non-dependent name was declared after the template
9758/// was defined. This is common in code written for a compilers which do not
9759/// correctly implement two-stage name lookup.
9760///
9761/// Returns true if a viable candidate was found and a diagnostic was issued.
9762static bool
9763DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9764 const CXXScopeSpec &SS, LookupResult &R,
9765 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009766 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009767 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9768 return false;
9769
9770 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009771 if (DC->isTransparentContext())
9772 continue;
9773
Richard Smithf50e88a2011-06-05 22:42:48 +00009774 SemaRef.LookupQualifiedName(R, DC);
9775
9776 if (!R.empty()) {
9777 R.suppressDiagnostics();
9778
9779 if (isa<CXXRecordDecl>(DC)) {
9780 // Don't diagnose names we find in classes; we get much better
9781 // diagnostics for these from DiagnoseEmptyLookup.
9782 R.clear();
9783 return false;
9784 }
9785
9786 OverloadCandidateSet Candidates(FnLoc);
9787 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9788 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009789 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009790 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009791
9792 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009793 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009794 // No viable functions. Don't bother the user with notes for functions
9795 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009796 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009797 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009798 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009799
9800 // Find the namespaces where ADL would have looked, and suggest
9801 // declaring the function there instead.
9802 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9803 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009804 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009805 AssociatedNamespaces,
9806 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009807 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009808 if (canBeDeclaredInNamespace(R.getLookupName())) {
9809 DeclContext *Std = SemaRef.getStdNamespace();
9810 for (Sema::AssociatedNamespaceSet::iterator
9811 it = AssociatedNamespaces.begin(),
9812 end = AssociatedNamespaces.end(); it != end; ++it) {
9813 // Never suggest declaring a function within namespace 'std'.
9814 if (Std && Std->Encloses(*it))
9815 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009816
Richard Smithd3ff3252013-06-12 22:56:54 +00009817 // Never suggest declaring a function within a namespace with a
9818 // reserved name, like __gnu_cxx.
9819 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9820 if (NS &&
9821 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9822 continue;
9823
9824 SuggestedNamespaces.insert(*it);
9825 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009826 }
9827
9828 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9829 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009830 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009831 SemaRef.Diag(Best->Function->getLocation(),
9832 diag::note_not_found_by_two_phase_lookup)
9833 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009834 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009835 SemaRef.Diag(Best->Function->getLocation(),
9836 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009837 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009838 } else {
9839 // FIXME: It would be useful to list the associated namespaces here,
9840 // but the diagnostics infrastructure doesn't provide a way to produce
9841 // a localized representation of a list of items.
9842 SemaRef.Diag(Best->Function->getLocation(),
9843 diag::note_not_found_by_two_phase_lookup)
9844 << R.getLookupName() << 2;
9845 }
9846
9847 // Try to recover by calling this function.
9848 return true;
9849 }
9850
9851 R.clear();
9852 }
9853
9854 return false;
9855}
9856
9857/// Attempt to recover from ill-formed use of a non-dependent operator in a
9858/// template, where the non-dependent operator was declared after the template
9859/// was defined.
9860///
9861/// Returns true if a viable candidate was found and a diagnostic was issued.
9862static bool
9863DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9864 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009865 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009866 DeclarationName OpName =
9867 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9868 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9869 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009870 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009871}
9872
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009873namespace {
9874// Callback to limit the allowed keywords and to only accept typo corrections
9875// that are keywords or whose decls refer to functions (or template functions)
9876// that accept the given number of arguments.
9877class RecoveryCallCCC : public CorrectionCandidateCallback {
9878 public:
9879 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9880 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009881 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009882 WantRemainingKeywords = false;
9883 }
9884
9885 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9886 if (!candidate.getCorrectionDecl())
9887 return candidate.isKeyword();
9888
9889 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9890 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9891 FunctionDecl *FD = 0;
9892 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9893 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9894 FD = FTD->getTemplatedDecl();
9895 if (!HasExplicitTemplateArgs && !FD) {
9896 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9897 // If the Decl is neither a function nor a template function,
9898 // determine if it is a pointer or reference to a function. If so,
9899 // check against the number of arguments expected for the pointee.
9900 QualType ValType = cast<ValueDecl>(ND)->getType();
9901 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9902 ValType = ValType->getPointeeType();
9903 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9904 if (FPT->getNumArgs() == NumArgs)
9905 return true;
9906 }
9907 }
9908 if (FD && FD->getNumParams() >= NumArgs &&
9909 FD->getMinRequiredArguments() <= NumArgs)
9910 return true;
9911 }
9912 return false;
9913 }
9914
9915 private:
9916 unsigned NumArgs;
9917 bool HasExplicitTemplateArgs;
9918};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009919
9920// Callback that effectively disabled typo correction
9921class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9922 public:
9923 NoTypoCorrectionCCC() {
9924 WantTypeSpecifiers = false;
9925 WantExpressionKeywords = false;
9926 WantCXXNamedCasts = false;
9927 WantRemainingKeywords = false;
9928 }
9929
9930 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9931 return false;
9932 }
9933};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009934
9935class BuildRecoveryCallExprRAII {
9936 Sema &SemaRef;
9937public:
9938 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9939 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9940 SemaRef.IsBuildingRecoveryCallExpr = true;
9941 }
9942
9943 ~BuildRecoveryCallExprRAII() {
9944 SemaRef.IsBuildingRecoveryCallExpr = false;
9945 }
9946};
9947
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009948}
9949
John McCall578b69b2009-12-16 08:11:27 +00009950/// Attempts to recover from a call where no functions were found.
9951///
9952/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009953static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009954BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009955 UnresolvedLookupExpr *ULE,
9956 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009957 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009958 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009959 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009960 // Do not try to recover if it is already building a recovery call.
9961 // This stops infinite loops for template instantiations like
9962 //
9963 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9964 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9965 //
9966 if (SemaRef.IsBuildingRecoveryCallExpr)
9967 return ExprError();
9968 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009969
9970 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009971 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009972 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009973
John McCall3b4294e2009-12-16 12:17:52 +00009974 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009975 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009976 if (ULE->hasExplicitTemplateArgs()) {
9977 ULE->copyTemplateArgumentsInto(TABuffer);
9978 ExplicitTemplateArgs = &TABuffer;
9979 }
9980
John McCall578b69b2009-12-16 08:11:27 +00009981 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9982 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009983 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009984 NoTypoCorrectionCCC RejectAll;
9985 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9986 (CorrectionCandidateCallback*)&Validator :
9987 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009988 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009989 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009990 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009991 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009992 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009993 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009994
John McCall3b4294e2009-12-16 12:17:52 +00009995 assert(!R.empty() && "lookup results empty despite recovery");
9996
9997 // Build an implicit member call if appropriate. Just drop the
9998 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009999 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010000 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010001 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10002 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010003 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010004 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010005 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010006 else
10007 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10008
10009 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010010 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010011
10012 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010013 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010014 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010015 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010016 MultiExprArg(Args.data(), Args.size()),
10017 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010018}
Douglas Gregord7a95972010-06-08 17:35:15 +000010019
Sam Panzere1715b62012-08-21 00:52:01 +000010020/// \brief Constructs and populates an OverloadedCandidateSet from
10021/// the given function.
10022/// \returns true when an the ExprResult output parameter has been set.
10023bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10024 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010025 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010026 SourceLocation RParenLoc,
10027 OverloadCandidateSet *CandidateSet,
10028 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010029#ifndef NDEBUG
10030 if (ULE->requiresADL()) {
10031 // To do ADL, we must have found an unqualified name.
10032 assert(!ULE->getQualifier() && "qualified name with ADL");
10033
10034 // We don't perform ADL for implicit declarations of builtins.
10035 // Verify that this was correctly set up.
10036 FunctionDecl *F;
10037 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10038 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10039 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010040 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010041
John McCall3b4294e2009-12-16 12:17:52 +000010042 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010043 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010044 }
John McCall3b4294e2009-12-16 12:17:52 +000010045#endif
10046
John McCall5acb0c92011-10-17 18:40:02 +000010047 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010048 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010049 *Result = ExprError();
10050 return true;
10051 }
Douglas Gregor17330012009-02-04 15:01:18 +000010052
John McCall3b4294e2009-12-16 12:17:52 +000010053 // Add the functions denoted by the callee to the set of candidate
10054 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010055 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010056
10057 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010058 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10059 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010060 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010061 // In Microsoft mode, if we are inside a template class member function then
10062 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010063 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010064 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010065 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010066 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010067 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010068 Context.DependentTy, VK_RValue,
10069 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010070 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010071 *Result = Owned(CE);
10072 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010073 }
Sam Panzere1715b62012-08-21 00:52:01 +000010074 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010075 }
John McCall578b69b2009-12-16 08:11:27 +000010076
John McCall5acb0c92011-10-17 18:40:02 +000010077 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010078 return false;
10079}
John McCall5acb0c92011-10-17 18:40:02 +000010080
Sam Panzere1715b62012-08-21 00:52:01 +000010081/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10082/// the completed call expression. If overload resolution fails, emits
10083/// diagnostics and returns ExprError()
10084static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10085 UnresolvedLookupExpr *ULE,
10086 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010087 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010088 SourceLocation RParenLoc,
10089 Expr *ExecConfig,
10090 OverloadCandidateSet *CandidateSet,
10091 OverloadCandidateSet::iterator *Best,
10092 OverloadingResult OverloadResult,
10093 bool AllowTypoCorrection) {
10094 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010095 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010096 RParenLoc, /*EmptyLookup=*/true,
10097 AllowTypoCorrection);
10098
10099 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010100 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010101 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010102 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010103 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10104 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010105 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010106 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10107 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010108 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010109
Richard Smithf50e88a2011-06-05 22:42:48 +000010110 case OR_No_Viable_Function: {
10111 // Try to recover by looking for viable functions which the user might
10112 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010113 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010114 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010115 /*EmptyLookup=*/false,
10116 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010117 if (!Recovery.isInvalid())
10118 return Recovery;
10119
Sam Panzere1715b62012-08-21 00:52:01 +000010120 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010121 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010122 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010123 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010124 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010125 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010126
10127 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010128 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010129 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010130 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010131 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010132
Sam Panzere1715b62012-08-21 00:52:01 +000010133 case OR_Deleted: {
10134 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10135 << (*Best)->Function->isDeleted()
10136 << ULE->getName()
10137 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10138 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010139 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010140
Sam Panzere1715b62012-08-21 00:52:01 +000010141 // We emitted an error for the unvailable/deleted function call but keep
10142 // the call in the AST.
10143 FunctionDecl *FDecl = (*Best)->Function;
10144 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010145 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10146 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010147 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010148 }
10149
Douglas Gregorff331c12010-07-25 18:17:45 +000010150 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010151 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010152}
10153
Sam Panzere1715b62012-08-21 00:52:01 +000010154/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10155/// (which eventually refers to the declaration Func) and the call
10156/// arguments Args/NumArgs, attempt to resolve the function call down
10157/// to a specific function. If overload resolution succeeds, returns
10158/// the call expression produced by overload resolution.
10159/// Otherwise, emits diagnostics and returns ExprError.
10160ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10161 UnresolvedLookupExpr *ULE,
10162 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010163 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010164 SourceLocation RParenLoc,
10165 Expr *ExecConfig,
10166 bool AllowTypoCorrection) {
10167 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10168 ExprResult result;
10169
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010170 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10171 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010172 return result;
10173
10174 OverloadCandidateSet::iterator Best;
10175 OverloadingResult OverloadResult =
10176 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10177
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010178 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010179 RParenLoc, ExecConfig, &CandidateSet,
10180 &Best, OverloadResult,
10181 AllowTypoCorrection);
10182}
10183
John McCall6e266892010-01-26 03:27:55 +000010184static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010185 return Functions.size() > 1 ||
10186 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10187}
10188
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010189/// \brief Create a unary operation that may resolve to an overloaded
10190/// operator.
10191///
10192/// \param OpLoc The location of the operator itself (e.g., '*').
10193///
10194/// \param OpcIn The UnaryOperator::Opcode that describes this
10195/// operator.
10196///
James Dennett40ae6662012-06-22 08:52:37 +000010197/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010198/// considered by overload resolution. The caller needs to build this
10199/// set based on the context using, e.g.,
10200/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10201/// set should not contain any member functions; those will be added
10202/// by CreateOverloadedUnaryOp().
10203///
James Dennett8da16872012-06-22 10:32:46 +000010204/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010205ExprResult
John McCall6e266892010-01-26 03:27:55 +000010206Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10207 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010208 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010209 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010210
10211 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10212 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10213 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010214 // TODO: provide better source location info.
10215 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010216
John McCall5acb0c92011-10-17 18:40:02 +000010217 if (checkPlaceholderForOverload(*this, Input))
10218 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010219
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010220 Expr *Args[2] = { Input, 0 };
10221 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010222
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010223 // For post-increment and post-decrement, add the implicit '0' as
10224 // the second argument, so that we know this is a post-increment or
10225 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010226 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010227 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010228 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10229 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010230 NumArgs = 2;
10231 }
10232
Richard Smith958ba642013-05-05 15:51:06 +000010233 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10234
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010235 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010236 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010237 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010238 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010239 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010240 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010241 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010242
John McCallc373d482010-01-27 01:50:18 +000010243 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010244 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010245 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010246 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010247 /*ADL*/ true, IsOverloaded(Fns),
10248 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010249 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010250 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010251 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010252 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010253 }
10254
10255 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010256 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010257
10258 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010259 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010260
10261 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010262 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010263
John McCall6e266892010-01-26 03:27:55 +000010264 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010265 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10266 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010267 CandidateSet);
10268
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010269 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010270 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010271
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10273
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010274 // Perform overload resolution.
10275 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010276 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010277 case OR_Success: {
10278 // We found a built-in operator or an overloaded operator.
10279 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010280
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010281 if (FnDecl) {
10282 // We matched an overloaded operator. Build a call to that
10283 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010284
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010285 // Convert the arguments.
10286 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010287 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010288
John Wiegley429bb272011-04-08 18:41:53 +000010289 ExprResult InputRes =
10290 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10291 Best->FoundDecl, Method);
10292 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010293 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010294 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010295 } else {
10296 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010297 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010298 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010299 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010300 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010301 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010302 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010303 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010304 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010305 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010306 }
10307
John McCallf89e55a2010-11-18 06:31:45 +000010308 // Determine the result type.
10309 QualType ResultTy = FnDecl->getResultType();
10310 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10311 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010312
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010313 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010314 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010315 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010316 if (FnExpr.isInvalid())
10317 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010318
Eli Friedman4c3b8962009-11-18 03:58:17 +000010319 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010320 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010321 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010322 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010323
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010324 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010325 FnDecl))
10326 return ExprError();
10327
John McCall9ae2f072010-08-23 23:25:46 +000010328 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010329 } else {
10330 // We matched a built-in operator. Convert the arguments, then
10331 // break out so that we will build the appropriate built-in
10332 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010333 ExprResult InputRes =
10334 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10335 Best->Conversions[0], AA_Passing);
10336 if (InputRes.isInvalid())
10337 return ExprError();
10338 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010339 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010340 }
John Wiegley429bb272011-04-08 18:41:53 +000010341 }
10342
10343 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010344 // This is an erroneous use of an operator which can be overloaded by
10345 // a non-member function. Check for non-member operators which were
10346 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010347 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010348 // FIXME: Recover by calling the found function.
10349 return ExprError();
10350
John Wiegley429bb272011-04-08 18:41:53 +000010351 // No viable function; fall through to handling this as a
10352 // built-in operator, which will produce an error message for us.
10353 break;
10354
10355 case OR_Ambiguous:
10356 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10357 << UnaryOperator::getOpcodeStr(Opc)
10358 << Input->getType()
10359 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010360 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010361 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10362 return ExprError();
10363
10364 case OR_Deleted:
10365 Diag(OpLoc, diag::err_ovl_deleted_oper)
10366 << Best->Function->isDeleted()
10367 << UnaryOperator::getOpcodeStr(Opc)
10368 << getDeletedOrUnavailableSuffix(Best->Function)
10369 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010370 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010371 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010372 return ExprError();
10373 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010374
10375 // Either we found no viable overloaded operator or we matched a
10376 // built-in operator. In either case, fall through to trying to
10377 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010378 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010379}
10380
Douglas Gregor063daf62009-03-13 18:40:31 +000010381/// \brief Create a binary operation that may resolve to an overloaded
10382/// operator.
10383///
10384/// \param OpLoc The location of the operator itself (e.g., '+').
10385///
10386/// \param OpcIn The BinaryOperator::Opcode that describes this
10387/// operator.
10388///
James Dennett40ae6662012-06-22 08:52:37 +000010389/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010390/// considered by overload resolution. The caller needs to build this
10391/// set based on the context using, e.g.,
10392/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10393/// set should not contain any member functions; those will be added
10394/// by CreateOverloadedBinOp().
10395///
10396/// \param LHS Left-hand argument.
10397/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010398ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010399Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010400 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010401 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010402 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010403 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010404 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010405
10406 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10407 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10408 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10409
10410 // If either side is type-dependent, create an appropriate dependent
10411 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010412 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010413 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010414 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010415 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010416 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010417 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010418 Context.DependentTy,
10419 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010420 OpLoc,
10421 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010422
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010423 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10424 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010425 VK_LValue,
10426 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010427 Context.DependentTy,
10428 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010429 OpLoc,
10430 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010431 }
John McCall6e266892010-01-26 03:27:55 +000010432
10433 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010434 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010435 // TODO: provide better source location info in DNLoc component.
10436 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010437 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010438 = UnresolvedLookupExpr::Create(Context, NamingClass,
10439 NestedNameSpecifierLoc(), OpNameInfo,
10440 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010441 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010442 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10443 Context.DependentTy, VK_RValue,
10444 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010445 }
10446
John McCall5acb0c92011-10-17 18:40:02 +000010447 // Always do placeholder-like conversions on the RHS.
10448 if (checkPlaceholderForOverload(*this, Args[1]))
10449 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010450
John McCall3c3b7f92011-10-25 17:37:35 +000010451 // Do placeholder-like conversion on the LHS; note that we should
10452 // not get here with a PseudoObject LHS.
10453 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010454 if (checkPlaceholderForOverload(*this, Args[0]))
10455 return ExprError();
10456
Sebastian Redl275c2b42009-11-18 23:10:33 +000010457 // If this is the assignment operator, we only perform overload resolution
10458 // if the left-hand side is a class or enumeration type. This is actually
10459 // a hack. The standard requires that we do overload resolution between the
10460 // various built-in candidates, but as DR507 points out, this can lead to
10461 // problems. So we do it this way, which pretty much follows what GCC does.
10462 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010463 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010464 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010465
John McCall0e800c92010-12-04 08:14:53 +000010466 // If this is the .* operator, which is not overloadable, just
10467 // create a built-in binary operator.
10468 if (Opc == BO_PtrMemD)
10469 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10470
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010471 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010472 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010473
10474 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010475 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010476
10477 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010478 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010479
John McCall6e266892010-01-26 03:27:55 +000010480 // Add candidates from ADL.
10481 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010482 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010483 /*ExplicitTemplateArgs*/ 0,
10484 CandidateSet);
10485
Douglas Gregor063daf62009-03-13 18:40:31 +000010486 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010487 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010488
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010489 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10490
Douglas Gregor063daf62009-03-13 18:40:31 +000010491 // Perform overload resolution.
10492 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010493 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010494 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010495 // We found a built-in operator or an overloaded operator.
10496 FunctionDecl *FnDecl = Best->Function;
10497
10498 if (FnDecl) {
10499 // We matched an overloaded operator. Build a call to that
10500 // operator.
10501
10502 // Convert the arguments.
10503 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010504 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010505 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010506
Chandler Carruth6df868e2010-12-12 08:17:55 +000010507 ExprResult Arg1 =
10508 PerformCopyInitialization(
10509 InitializedEntity::InitializeParameter(Context,
10510 FnDecl->getParamDecl(0)),
10511 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010512 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010513 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010514
John Wiegley429bb272011-04-08 18:41:53 +000010515 ExprResult Arg0 =
10516 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10517 Best->FoundDecl, Method);
10518 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010519 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010520 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010521 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010522 } else {
10523 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010524 ExprResult Arg0 = PerformCopyInitialization(
10525 InitializedEntity::InitializeParameter(Context,
10526 FnDecl->getParamDecl(0)),
10527 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010528 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010529 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010530
Chandler Carruth6df868e2010-12-12 08:17:55 +000010531 ExprResult Arg1 =
10532 PerformCopyInitialization(
10533 InitializedEntity::InitializeParameter(Context,
10534 FnDecl->getParamDecl(1)),
10535 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010536 if (Arg1.isInvalid())
10537 return ExprError();
10538 Args[0] = LHS = Arg0.takeAs<Expr>();
10539 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010540 }
10541
John McCallf89e55a2010-11-18 06:31:45 +000010542 // Determine the result type.
10543 QualType ResultTy = FnDecl->getResultType();
10544 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10545 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010546
10547 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010548 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010549 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010550 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010551 if (FnExpr.isInvalid())
10552 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010553
John McCall9ae2f072010-08-23 23:25:46 +000010554 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010555 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010556 Args, ResultTy, VK, OpLoc,
10557 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010558
10559 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010560 FnDecl))
10561 return ExprError();
10562
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010563 ArrayRef<const Expr *> ArgsArray(Args, 2);
10564 // Cut off the implicit 'this'.
10565 if (isa<CXXMethodDecl>(FnDecl))
10566 ArgsArray = ArgsArray.slice(1);
10567 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10568 TheCall->getSourceRange(), VariadicDoesNotApply);
10569
John McCall9ae2f072010-08-23 23:25:46 +000010570 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010571 } else {
10572 // We matched a built-in operator. Convert the arguments, then
10573 // break out so that we will build the appropriate built-in
10574 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010575 ExprResult ArgsRes0 =
10576 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10577 Best->Conversions[0], AA_Passing);
10578 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010579 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010580 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010581
John Wiegley429bb272011-04-08 18:41:53 +000010582 ExprResult ArgsRes1 =
10583 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10584 Best->Conversions[1], AA_Passing);
10585 if (ArgsRes1.isInvalid())
10586 return ExprError();
10587 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010588 break;
10589 }
10590 }
10591
Douglas Gregor33074752009-09-30 21:46:01 +000010592 case OR_No_Viable_Function: {
10593 // C++ [over.match.oper]p9:
10594 // If the operator is the operator , [...] and there are no
10595 // viable functions, then the operator is assumed to be the
10596 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010597 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010598 break;
10599
Chandler Carruth6df868e2010-12-12 08:17:55 +000010600 // For class as left operand for assignment or compound assigment
10601 // operator do not fall through to handling in built-in, but report that
10602 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010603 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010604 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010605 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010606 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10607 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010609 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010610 // This is an erroneous use of an operator which can be overloaded by
10611 // a non-member function. Check for non-member operators which were
10612 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010613 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010614 // FIXME: Recover by calling the found function.
10615 return ExprError();
10616
Douglas Gregor33074752009-09-30 21:46:01 +000010617 // No viable function; try to create a built-in operation, which will
10618 // produce an error. Then, show the non-viable candidates.
10619 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010620 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010621 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010622 "C++ binary operator overloading is missing candidates!");
10623 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010624 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010625 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010626 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010627 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010628
10629 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010630 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010631 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010632 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010633 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010634 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010635 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010636 return ExprError();
10637
10638 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010639 if (isImplicitlyDeleted(Best->Function)) {
10640 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10641 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010642 << Context.getRecordType(Method->getParent())
10643 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010644
Richard Smith0f46e642012-12-28 12:23:24 +000010645 // The user probably meant to call this special member. Just
10646 // explain why it's deleted.
10647 NoteDeletedFunction(Method);
10648 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010649 } else {
10650 Diag(OpLoc, diag::err_ovl_deleted_oper)
10651 << Best->Function->isDeleted()
10652 << BinaryOperator::getOpcodeStr(Opc)
10653 << getDeletedOrUnavailableSuffix(Best->Function)
10654 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10655 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010656 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010657 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010658 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010659 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010660
Douglas Gregor33074752009-09-30 21:46:01 +000010661 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010662 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010663}
10664
John McCall60d7b3a2010-08-24 06:29:42 +000010665ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010666Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10667 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010668 Expr *Base, Expr *Idx) {
10669 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010670 DeclarationName OpName =
10671 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10672
10673 // If either side is type-dependent, create an appropriate dependent
10674 // expression.
10675 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10676
John McCallc373d482010-01-27 01:50:18 +000010677 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010678 // CHECKME: no 'operator' keyword?
10679 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10680 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010681 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010682 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010683 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010684 /*ADL*/ true, /*Overloaded*/ false,
10685 UnresolvedSetIterator(),
10686 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010687 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010688
Sebastian Redlf322ed62009-10-29 20:17:01 +000010689 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010690 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010691 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010692 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010693 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010694 }
10695
John McCall5acb0c92011-10-17 18:40:02 +000010696 // Handle placeholders on both operands.
10697 if (checkPlaceholderForOverload(*this, Args[0]))
10698 return ExprError();
10699 if (checkPlaceholderForOverload(*this, Args[1]))
10700 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010701
Sebastian Redlf322ed62009-10-29 20:17:01 +000010702 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010703 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010704
10705 // Subscript can only be overloaded as a member function.
10706
10707 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010708 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010709
10710 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010711 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010712
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010713 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10714
Sebastian Redlf322ed62009-10-29 20:17:01 +000010715 // Perform overload resolution.
10716 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010717 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010718 case OR_Success: {
10719 // We found a built-in operator or an overloaded operator.
10720 FunctionDecl *FnDecl = Best->Function;
10721
10722 if (FnDecl) {
10723 // We matched an overloaded operator. Build a call to that
10724 // operator.
10725
John McCall9aa472c2010-03-19 07:35:19 +000010726 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010727
Sebastian Redlf322ed62009-10-29 20:17:01 +000010728 // Convert the arguments.
10729 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010730 ExprResult Arg0 =
10731 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10732 Best->FoundDecl, Method);
10733 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010734 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010735 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010736
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010737 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010738 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010739 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010740 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010741 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010742 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010743 Owned(Args[1]));
10744 if (InputInit.isInvalid())
10745 return ExprError();
10746
10747 Args[1] = InputInit.takeAs<Expr>();
10748
Sebastian Redlf322ed62009-10-29 20:17:01 +000010749 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010750 QualType ResultTy = FnDecl->getResultType();
10751 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10752 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010753
10754 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010755 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10756 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010757 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010758 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010759 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010760 OpLocInfo.getLoc(),
10761 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010762 if (FnExpr.isInvalid())
10763 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010764
John McCall9ae2f072010-08-23 23:25:46 +000010765 CXXOperatorCallExpr *TheCall =
10766 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010767 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010768 ResultTy, VK, RLoc,
10769 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010770
John McCall9ae2f072010-08-23 23:25:46 +000010771 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010772 FnDecl))
10773 return ExprError();
10774
John McCall9ae2f072010-08-23 23:25:46 +000010775 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010776 } else {
10777 // We matched a built-in operator. Convert the arguments, then
10778 // break out so that we will build the appropriate built-in
10779 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010780 ExprResult ArgsRes0 =
10781 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10782 Best->Conversions[0], AA_Passing);
10783 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010784 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010785 Args[0] = ArgsRes0.take();
10786
10787 ExprResult ArgsRes1 =
10788 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10789 Best->Conversions[1], AA_Passing);
10790 if (ArgsRes1.isInvalid())
10791 return ExprError();
10792 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010793
10794 break;
10795 }
10796 }
10797
10798 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010799 if (CandidateSet.empty())
10800 Diag(LLoc, diag::err_ovl_no_oper)
10801 << Args[0]->getType() << /*subscript*/ 0
10802 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10803 else
10804 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10805 << Args[0]->getType()
10806 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010807 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010808 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010809 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010810 }
10811
10812 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010813 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010814 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010815 << Args[0]->getType() << Args[1]->getType()
10816 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010817 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010818 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010819 return ExprError();
10820
10821 case OR_Deleted:
10822 Diag(LLoc, diag::err_ovl_deleted_oper)
10823 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010824 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010825 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010826 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010827 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010828 return ExprError();
10829 }
10830
10831 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010832 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010833}
10834
Douglas Gregor88a35142008-12-22 05:46:06 +000010835/// BuildCallToMemberFunction - Build a call to a member
10836/// function. MemExpr is the expression that refers to the member
10837/// function (and includes the object parameter), Args/NumArgs are the
10838/// arguments to the function call (not including the object
10839/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010840/// expression refers to a non-static member function or an overloaded
10841/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010842ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010843Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010844 SourceLocation LParenLoc,
10845 MultiExprArg Args,
10846 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010847 assert(MemExprE->getType() == Context.BoundMemberTy ||
10848 MemExprE->getType() == Context.OverloadTy);
10849
Douglas Gregor88a35142008-12-22 05:46:06 +000010850 // Dig out the member expression. This holds both the object
10851 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010852 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010853
John McCall864c0412011-04-26 20:42:42 +000010854 // Determine whether this is a call to a pointer-to-member function.
10855 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10856 assert(op->getType() == Context.BoundMemberTy);
10857 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10858
10859 QualType fnType =
10860 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10861
10862 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10863 QualType resultType = proto->getCallResultType(Context);
10864 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10865
10866 // Check that the object type isn't more qualified than the
10867 // member function we're calling.
10868 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10869
10870 QualType objectType = op->getLHS()->getType();
10871 if (op->getOpcode() == BO_PtrMemI)
10872 objectType = objectType->castAs<PointerType>()->getPointeeType();
10873 Qualifiers objectQuals = objectType.getQualifiers();
10874
10875 Qualifiers difference = objectQuals - funcQuals;
10876 difference.removeObjCGCAttr();
10877 difference.removeAddressSpace();
10878 if (difference) {
10879 std::string qualsString = difference.getAsString();
10880 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10881 << fnType.getUnqualifiedType()
10882 << qualsString
10883 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10884 }
10885
10886 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010887 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000010888 resultType, valueKind, RParenLoc);
10889
10890 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010891 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010892 call, 0))
10893 return ExprError();
10894
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010895 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000010896 return ExprError();
10897
Richard Trieue2a90b82013-06-22 02:30:38 +000010898 if (CheckOtherCall(call, proto))
10899 return ExprError();
10900
John McCall864c0412011-04-26 20:42:42 +000010901 return MaybeBindToTemporary(call);
10902 }
10903
John McCall5acb0c92011-10-17 18:40:02 +000010904 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010905 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000010906 return ExprError();
10907
John McCall129e2df2009-11-30 22:42:35 +000010908 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010909 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010910 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010911 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010912 if (isa<MemberExpr>(NakedMemExpr)) {
10913 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010914 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010915 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010916 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010917 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010918 } else {
10919 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010920 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010921
John McCall701c89e2009-12-03 04:06:58 +000010922 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010923 Expr::Classification ObjectClassification
10924 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10925 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010926
Douglas Gregor88a35142008-12-22 05:46:06 +000010927 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010928 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010929
John McCallaa81e162009-12-01 22:10:20 +000010930 // FIXME: avoid copy.
10931 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10932 if (UnresExpr->hasExplicitTemplateArgs()) {
10933 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10934 TemplateArgs = &TemplateArgsBuffer;
10935 }
10936
John McCall129e2df2009-11-30 22:42:35 +000010937 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10938 E = UnresExpr->decls_end(); I != E; ++I) {
10939
John McCall701c89e2009-12-03 04:06:58 +000010940 NamedDecl *Func = *I;
10941 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10942 if (isa<UsingShadowDecl>(Func))
10943 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10944
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010945
Francois Pichetdbee3412011-01-18 05:04:39 +000010946 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010947 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010948 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010949 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010950 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010951 // If explicit template arguments were provided, we can't call a
10952 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010953 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010954 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010955
John McCall9aa472c2010-03-19 07:35:19 +000010956 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010957 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010958 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010959 } else {
John McCall129e2df2009-11-30 22:42:35 +000010960 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010961 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010962 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010963 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010964 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010965 }
Douglas Gregordec06662009-08-21 18:42:58 +000010966 }
Mike Stump1eb44332009-09-09 15:08:12 +000010967
John McCall129e2df2009-11-30 22:42:35 +000010968 DeclarationName DeclName = UnresExpr->getMemberName();
10969
John McCall5acb0c92011-10-17 18:40:02 +000010970 UnbridgedCasts.restore();
10971
Douglas Gregor88a35142008-12-22 05:46:06 +000010972 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010973 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010974 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010975 case OR_Success:
10976 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010977 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010978 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010979 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
10980 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000010981 // If FoundDecl is different from Method (such as if one is a template
10982 // and the other a specialization), make sure DiagnoseUseOfDecl is
10983 // called on both.
10984 // FIXME: This would be more comprehensively addressed by modifying
10985 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
10986 // being used.
10987 if (Method != FoundDecl.getDecl() &&
10988 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
10989 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010990 break;
10991
10992 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010993 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010994 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010995 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010996 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000010997 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010998 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010999
11000 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011001 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011002 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011003 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011004 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011005 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011006
11007 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011008 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011009 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011010 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011011 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011012 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011013 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011014 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011015 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011016 }
11017
John McCall6bb80172010-03-30 21:47:33 +000011018 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011019
John McCallaa81e162009-12-01 22:10:20 +000011020 // If overload resolution picked a static member, build a
11021 // non-member call based on that function.
11022 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011023 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11024 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011025 }
11026
John McCall129e2df2009-11-30 22:42:35 +000011027 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011028 }
11029
John McCallf89e55a2010-11-18 06:31:45 +000011030 QualType ResultType = Method->getResultType();
11031 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11032 ResultType = ResultType.getNonLValueExprType(Context);
11033
Douglas Gregor88a35142008-12-22 05:46:06 +000011034 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011035 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011036 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011037 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011038
Anders Carlssoneed3e692009-10-10 00:06:20 +000011039 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011040 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011041 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011042 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011043
Douglas Gregor88a35142008-12-22 05:46:06 +000011044 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011045 // We only need to do this if there was actually an overload; otherwise
11046 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011047 if (!Method->isStatic()) {
11048 ExprResult ObjectArg =
11049 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11050 FoundDecl, Method);
11051 if (ObjectArg.isInvalid())
11052 return ExprError();
11053 MemExpr->setBase(ObjectArg.take());
11054 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011055
11056 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011057 const FunctionProtoType *Proto =
11058 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011059 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011060 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011061 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011062
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011063 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011064
Richard Smith831421f2012-06-25 20:30:08 +000011065 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011066 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011067
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011068 if ((isa<CXXConstructorDecl>(CurContext) ||
11069 isa<CXXDestructorDecl>(CurContext)) &&
11070 TheCall->getMethodDecl()->isPure()) {
11071 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11072
Chandler Carruthae198062011-06-27 08:31:58 +000011073 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011074 Diag(MemExpr->getLocStart(),
11075 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11076 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11077 << MD->getParent()->getDeclName();
11078
11079 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011080 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011081 }
John McCall9ae2f072010-08-23 23:25:46 +000011082 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011083}
11084
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011085/// BuildCallToObjectOfClassType - Build a call to an object of class
11086/// type (C++ [over.call.object]), which can end up invoking an
11087/// overloaded function call operator (@c operator()) or performing a
11088/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011089ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011090Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011091 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011092 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011093 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011094 if (checkPlaceholderForOverload(*this, Obj))
11095 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011096 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011097
11098 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011099 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011100 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011101
John Wiegley429bb272011-04-08 18:41:53 +000011102 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11103 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011104
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011105 // C++ [over.call.object]p1:
11106 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011107 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011108 // candidate functions includes at least the function call
11109 // operators of T. The function call operators of T are obtained by
11110 // ordinary lookup of the name operator() in the context of
11111 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011112 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011113 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011114
John Wiegley429bb272011-04-08 18:41:53 +000011115 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011116 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011117 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011118
John McCalla24dc2e2009-11-17 02:14:36 +000011119 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11120 LookupQualifiedName(R, Record->getDecl());
11121 R.suppressDiagnostics();
11122
Douglas Gregor593564b2009-11-15 07:48:03 +000011123 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011124 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011125 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011126 Object.get()->Classify(Context),
11127 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011128 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011130
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011131 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011132 // In addition, for each (non-explicit in C++0x) conversion function
11133 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011134 //
11135 // operator conversion-type-id () cv-qualifier;
11136 //
11137 // where cv-qualifier is the same cv-qualification as, or a
11138 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011139 // denotes the type "pointer to function of (P1,...,Pn) returning
11140 // R", or the type "reference to pointer to function of
11141 // (P1,...,Pn) returning R", or the type "reference to function
11142 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011143 // is also considered as a candidate function. Similarly,
11144 // surrogate call functions are added to the set of candidate
11145 // functions for each conversion function declared in an
11146 // accessible base class provided the function is not hidden
11147 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011148 std::pair<CXXRecordDecl::conversion_iterator,
11149 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011150 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011151 for (CXXRecordDecl::conversion_iterator
11152 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011153 NamedDecl *D = *I;
11154 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11155 if (isa<UsingShadowDecl>(D))
11156 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011157
Douglas Gregor4a27d702009-10-21 06:18:39 +000011158 // Skip over templated conversion functions; they aren't
11159 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011160 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011161 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011162
John McCall701c89e2009-12-03 04:06:58 +000011163 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011164 if (!Conv->isExplicit()) {
11165 // Strip the reference type (if any) and then the pointer type (if
11166 // any) to get down to what might be a function type.
11167 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11168 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11169 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011170
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011171 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11172 {
11173 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011174 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011175 }
11176 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011177 }
Mike Stump1eb44332009-09-09 15:08:12 +000011178
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011179 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11180
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011181 // Perform overload resolution.
11182 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011183 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011184 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011185 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011186 // Overload resolution succeeded; we'll build the appropriate call
11187 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011188 break;
11189
11190 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011191 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011192 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011193 << Object.get()->getType() << /*call*/ 1
11194 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011195 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011196 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011197 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011198 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011199 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011200 break;
11201
11202 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011203 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011204 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011205 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011206 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011207 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011208
11209 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011210 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011211 diag::err_ovl_deleted_object_call)
11212 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011213 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011214 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011215 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011216 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011217 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011218 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011219
Douglas Gregorff331c12010-07-25 18:17:45 +000011220 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011221 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011222
John McCall5acb0c92011-10-17 18:40:02 +000011223 UnbridgedCasts.restore();
11224
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011225 if (Best->Function == 0) {
11226 // Since there is no function declaration, this is one of the
11227 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011228 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011229 = cast<CXXConversionDecl>(
11230 Best->Conversions[0].UserDefined.ConversionFunction);
11231
John Wiegley429bb272011-04-08 18:41:53 +000011232 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011233 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11234 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011235 assert(Conv == Best->FoundDecl.getDecl() &&
11236 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011237 // We selected one of the surrogate functions that converts the
11238 // object parameter to a function pointer. Perform the conversion
11239 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011240
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011241 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011242 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011243 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11244 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011245 if (Call.isInvalid())
11246 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011247 // Record usage of conversion in an implicit cast.
11248 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11249 CK_UserDefinedConversion,
11250 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011251
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011252 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011253 }
11254
John Wiegley429bb272011-04-08 18:41:53 +000011255 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011256
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011257 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11258 // that calls this method, using Object for the implicit object
11259 // parameter and passing along the remaining arguments.
11260 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011261
11262 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011263 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011264 return ExprError();
11265
Chandler Carruth6df868e2010-12-12 08:17:55 +000011266 const FunctionProtoType *Proto =
11267 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011268
11269 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011270 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011271
11272 // Build the full argument list for the method call (the
11273 // implicit object parameter is placed at the beginning of the
11274 // list).
11275 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011276 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011277 NumArgsToCheck = NumArgsInProto;
11278 MethodArgs = new Expr*[NumArgsInProto + 1];
11279 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011280 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011281 }
John Wiegley429bb272011-04-08 18:41:53 +000011282 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011283 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011284 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011285
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011286 DeclarationNameInfo OpLocInfo(
11287 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11288 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011289 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011290 HadMultipleCandidates,
11291 OpLocInfo.getLoc(),
11292 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011293 if (NewFn.isInvalid())
11294 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011295
11296 // Once we've built TheCall, all of the expressions are properly
11297 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011298 QualType ResultTy = Method->getResultType();
11299 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11300 ResultTy = ResultTy.getNonLValueExprType(Context);
11301
John McCall9ae2f072010-08-23 23:25:46 +000011302 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011303 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011304 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011305 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011306 delete [] MethodArgs;
11307
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011308 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011309 Method))
11310 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011311
Douglas Gregor518fda12009-01-13 05:10:00 +000011312 // We may have default arguments. If so, we need to allocate more
11313 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011314 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011315 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011316 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011317 NumArgsToCheck = NumArgsInProto;
11318
Chris Lattner312531a2009-04-12 08:11:20 +000011319 bool IsError = false;
11320
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011321 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011322 ExprResult ObjRes =
11323 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11324 Best->FoundDecl, Method);
11325 if (ObjRes.isInvalid())
11326 IsError = true;
11327 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011328 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011329 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011330
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011331 // Check the argument types.
11332 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011333 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011334 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011335 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011336
Douglas Gregor518fda12009-01-13 05:10:00 +000011337 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011338
John McCall60d7b3a2010-08-24 06:29:42 +000011339 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011340 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011341 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011342 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011343 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011344
Anders Carlsson3faa4862010-01-29 18:43:53 +000011345 IsError |= InputInit.isInvalid();
11346 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011347 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011348 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011349 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11350 if (DefArg.isInvalid()) {
11351 IsError = true;
11352 break;
11353 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011354
Douglas Gregord47c47d2009-11-09 19:27:57 +000011355 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011356 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011357
11358 TheCall->setArg(i + 1, Arg);
11359 }
11360
11361 // If this is a variadic call, handle args passed through "...".
11362 if (Proto->isVariadic()) {
11363 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011364 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011365 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11366 IsError |= Arg.isInvalid();
11367 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011368 }
11369 }
11370
Chris Lattner312531a2009-04-12 08:11:20 +000011371 if (IsError) return true;
11372
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011373 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011374
Richard Smith831421f2012-06-25 20:30:08 +000011375 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011376 return true;
11377
John McCall182f7092010-08-24 06:09:16 +000011378 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011379}
11380
Douglas Gregor8ba10742008-11-20 16:27:02 +000011381/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011382/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011383/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011384ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011385Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011386 assert(Base->getType()->isRecordType() &&
11387 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011388
John McCall5acb0c92011-10-17 18:40:02 +000011389 if (checkPlaceholderForOverload(*this, Base))
11390 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011391
John McCall5769d612010-02-08 23:07:23 +000011392 SourceLocation Loc = Base->getExprLoc();
11393
Douglas Gregor8ba10742008-11-20 16:27:02 +000011394 // C++ [over.ref]p1:
11395 //
11396 // [...] An expression x->m is interpreted as (x.operator->())->m
11397 // for a class object x of type T if T::operator->() exists and if
11398 // the operator is selected as the best match function by the
11399 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011400 DeclarationName OpName =
11401 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011402 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011403 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011404
John McCall5769d612010-02-08 23:07:23 +000011405 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011406 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011407 return ExprError();
11408
John McCalla24dc2e2009-11-17 02:14:36 +000011409 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11410 LookupQualifiedName(R, BaseRecord->getDecl());
11411 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011412
11413 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011414 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011415 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011416 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011417 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011418
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011419 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11420
Douglas Gregor8ba10742008-11-20 16:27:02 +000011421 // Perform overload resolution.
11422 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011423 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011424 case OR_Success:
11425 // Overload resolution succeeded; we'll build the call below.
11426 break;
11427
11428 case OR_No_Viable_Function:
11429 if (CandidateSet.empty())
11430 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011431 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011432 else
11433 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011434 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011435 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011436 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011437
11438 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011439 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11440 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011441 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011442 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011443
11444 case OR_Deleted:
11445 Diag(OpLoc, diag::err_ovl_deleted_oper)
11446 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011447 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011448 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011449 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011450 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011451 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011452 }
11453
John McCall9aa472c2010-03-19 07:35:19 +000011454 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11455
Douglas Gregor8ba10742008-11-20 16:27:02 +000011456 // Convert the object parameter.
11457 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011458 ExprResult BaseResult =
11459 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11460 Best->FoundDecl, Method);
11461 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011462 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011463 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011464
Douglas Gregor8ba10742008-11-20 16:27:02 +000011465 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011466 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011467 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011468 if (FnExpr.isInvalid())
11469 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011470
John McCallf89e55a2010-11-18 06:31:45 +000011471 QualType ResultTy = Method->getResultType();
11472 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11473 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011474 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011475 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011476 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011477
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011478 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011479 Method))
11480 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011481
11482 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011483}
11484
Richard Smith36f5cfe2012-03-09 08:00:36 +000011485/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11486/// a literal operator described by the provided lookup results.
11487ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11488 DeclarationNameInfo &SuffixInfo,
11489 ArrayRef<Expr*> Args,
11490 SourceLocation LitEndLoc,
11491 TemplateArgumentListInfo *TemplateArgs) {
11492 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011493
Richard Smith36f5cfe2012-03-09 08:00:36 +000011494 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11495 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11496 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011497
Richard Smith36f5cfe2012-03-09 08:00:36 +000011498 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11499
Richard Smith36f5cfe2012-03-09 08:00:36 +000011500 // Perform overload resolution. This will usually be trivial, but might need
11501 // to perform substitutions for a literal operator template.
11502 OverloadCandidateSet::iterator Best;
11503 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11504 case OR_Success:
11505 case OR_Deleted:
11506 break;
11507
11508 case OR_No_Viable_Function:
11509 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11510 << R.getLookupName();
11511 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11512 return ExprError();
11513
11514 case OR_Ambiguous:
11515 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11516 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11517 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011518 }
11519
Richard Smith36f5cfe2012-03-09 08:00:36 +000011520 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011521 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11522 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011523 SuffixInfo.getLoc(),
11524 SuffixInfo.getInfo());
11525 if (Fn.isInvalid())
11526 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011527
11528 // Check the argument types. This should almost always be a no-op, except
11529 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011530 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011531 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011532 ExprResult InputInit = PerformCopyInitialization(
11533 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11534 SourceLocation(), Args[ArgIdx]);
11535 if (InputInit.isInvalid())
11536 return true;
11537 ConvArgs[ArgIdx] = InputInit.take();
11538 }
11539
Richard Smith9fcce652012-03-07 08:35:16 +000011540 QualType ResultTy = FD->getResultType();
11541 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11542 ResultTy = ResultTy.getNonLValueExprType(Context);
11543
Richard Smith9fcce652012-03-07 08:35:16 +000011544 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011545 new (Context) UserDefinedLiteral(Context, Fn.take(),
11546 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011547 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11548
11549 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11550 return ExprError();
11551
Richard Smith831421f2012-06-25 20:30:08 +000011552 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011553 return ExprError();
11554
11555 return MaybeBindToTemporary(UDL);
11556}
11557
Sam Panzere1715b62012-08-21 00:52:01 +000011558/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11559/// given LookupResult is non-empty, it is assumed to describe a member which
11560/// will be invoked. Otherwise, the function will be found via argument
11561/// dependent lookup.
11562/// CallExpr is set to a valid expression and FRS_Success returned on success,
11563/// otherwise CallExpr is set to ExprError() and some non-success value
11564/// is returned.
11565Sema::ForRangeStatus
11566Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11567 SourceLocation RangeLoc, VarDecl *Decl,
11568 BeginEndFunction BEF,
11569 const DeclarationNameInfo &NameInfo,
11570 LookupResult &MemberLookup,
11571 OverloadCandidateSet *CandidateSet,
11572 Expr *Range, ExprResult *CallExpr) {
11573 CandidateSet->clear();
11574 if (!MemberLookup.empty()) {
11575 ExprResult MemberRef =
11576 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11577 /*IsPtr=*/false, CXXScopeSpec(),
11578 /*TemplateKWLoc=*/SourceLocation(),
11579 /*FirstQualifierInScope=*/0,
11580 MemberLookup,
11581 /*TemplateArgs=*/0);
11582 if (MemberRef.isInvalid()) {
11583 *CallExpr = ExprError();
11584 Diag(Range->getLocStart(), diag::note_in_for_range)
11585 << RangeLoc << BEF << Range->getType();
11586 return FRS_DiagnosticIssued;
11587 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011588 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011589 if (CallExpr->isInvalid()) {
11590 *CallExpr = ExprError();
11591 Diag(Range->getLocStart(), diag::note_in_for_range)
11592 << RangeLoc << BEF << Range->getType();
11593 return FRS_DiagnosticIssued;
11594 }
11595 } else {
11596 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011597 UnresolvedLookupExpr *Fn =
11598 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11599 NestedNameSpecifierLoc(), NameInfo,
11600 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011601 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011602
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011603 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011604 CandidateSet, CallExpr);
11605 if (CandidateSet->empty() || CandidateSetError) {
11606 *CallExpr = ExprError();
11607 return FRS_NoViableFunction;
11608 }
11609 OverloadCandidateSet::iterator Best;
11610 OverloadingResult OverloadResult =
11611 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11612
11613 if (OverloadResult == OR_No_Viable_Function) {
11614 *CallExpr = ExprError();
11615 return FRS_NoViableFunction;
11616 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011617 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011618 Loc, 0, CandidateSet, &Best,
11619 OverloadResult,
11620 /*AllowTypoCorrection=*/false);
11621 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11622 *CallExpr = ExprError();
11623 Diag(Range->getLocStart(), diag::note_in_for_range)
11624 << RangeLoc << BEF << Range->getType();
11625 return FRS_DiagnosticIssued;
11626 }
11627 }
11628 return FRS_Success;
11629}
11630
11631
Douglas Gregor904eed32008-11-10 20:40:00 +000011632/// FixOverloadedFunctionReference - E is an expression that refers to
11633/// a C++ overloaded function (possibly with some parentheses and
11634/// perhaps a '&' around it). We have resolved the overloaded function
11635/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011636/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011637Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011638 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011639 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011640 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11641 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011642 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011643 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011644
Douglas Gregor699ee522009-11-20 19:42:02 +000011645 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011646 }
11647
Douglas Gregor699ee522009-11-20 19:42:02 +000011648 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011649 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11650 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011651 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011652 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011653 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011654 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011655 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011656 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011657
11658 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011659 ICE->getCastKind(),
11660 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011661 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011662 }
11663
Douglas Gregor699ee522009-11-20 19:42:02 +000011664 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011665 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011666 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011667 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11668 if (Method->isStatic()) {
11669 // Do nothing: static member functions aren't any different
11670 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011671 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011672 // Fix the sub expression, which really has to be an
11673 // UnresolvedLookupExpr holding an overloaded member function
11674 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011675 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11676 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011677 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011678 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011679
John McCallba135432009-11-21 08:51:07 +000011680 assert(isa<DeclRefExpr>(SubExpr)
11681 && "fixed to something other than a decl ref");
11682 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11683 && "fixed to a member ref with no nested name qualifier");
11684
11685 // We have taken the address of a pointer to member
11686 // function. Perform the computation here so that we get the
11687 // appropriate pointer to member type.
11688 QualType ClassType
11689 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11690 QualType MemPtrType
11691 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11692
John McCallf89e55a2010-11-18 06:31:45 +000011693 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11694 VK_RValue, OK_Ordinary,
11695 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011696 }
11697 }
John McCall6bb80172010-03-30 21:47:33 +000011698 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11699 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011700 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011701 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011702
John McCall2de56d12010-08-25 11:45:40 +000011703 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011704 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011705 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011706 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011707 }
John McCallba135432009-11-21 08:51:07 +000011708
11709 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011710 // FIXME: avoid copy.
11711 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011712 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011713 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11714 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011715 }
11716
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011717 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11718 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011719 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011720 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011721 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011722 ULE->getNameLoc(),
11723 Fn->getType(),
11724 VK_LValue,
11725 Found.getDecl(),
11726 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011727 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011728 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11729 return DRE;
John McCallba135432009-11-21 08:51:07 +000011730 }
11731
John McCall129e2df2009-11-30 22:42:35 +000011732 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011733 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011734 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11735 if (MemExpr->hasExplicitTemplateArgs()) {
11736 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11737 TemplateArgs = &TemplateArgsBuffer;
11738 }
John McCalld5532b62009-11-23 01:53:49 +000011739
John McCallaa81e162009-12-01 22:10:20 +000011740 Expr *Base;
11741
John McCallf89e55a2010-11-18 06:31:45 +000011742 // If we're filling in a static method where we used to have an
11743 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011744 if (MemExpr->isImplicitAccess()) {
11745 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011746 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11747 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011748 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011749 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011750 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011751 MemExpr->getMemberLoc(),
11752 Fn->getType(),
11753 VK_LValue,
11754 Found.getDecl(),
11755 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011756 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011757 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11758 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011759 } else {
11760 SourceLocation Loc = MemExpr->getMemberLoc();
11761 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011762 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011763 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011764 Base = new (Context) CXXThisExpr(Loc,
11765 MemExpr->getBaseType(),
11766 /*isImplicit=*/true);
11767 }
John McCallaa81e162009-12-01 22:10:20 +000011768 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011769 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011770
John McCallf5307512011-04-27 00:36:17 +000011771 ExprValueKind valueKind;
11772 QualType type;
11773 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11774 valueKind = VK_LValue;
11775 type = Fn->getType();
11776 } else {
11777 valueKind = VK_RValue;
11778 type = Context.BoundMemberTy;
11779 }
11780
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011781 MemberExpr *ME = MemberExpr::Create(Context, Base,
11782 MemExpr->isArrow(),
11783 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011784 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011785 Fn,
11786 Found,
11787 MemExpr->getMemberNameInfo(),
11788 TemplateArgs,
11789 type, valueKind, OK_Ordinary);
11790 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011791 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011792 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011793 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011794
John McCall3fa5cae2010-10-26 07:05:15 +000011795 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011796}
11797
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011798ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011799 DeclAccessPair Found,
11800 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011801 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011802}
11803
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011804} // end namespace clang