blob: 04aaf181af3497d0f778993cea3fc4d9d1ef68cb [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 {
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000551 // 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 };
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000557 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000558 // 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.
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000566OverloadCandidate::DeductionFailureInfo
567static MakeDeductionFailureInfo(ASTContext &Context,
568 Sema::TemplateDeductionResult TDK,
569 TemplateDeductionInfo &Info) {
570 OverloadCandidate::DeductionFailureInfo Result;
Douglas Gregora9333192010-05-08 17:41:32 +0000571 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
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000628void OverloadCandidate::DeductionFailureInfo::Destroy() {
Douglas Gregora9333192010-05-08 17:41:32 +0000629 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
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000662PartialDiagnosticAt *
663OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smithb8590f32012-05-07 09:03:25 +0000664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
666 return 0;
667}
668
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000669TemplateParameter
670OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
Douglas Gregora9333192010-05-08 17:41:32 +0000671 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
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000698TemplateArgumentList *
699OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregorec20f462010-05-08 20:07:26 +0000700 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
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000725const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000726 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
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000751const TemplateArgument *
752OverloadCandidate::DeductionFailureInfo::getSecondArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000753 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
Larisse Voufo8c5d4072013-07-19 22:53:23 +0000778Expr *
779OverloadCandidate::DeductionFailureInfo::getExpr() {
Richard Smith0efa62f2013-01-31 04:03:12 +0000780 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
Richard Smithaa4bc182013-06-30 09:48:50 +0000980bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
981 bool UseUsingDeclRules) {
982 // C++ [basic.start.main]p2: This function shall not be overloaded.
983 if (New->isMain())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000984 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000985
John McCall68263142009-11-18 22:49:29 +0000986 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
987 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
988
989 // C++ [temp.fct]p2:
990 // A function template can be overloaded with other function templates
991 // and with normal (non-template) functions.
992 if ((OldTemplate == 0) != (NewTemplate == 0))
993 return true;
994
995 // Is the function New an overload of the function Old?
Richard Smithaa4bc182013-06-30 09:48:50 +0000996 QualType OldQType = Context.getCanonicalType(Old->getType());
997 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +0000998
999 // Compare the signatures (C++ 1.3.10) of the two functions to
1000 // determine whether they are overloads. If we find any mismatch
1001 // in the signature, they are overloads.
1002
1003 // If either of these functions is a K&R-style function (no
1004 // prototype), then we consider them to have matching signatures.
1005 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1006 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1007 return false;
1008
John McCallf4c73712011-01-19 06:33:43 +00001009 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1010 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001011
1012 // The signature of a function includes the types of its
1013 // parameters (C++ 1.3.10), which includes the presence or absence
1014 // of the ellipsis; see C++ DR 357).
1015 if (OldQType != NewQType &&
1016 (OldType->getNumArgs() != NewType->getNumArgs() ||
1017 OldType->isVariadic() != NewType->isVariadic() ||
Richard Smithaa4bc182013-06-30 09:48:50 +00001018 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001019 return true;
1020
1021 // C++ [temp.over.link]p4:
1022 // The signature of a function template consists of its function
1023 // signature, its return type and its template parameter list. The names
1024 // of the template parameters are significant only for establishing the
1025 // relationship between the template parameters and the rest of the
1026 // signature.
1027 //
1028 // We check the return type and template parameter lists for function
1029 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001030 //
1031 // However, we don't consider either of these when deciding whether
1032 // a member introduced by a shadow declaration is hidden.
1033 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithaa4bc182013-06-30 09:48:50 +00001034 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1035 OldTemplate->getTemplateParameters(),
1036 false, TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001037 OldType->getResultType() != NewType->getResultType()))
1038 return true;
1039
1040 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001041 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001042 //
1043 // As part of this, also check whether one of the member functions
1044 // is static, in which case they are not overloads (C++
1045 // 13.1p2). While not part of the definition of the signature,
1046 // this check is important to determine whether these functions
1047 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001048 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1049 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001050 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001051 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1052 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1053 if (!UseUsingDeclRules &&
1054 (OldMethod->getRefQualifier() == RQ_None ||
1055 NewMethod->getRefQualifier() == RQ_None)) {
1056 // C++0x [over.load]p2:
1057 // - Member function declarations with the same name and the same
1058 // parameter-type-list as well as member function template
1059 // declarations with the same name, the same parameter-type-list, and
1060 // the same template parameter lists cannot be overloaded if any of
1061 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithaa4bc182013-06-30 09:48:50 +00001062 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001063 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithaa4bc182013-06-30 09:48:50 +00001064 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001065 }
1066 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001067 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
Richard Smith21c8fa82013-01-14 05:37:29 +00001069 // We may not have applied the implicit const for a constexpr member
1070 // function yet (because we haven't yet resolved whether this is a static
1071 // or non-static member function). Add it now, on the assumption that this
1072 // is a redeclaration of OldMethod.
1073 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithaa4bc182013-06-30 09:48:50 +00001074 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithdb2fe732013-06-25 18:46:26 +00001075 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001076 NewQuals |= Qualifiers::Const;
1077 if (OldMethod->getTypeQualifiers() != NewQuals)
1078 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001080
John McCall68263142009-11-18 22:49:29 +00001081 // The signatures match; this is not an overload.
1082 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001083}
1084
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001085/// \brief Checks availability of the function depending on the current
1086/// function context. Inside an unavailable function, unavailability is ignored.
1087///
1088/// \returns true if \arg FD is unavailable and current context is inside
1089/// an available function, false otherwise.
1090bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1091 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1092}
1093
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001094/// \brief Tries a user-defined conversion from From to ToType.
1095///
1096/// Produces an implicit conversion sequence for when a standard conversion
1097/// is not an option. See TryImplicitConversion for more information.
1098static ImplicitConversionSequence
1099TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1100 bool SuppressUserConversions,
1101 bool AllowExplicit,
1102 bool InOverloadResolution,
1103 bool CStyle,
1104 bool AllowObjCWritebackConversion) {
1105 ImplicitConversionSequence ICS;
1106
1107 if (SuppressUserConversions) {
1108 // We're not in the case above, so there is no conversion that
1109 // we can perform.
1110 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1111 return ICS;
1112 }
1113
1114 // Attempt user-defined conversion.
1115 OverloadCandidateSet Conversions(From->getExprLoc());
1116 OverloadingResult UserDefResult
1117 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1118 AllowExplicit);
1119
1120 if (UserDefResult == OR_Success) {
1121 ICS.setUserDefined();
1122 // C++ [over.ics.user]p4:
1123 // A conversion of an expression of class type to the same class
1124 // type is given Exact Match rank, and a conversion of an
1125 // expression of class type to a base class of that type is
1126 // given Conversion rank, in spite of the fact that a copy
1127 // constructor (i.e., a user-defined conversion function) is
1128 // called for those cases.
1129 if (CXXConstructorDecl *Constructor
1130 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1131 QualType FromCanon
1132 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1133 QualType ToCanon
1134 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1135 if (Constructor->isCopyConstructor() &&
1136 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1137 // Turn this into a "standard" conversion sequence, so that it
1138 // gets ranked with standard conversion sequences.
1139 ICS.setStandard();
1140 ICS.Standard.setAsIdentityConversion();
1141 ICS.Standard.setFromType(From->getType());
1142 ICS.Standard.setAllToTypes(ToType);
1143 ICS.Standard.CopyConstructor = Constructor;
1144 if (ToCanon != FromCanon)
1145 ICS.Standard.Second = ICK_Derived_To_Base;
1146 }
1147 }
1148
1149 // C++ [over.best.ics]p4:
1150 // However, when considering the argument of a user-defined
1151 // conversion function that is a candidate by 13.3.1.3 when
1152 // invoked for the copying of the temporary in the second step
1153 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1154 // 13.3.1.6 in all cases, only standard conversion sequences and
1155 // ellipsis conversion sequences are allowed.
1156 if (SuppressUserConversions && ICS.isUserDefined()) {
1157 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1158 }
1159 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1160 ICS.setAmbiguous();
1161 ICS.Ambiguous.setFromType(From->getType());
1162 ICS.Ambiguous.setToType(ToType);
1163 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1164 Cand != Conversions.end(); ++Cand)
1165 if (Cand->Viable)
1166 ICS.Ambiguous.addConversion(Cand->Function);
1167 } else {
1168 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1169 }
1170
1171 return ICS;
1172}
1173
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001174/// TryImplicitConversion - Attempt to perform an implicit conversion
1175/// from the given expression (Expr) to the given type (ToType). This
1176/// function returns an implicit conversion sequence that can be used
1177/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001178///
1179/// void f(float f);
1180/// void g(int i) { f(i); }
1181///
1182/// this routine would produce an implicit conversion sequence to
1183/// describe the initialization of f from i, which will be a standard
1184/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1185/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1186//
1187/// Note that this routine only determines how the conversion can be
1188/// performed; it does not actually perform the conversion. As such,
1189/// it will not produce any diagnostics if no conversion is available,
1190/// but will instead return an implicit conversion sequence of kind
1191/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001192///
1193/// If @p SuppressUserConversions, then user-defined conversions are
1194/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001195/// If @p AllowExplicit, then explicit user-defined conversions are
1196/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001197///
1198/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1199/// writeback conversion, which allows __autoreleasing id* parameters to
1200/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001201static ImplicitConversionSequence
1202TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1203 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001205 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001206 bool CStyle,
1207 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001208 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001209 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001210 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001211 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001212 return ICS;
1213 }
1214
David Blaikie4e4d0842012-03-11 07:00:24 +00001215 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001216 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001217 return ICS;
1218 }
1219
Douglas Gregor604eb652010-08-11 02:15:33 +00001220 // C++ [over.ics.user]p4:
1221 // A conversion of an expression of class type to the same class
1222 // type is given Exact Match rank, and a conversion of an
1223 // expression of class type to a base class of that type is
1224 // given Conversion rank, in spite of the fact that a copy/move
1225 // constructor (i.e., a user-defined conversion function) is
1226 // called for those cases.
1227 QualType FromType = From->getType();
1228 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001229 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1230 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001231 ICS.setStandard();
1232 ICS.Standard.setAsIdentityConversion();
1233 ICS.Standard.setFromType(FromType);
1234 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001236 // We don't actually check at this point whether there is a valid
1237 // copy/move constructor, since overloading just assumes that it
1238 // exists. When we actually perform initialization, we'll find the
1239 // appropriate constructor to copy the returned object, if needed.
1240 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001241
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001242 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001243 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001244 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001245
Douglas Gregor604eb652010-08-11 02:15:33 +00001246 return ICS;
1247 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001248
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001249 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1250 AllowExplicit, InOverloadResolution, CStyle,
1251 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001252}
1253
John McCallf85e1932011-06-15 23:02:42 +00001254ImplicitConversionSequence
1255Sema::TryImplicitConversion(Expr *From, QualType ToType,
1256 bool SuppressUserConversions,
1257 bool AllowExplicit,
1258 bool InOverloadResolution,
1259 bool CStyle,
1260 bool AllowObjCWritebackConversion) {
1261 return clang::TryImplicitConversion(*this, From, ToType,
1262 SuppressUserConversions, AllowExplicit,
1263 InOverloadResolution, CStyle,
1264 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001265}
1266
Douglas Gregor575c63a2010-04-16 22:27:05 +00001267/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001268/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001269/// converted expression. Flavor is the kind of conversion we're
1270/// performing, used in the error message. If @p AllowExplicit,
1271/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001272ExprResult
1273Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001274 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001275 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001276 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001277}
1278
John Wiegley429bb272011-04-08 18:41:53 +00001279ExprResult
1280Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001281 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001282 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001283 if (checkPlaceholderForOverload(*this, From))
1284 return ExprError();
1285
John McCallf85e1932011-06-15 23:02:42 +00001286 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1287 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001288 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001289 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001290
John McCall120d63c2010-08-24 20:38:10 +00001291 ICS = clang::TryImplicitConversion(*this, From, ToType,
1292 /*SuppressUserConversions=*/false,
1293 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001294 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001295 /*CStyle=*/false,
1296 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001297 return PerformImplicitConversion(From, ToType, ICS, Action);
1298}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001299
1300/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001301/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001302bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1303 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001304 if (Context.hasSameUnqualifiedType(FromType, ToType))
1305 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001306
John McCall00ccbef2010-12-21 00:44:39 +00001307 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1308 // where F adds one of the following at most once:
1309 // - a pointer
1310 // - a member pointer
1311 // - a block pointer
1312 CanQualType CanTo = Context.getCanonicalType(ToType);
1313 CanQualType CanFrom = Context.getCanonicalType(FromType);
1314 Type::TypeClass TyClass = CanTo->getTypeClass();
1315 if (TyClass != CanFrom->getTypeClass()) return false;
1316 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1317 if (TyClass == Type::Pointer) {
1318 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1319 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1320 } else if (TyClass == Type::BlockPointer) {
1321 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1322 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1323 } else if (TyClass == Type::MemberPointer) {
1324 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1325 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1326 } else {
1327 return false;
1328 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001329
John McCall00ccbef2010-12-21 00:44:39 +00001330 TyClass = CanTo->getTypeClass();
1331 if (TyClass != CanFrom->getTypeClass()) return false;
1332 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1333 return false;
1334 }
1335
1336 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1337 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1338 if (!EInfo.getNoReturn()) return false;
1339
1340 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1341 assert(QualType(FromFn, 0).isCanonical());
1342 if (QualType(FromFn, 0) != CanTo) return false;
1343
1344 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001345 return true;
1346}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001348/// \brief Determine whether the conversion from FromType to ToType is a valid
1349/// vector conversion.
1350///
1351/// \param ICK Will be set to the vector conversion kind, if this is a vector
1352/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001353static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1354 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001355 // We need at least one of these types to be a vector type to have a vector
1356 // conversion.
1357 if (!ToType->isVectorType() && !FromType->isVectorType())
1358 return false;
1359
1360 // Identical types require no conversions.
1361 if (Context.hasSameUnqualifiedType(FromType, ToType))
1362 return false;
1363
1364 // There are no conversions between extended vector types, only identity.
1365 if (ToType->isExtVectorType()) {
1366 // There are no conversions between extended vector types other than the
1367 // identity conversion.
1368 if (FromType->isExtVectorType())
1369 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001370
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001371 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001372 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001373 ICK = ICK_Vector_Splat;
1374 return true;
1375 }
1376 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001377
1378 // We can perform the conversion between vector types in the following cases:
1379 // 1)vector types are equivalent AltiVec and GCC vector types
1380 // 2)lax vector conversions are permitted and the vector types are of the
1381 // same size
1382 if (ToType->isVectorType() && FromType->isVectorType()) {
1383 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001384 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001385 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001386 ICK = ICK_Vector_Conversion;
1387 return true;
1388 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001389 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001390
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001391 return false;
1392}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001393
Douglas Gregor7d000652012-04-12 20:48:09 +00001394static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1395 bool InOverloadResolution,
1396 StandardConversionSequence &SCS,
1397 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001398
Douglas Gregor60d62c22008-10-31 16:23:19 +00001399/// IsStandardConversion - Determines whether there is a standard
1400/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1401/// expression From to the type ToType. Standard conversion sequences
1402/// only consider non-class types; for conversions that involve class
1403/// types, use TryImplicitConversion. If a conversion exists, SCS will
1404/// contain the standard conversion sequence required to perform this
1405/// conversion and this routine will return true. Otherwise, this
1406/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001407static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1408 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001409 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001410 bool CStyle,
1411 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001412 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413
Douglas Gregor60d62c22008-10-31 16:23:19 +00001414 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001415 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001416 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001417 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001418 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001419 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001420
Douglas Gregorf9201e02009-02-11 23:02:49 +00001421 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001422 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001423 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001424 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001425 return false;
1426
Mike Stump1eb44332009-09-09 15:08:12 +00001427 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001428 }
1429
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430 // The first conversion can be an lvalue-to-rvalue conversion,
1431 // array-to-pointer conversion, or function-to-pointer conversion
1432 // (C++ 4p1).
1433
John McCall120d63c2010-08-24 20:38:10 +00001434 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001435 DeclAccessPair AccessPair;
1436 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001437 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001438 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001439 // We were able to resolve the address of the overloaded function,
1440 // so we can convert to the type of that function.
1441 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001442
1443 // we can sometimes resolve &foo<int> regardless of ToType, so check
1444 // if the type matches (identity) or we are converting to bool
1445 if (!S.Context.hasSameUnqualifiedType(
1446 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1447 QualType resultTy;
1448 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001449 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001450 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1451 // otherwise, only a boolean conversion is standard
1452 if (!ToType->isBooleanType())
1453 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001454 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001455
Chandler Carruth90434232011-03-29 08:08:18 +00001456 // Check if the "from" expression is taking the address of an overloaded
1457 // function and recompute the FromType accordingly. Take advantage of the
1458 // fact that non-static member functions *must* have such an address-of
1459 // expression.
1460 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1461 if (Method && !Method->isStatic()) {
1462 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1463 "Non-unary operator on non-static member address");
1464 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1465 == UO_AddrOf &&
1466 "Non-address-of operator on non-static member address");
1467 const Type *ClassType
1468 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1469 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001470 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1471 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1472 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001473 "Non-address-of operator for overloaded function expression");
1474 FromType = S.Context.getPointerType(FromType);
1475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001476
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001477 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001478 assert(S.Context.hasSameType(
1479 FromType,
1480 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001481 } else {
1482 return false;
1483 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001484 }
John McCall21480112011-08-30 00:57:29 +00001485 // Lvalue-to-rvalue conversion (C++11 4.1):
1486 // A glvalue (3.10) of a non-function, non-array type T can
1487 // be converted to a prvalue.
1488 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001489 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001490 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001491 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001492 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001493
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001494 // C11 6.3.2.1p2:
1495 // ... if the lvalue has atomic type, the value has the non-atomic version
1496 // of the type of the lvalue ...
1497 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1498 FromType = Atomic->getValueType();
1499
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001500 // If T is a non-class type, the type of the rvalue is the
1501 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001502 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1503 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001504 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001505 } else if (FromType->isArrayType()) {
1506 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001507 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001508
1509 // An lvalue or rvalue of type "array of N T" or "array of unknown
1510 // bound of T" can be converted to an rvalue of type "pointer to
1511 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001512 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001513
John McCall120d63c2010-08-24 20:38:10 +00001514 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001515 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001516 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517
1518 // For the purpose of ranking in overload resolution
1519 // (13.3.3.1.1), this conversion is considered an
1520 // array-to-pointer conversion followed by a qualification
1521 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 SCS.Second = ICK_Identity;
1523 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001524 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001525 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001526 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001528 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001529 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001530 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531
1532 // An lvalue of function type T can be converted to an rvalue of
1533 // type "pointer to T." The result is a pointer to the
1534 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001535 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001536 } else {
1537 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001538 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001540 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001541
1542 // The second conversion can be an integral promotion, floating
1543 // point promotion, integral conversion, floating point conversion,
1544 // floating-integral conversion, pointer conversion,
1545 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001546 // For overloading in C, this can also be a "compatible-type"
1547 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001548 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001549 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001550 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001551 // The unqualified versions of the types are the same: there's no
1552 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001553 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001554 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001555 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001556 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001557 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001558 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001559 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001561 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001562 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001563 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001564 SCS.Second = ICK_Complex_Promotion;
1565 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001566 } else if (ToType->isBooleanType() &&
1567 (FromType->isArithmeticType() ||
1568 FromType->isAnyPointerType() ||
1569 FromType->isBlockPointerType() ||
1570 FromType->isMemberPointerType() ||
1571 FromType->isNullPtrType())) {
1572 // Boolean conversions (C++ 4.12).
1573 SCS.Second = ICK_Boolean_Conversion;
1574 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001575 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001576 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001577 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001578 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001579 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001580 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001581 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001582 SCS.Second = ICK_Complex_Conversion;
1583 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001584 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1585 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001586 // Complex-real conversions (C99 6.3.1.7)
1587 SCS.Second = ICK_Complex_Real;
1588 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001589 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001590 // Floating point conversions (C++ 4.8).
1591 SCS.Second = ICK_Floating_Conversion;
1592 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001593 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001594 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001595 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001596 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001597 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001598 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001599 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001600 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001601 SCS.Second = ICK_Block_Pointer_Conversion;
1602 } else if (AllowObjCWritebackConversion &&
1603 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1604 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001605 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1606 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001607 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001608 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001609 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001610 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001611 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001612 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001613 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001614 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001615 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001616 SCS.Second = SecondICK;
1617 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001618 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001619 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001620 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001621 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001622 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001623 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001624 // Treat a conversion that strips "noreturn" as an identity conversion.
1625 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001626 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1627 InOverloadResolution,
1628 SCS, CStyle)) {
1629 SCS.Second = ICK_TransparentUnionConversion;
1630 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001631 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1632 CStyle)) {
1633 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001634 // appropriately.
1635 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001636 } else if (ToType->isEventT() &&
1637 From->isIntegerConstantExpr(S.getASTContext()) &&
1638 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1639 SCS.Second = ICK_Zero_Event_Conversion;
1640 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001641 } else {
1642 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001643 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001644 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001645 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001646
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001647 QualType CanonFrom;
1648 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001649 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001650 bool ObjCLifetimeConversion;
1651 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1652 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001653 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001654 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001655 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001656 CanonFrom = S.Context.getCanonicalType(FromType);
1657 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001658 } else {
1659 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001660 SCS.Third = ICK_Identity;
1661
Mike Stump1eb44332009-09-09 15:08:12 +00001662 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001663 // [...] Any difference in top-level cv-qualification is
1664 // subsumed by the initialization itself and does not constitute
1665 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001666 CanonFrom = S.Context.getCanonicalType(FromType);
1667 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001669 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001670 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001671 FromType = ToType;
1672 CanonFrom = CanonTo;
1673 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001674 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001675 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676
1677 // If we have not converted the argument type to the parameter type,
1678 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001679 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001680 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001681
Douglas Gregor60d62c22008-10-31 16:23:19 +00001682 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001683}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001684
1685static bool
1686IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1687 QualType &ToType,
1688 bool InOverloadResolution,
1689 StandardConversionSequence &SCS,
1690 bool CStyle) {
1691
1692 const RecordType *UT = ToType->getAsUnionType();
1693 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1694 return false;
1695 // The field to initialize within the transparent union.
1696 RecordDecl *UD = UT->getDecl();
1697 // It's compatible if the expression matches any of the fields.
1698 for (RecordDecl::field_iterator it = UD->field_begin(),
1699 itend = UD->field_end();
1700 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001701 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1702 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001703 ToType = it->getType();
1704 return true;
1705 }
1706 }
1707 return false;
1708}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001709
1710/// IsIntegralPromotion - Determines whether the conversion from the
1711/// expression From (whose potentially-adjusted type is FromType) to
1712/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1713/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001714bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001715 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001716 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001717 if (!To) {
1718 return false;
1719 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001720
1721 // An rvalue of type char, signed char, unsigned char, short int, or
1722 // unsigned short int can be converted to an rvalue of type int if
1723 // int can represent all the values of the source type; otherwise,
1724 // the source rvalue can be converted to an rvalue of type unsigned
1725 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001726 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1727 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001728 if (// We can promote any signed, promotable integer type to an int
1729 (FromType->isSignedIntegerType() ||
1730 // We can promote any unsigned integer type whose size is
1731 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001732 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001733 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001734 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001735 }
1736
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001737 return To->getKind() == BuiltinType::UInt;
1738 }
1739
Richard Smithe7ff9192012-09-13 21:18:54 +00001740 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001741 // A prvalue of an unscoped enumeration type whose underlying type is not
1742 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1743 // following types that can represent all the values of the enumeration
1744 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1745 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001746 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001747 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001748 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001749 // with lowest integer conversion rank (4.13) greater than the rank of long
1750 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001751 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001752 // C++11 [conv.prom]p4:
1753 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1754 // can be converted to a prvalue of its underlying type. Moreover, if
1755 // integral promotion can be applied to its underlying type, a prvalue of an
1756 // unscoped enumeration type whose underlying type is fixed can also be
1757 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001758 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1759 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1760 // provided for a scoped enumeration.
1761 if (FromEnumType->getDecl()->isScoped())
1762 return false;
1763
Richard Smithe7ff9192012-09-13 21:18:54 +00001764 // We can perform an integral promotion to the underlying type of the enum,
1765 // even if that's not the promoted type.
1766 if (FromEnumType->getDecl()->isFixed()) {
1767 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1768 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1769 IsIntegralPromotion(From, Underlying, ToType);
1770 }
1771
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001772 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001773 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001774 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001775 return Context.hasSameUnqualifiedType(ToType,
1776 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001777 }
John McCall842aef82009-12-09 09:09:27 +00001778
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001779 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1781 // to an rvalue a prvalue of the first of the following types that can
1782 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001783 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001785 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001787 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001788 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001789 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001790 // Determine whether the type we're converting from is signed or
1791 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001792 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001793 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001795 // The types we'll try to promote to, in the appropriate
1796 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001797 QualType PromoteTypes[6] = {
1798 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001799 Context.LongTy, Context.UnsignedLongTy ,
1800 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001801 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001802 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001803 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1804 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001805 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001806 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1807 // We found the type that we can promote to. If this is the
1808 // type we wanted, we have a promotion. Otherwise, no
1809 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001810 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001811 }
1812 }
1813 }
1814
1815 // An rvalue for an integral bit-field (9.6) can be converted to an
1816 // rvalue of type int if int can represent all the values of the
1817 // bit-field; otherwise, it can be converted to unsigned int if
1818 // unsigned int can represent all the values of the bit-field. If
1819 // the bit-field is larger yet, no integral promotion applies to
1820 // it. If the bit-field has an enumerated type, it is treated as any
1821 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001822 // FIXME: We should delay checking of bit-fields until we actually perform the
1823 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001824 using llvm::APSInt;
1825 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001826 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001827 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001828 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001829 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1830 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1831 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregor86f19402008-12-20 23:49:58 +00001833 // Are we promoting to an int from a bitfield that fits in an int?
1834 if (BitWidth < ToSize ||
1835 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1836 return To->getKind() == BuiltinType::Int;
1837 }
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor86f19402008-12-20 23:49:58 +00001839 // Are we promoting to an unsigned int from an unsigned bitfield
1840 // that fits into an unsigned int?
1841 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1842 return To->getKind() == BuiltinType::UInt;
1843 }
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregor86f19402008-12-20 23:49:58 +00001845 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001846 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001847 }
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001849 // An rvalue of type bool can be converted to an rvalue of type int,
1850 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001851 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001852 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001853 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001854
1855 return false;
1856}
1857
1858/// IsFloatingPointPromotion - Determines whether the conversion from
1859/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1860/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001861bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001862 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1863 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001864 /// An rvalue of type float can be converted to an rvalue of type
1865 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001866 if (FromBuiltin->getKind() == BuiltinType::Float &&
1867 ToBuiltin->getKind() == BuiltinType::Double)
1868 return true;
1869
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001870 // C99 6.3.1.5p1:
1871 // When a float is promoted to double or long double, or a
1872 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001873 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001874 (FromBuiltin->getKind() == BuiltinType::Float ||
1875 FromBuiltin->getKind() == BuiltinType::Double) &&
1876 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1877 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001878
1879 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001880 if (!getLangOpts().NativeHalfType &&
1881 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001882 ToBuiltin->getKind() == BuiltinType::Float)
1883 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001884 }
1885
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001886 return false;
1887}
1888
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001889/// \brief Determine if a conversion is a complex promotion.
1890///
1891/// A complex promotion is defined as a complex -> complex conversion
1892/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001893/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001894bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001895 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001896 if (!FromComplex)
1897 return false;
1898
John McCall183700f2009-09-21 23:43:11 +00001899 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001900 if (!ToComplex)
1901 return false;
1902
1903 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001904 ToComplex->getElementType()) ||
1905 IsIntegralPromotion(0, FromComplex->getElementType(),
1906 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001907}
1908
Douglas Gregorcb7de522008-11-26 23:31:11 +00001909/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1910/// the pointer type FromPtr to a pointer to type ToPointee, with the
1911/// same type qualifiers as FromPtr has on its pointee type. ToType,
1912/// if non-empty, will be a pointer to ToType that may or may not have
1913/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001914///
Mike Stump1eb44332009-09-09 15:08:12 +00001915static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001916BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001917 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001918 ASTContext &Context,
1919 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001920 assert((FromPtr->getTypeClass() == Type::Pointer ||
1921 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1922 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001923
John McCallf85e1932011-06-15 23:02:42 +00001924 /// Conversions to 'id' subsume cv-qualifier conversions.
1925 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001926 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001927
1928 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001929 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001930 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001931 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001932
John McCallf85e1932011-06-15 23:02:42 +00001933 if (StripObjCLifetime)
1934 Quals.removeObjCLifetime();
1935
Mike Stump1eb44332009-09-09 15:08:12 +00001936 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001937 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001938 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001939 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001940 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001941
1942 // Build a pointer to ToPointee. It has the right qualifiers
1943 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001944 if (isa<ObjCObjectPointerType>(ToType))
1945 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001946 return Context.getPointerType(ToPointee);
1947 }
1948
1949 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001950 QualType QualifiedCanonToPointee
1951 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001952
Douglas Gregorda80f742010-12-01 21:43:58 +00001953 if (isa<ObjCObjectPointerType>(ToType))
1954 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1955 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001956}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001957
Mike Stump1eb44332009-09-09 15:08:12 +00001958static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001959 bool InOverloadResolution,
1960 ASTContext &Context) {
1961 // Handle value-dependent integral null pointer constants correctly.
1962 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1963 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001964 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001965 return !InOverloadResolution;
1966
Douglas Gregorce940492009-09-25 04:25:58 +00001967 return Expr->isNullPointerConstant(Context,
1968 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1969 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001970}
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001972/// IsPointerConversion - Determines whether the conversion of the
1973/// expression From, which has the (possibly adjusted) type FromType,
1974/// can be converted to the type ToType via a pointer conversion (C++
1975/// 4.10). If so, returns true and places the converted type (that
1976/// might differ from ToType in its cv-qualifiers at some level) into
1977/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001978///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001979/// This routine also supports conversions to and from block pointers
1980/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1981/// pointers to interfaces. FIXME: Once we've determined the
1982/// appropriate overloading rules for Objective-C, we may want to
1983/// split the Objective-C checks into a different routine; however,
1984/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001985/// conversions, so for now they live here. IncompatibleObjC will be
1986/// set if the conversion is an allowed Objective-C conversion that
1987/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001988bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001989 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001990 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001991 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001992 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001993 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1994 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001995 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001996
Mike Stump1eb44332009-09-09 15:08:12 +00001997 // Conversion from a null pointer constant to any Objective-C pointer type.
1998 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002000 ConvertedType = ToType;
2001 return true;
2002 }
2003
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002004 // Blocks: Block pointers can be converted to void*.
2005 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002006 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002007 ConvertedType = ToType;
2008 return true;
2009 }
2010 // Blocks: A null pointer constant can be converted to a block
2011 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002012 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002014 ConvertedType = ToType;
2015 return true;
2016 }
2017
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002018 // If the left-hand-side is nullptr_t, the right side can be a null
2019 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002020 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002022 ConvertedType = ToType;
2023 return true;
2024 }
2025
Ted Kremenek6217b802009-07-29 21:53:49 +00002026 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002027 if (!ToTypePtr)
2028 return false;
2029
2030 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002031 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002032 ConvertedType = ToType;
2033 return true;
2034 }
Sebastian Redl07779722008-10-31 14:43:28 +00002035
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002036 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002037 // , including objective-c pointers.
2038 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002039 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002040 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002041 ConvertedType = BuildSimilarlyQualifiedPointerType(
2042 FromType->getAs<ObjCObjectPointerType>(),
2043 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002044 ToType, Context);
2045 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002046 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002047 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002048 if (!FromTypePtr)
2049 return false;
2050
2051 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002052
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002053 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002054 // pointer conversion, so don't do all of the work below.
2055 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2056 return false;
2057
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002058 // An rvalue of type "pointer to cv T," where T is an object type,
2059 // can be converted to an rvalue of type "pointer to cv void" (C++
2060 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002061 if (FromPointeeType->isIncompleteOrObjectType() &&
2062 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002064 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002065 ToType, Context,
2066 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002067 return true;
2068 }
2069
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002070 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002071 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002072 ToPointeeType->isVoidType()) {
2073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2074 ToPointeeType,
2075 ToType, Context);
2076 return true;
2077 }
2078
Douglas Gregorf9201e02009-02-11 23:02:49 +00002079 // When we're overloading in C, we allow a special kind of pointer
2080 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002081 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002082 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002083 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002084 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002085 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002086 return true;
2087 }
2088
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002089 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002090 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002091 // An rvalue of type "pointer to cv D," where D is a class type,
2092 // can be converted to an rvalue of type "pointer to cv B," where
2093 // B is a base class (clause 10) of D. If B is an inaccessible
2094 // (clause 11) or ambiguous (10.2) base class of D, a program that
2095 // necessitates this conversion is ill-formed. The result of the
2096 // conversion is a pointer to the base class sub-object of the
2097 // derived class object. The null pointer value is converted to
2098 // the null pointer value of the destination type.
2099 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002100 // Note that we do not check for ambiguity or inaccessibility
2101 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002102 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002103 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002104 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002105 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002106 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002108 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002109 ToType, Context);
2110 return true;
2111 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002112
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002113 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2114 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2116 ToPointeeType,
2117 ToType, Context);
2118 return true;
2119 }
2120
Douglas Gregorc7887512008-12-19 19:13:09 +00002121 return false;
2122}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002123
2124/// \brief Adopt the given qualifiers for the given type.
2125static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2126 Qualifiers TQs = T.getQualifiers();
2127
2128 // Check whether qualifiers already match.
2129 if (TQs == Qs)
2130 return T;
2131
2132 if (Qs.compatiblyIncludes(TQs))
2133 return Context.getQualifiedType(T, Qs);
2134
2135 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2136}
Douglas Gregorc7887512008-12-19 19:13:09 +00002137
2138/// isObjCPointerConversion - Determines whether this is an
2139/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2140/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002141bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002142 QualType& ConvertedType,
2143 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002144 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002145 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002147 // The set of qualifiers on the type we're converting from.
2148 Qualifiers FromQualifiers = FromType.getQualifiers();
2149
Steve Naroff14108da2009-07-10 23:34:53 +00002150 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002151 const ObjCObjectPointerType* ToObjCPtr =
2152 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002153 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002154 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002155
Steve Naroff14108da2009-07-10 23:34:53 +00002156 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002157 // If the pointee types are the same (ignoring qualifications),
2158 // then this is not a pointer conversion.
2159 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2160 FromObjCPtr->getPointeeType()))
2161 return false;
2162
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002163 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002164 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002165 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002166 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002167 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002168 return true;
2169 }
2170 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002171 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002172 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002173 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002174 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002175 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002176 return true;
2177 }
2178 // Objective C++: We're able to convert from a pointer to an
2179 // interface to a pointer to a different interface.
2180 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002181 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2182 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002183 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002184 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2185 FromObjCPtr->getPointeeType()))
2186 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002187 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002188 ToObjCPtr->getPointeeType(),
2189 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002190 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002191 return true;
2192 }
2193
2194 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2195 // Okay: this is some kind of implicit downcast of Objective-C
2196 // interfaces, which is permitted. However, we're going to
2197 // complain about it.
2198 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002200 ToObjCPtr->getPointeeType(),
2201 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002203 return true;
2204 }
Mike Stump1eb44332009-09-09 15:08:12 +00002205 }
Steve Naroff14108da2009-07-10 23:34:53 +00002206 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002207 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002208 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002209 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002210 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002211 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002212 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002213 // to a block pointer type.
2214 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002215 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002216 return true;
2217 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002218 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002220 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002221 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002222 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002223 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002224 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002225 return true;
2226 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002227 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002228 return false;
2229
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002230 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002231 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002232 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002233 else if (const BlockPointerType *FromBlockPtr =
2234 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002235 FromPointeeType = FromBlockPtr->getPointeeType();
2236 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002237 return false;
2238
Douglas Gregorc7887512008-12-19 19:13:09 +00002239 // If we have pointers to pointers, recursively check whether this
2240 // is an Objective-C conversion.
2241 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2242 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2243 IncompatibleObjC)) {
2244 // We always complain about this conversion.
2245 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002246 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002247 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002248 return true;
2249 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002250 // Allow conversion of pointee being objective-c pointer to another one;
2251 // as in I* to id.
2252 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2253 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2255 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002256
Douglas Gregorda80f742010-12-01 21:43:58 +00002257 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002259 return true;
2260 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002261
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002262 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002263 // differences in the argument and result types are in Objective-C
2264 // pointer conversions. If so, we permit the conversion (but
2265 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002266 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002267 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002268 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002269 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002270 if (FromFunctionType && ToFunctionType) {
2271 // If the function types are exactly the same, this isn't an
2272 // Objective-C pointer conversion.
2273 if (Context.getCanonicalType(FromPointeeType)
2274 == Context.getCanonicalType(ToPointeeType))
2275 return false;
2276
2277 // Perform the quick checks that will tell us whether these
2278 // function types are obviously different.
2279 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2280 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2281 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2282 return false;
2283
2284 bool HasObjCConversion = false;
2285 if (Context.getCanonicalType(FromFunctionType->getResultType())
2286 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2287 // Okay, the types match exactly. Nothing to do.
2288 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2289 ToFunctionType->getResultType(),
2290 ConvertedType, IncompatibleObjC)) {
2291 // Okay, we have an Objective-C pointer conversion.
2292 HasObjCConversion = true;
2293 } else {
2294 // Function types are too different. Abort.
2295 return false;
2296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Douglas Gregorc7887512008-12-19 19:13:09 +00002298 // Check argument types.
2299 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2300 ArgIdx != NumArgs; ++ArgIdx) {
2301 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2302 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2303 if (Context.getCanonicalType(FromArgType)
2304 == Context.getCanonicalType(ToArgType)) {
2305 // Okay, the types match exactly. Nothing to do.
2306 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2307 ConvertedType, IncompatibleObjC)) {
2308 // Okay, we have an Objective-C pointer conversion.
2309 HasObjCConversion = true;
2310 } else {
2311 // Argument types are too different. Abort.
2312 return false;
2313 }
2314 }
2315
2316 if (HasObjCConversion) {
2317 // We had an Objective-C conversion. Allow this pointer
2318 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002319 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002320 IncompatibleObjC = true;
2321 return true;
2322 }
2323 }
2324
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002325 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002326}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002327
John McCallf85e1932011-06-15 23:02:42 +00002328/// \brief Determine whether this is an Objective-C writeback conversion,
2329/// used for parameter passing when performing automatic reference counting.
2330///
2331/// \param FromType The type we're converting form.
2332///
2333/// \param ToType The type we're converting to.
2334///
2335/// \param ConvertedType The type that will be produced after applying
2336/// this conversion.
2337bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2338 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002339 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002340 Context.hasSameUnqualifiedType(FromType, ToType))
2341 return false;
2342
2343 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2344 QualType ToPointee;
2345 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2346 ToPointee = ToPointer->getPointeeType();
2347 else
2348 return false;
2349
2350 Qualifiers ToQuals = ToPointee.getQualifiers();
2351 if (!ToPointee->isObjCLifetimeType() ||
2352 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002353 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002354 return false;
2355
2356 // Argument must be a pointer to __strong to __weak.
2357 QualType FromPointee;
2358 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2359 FromPointee = FromPointer->getPointeeType();
2360 else
2361 return false;
2362
2363 Qualifiers FromQuals = FromPointee.getQualifiers();
2364 if (!FromPointee->isObjCLifetimeType() ||
2365 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2366 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2367 return false;
2368
2369 // Make sure that we have compatible qualifiers.
2370 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2371 if (!ToQuals.compatiblyIncludes(FromQuals))
2372 return false;
2373
2374 // Remove qualifiers from the pointee type we're converting from; they
2375 // aren't used in the compatibility check belong, and we'll be adding back
2376 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2377 FromPointee = FromPointee.getUnqualifiedType();
2378
2379 // The unqualified form of the pointee types must be compatible.
2380 ToPointee = ToPointee.getUnqualifiedType();
2381 bool IncompatibleObjC;
2382 if (Context.typesAreCompatible(FromPointee, ToPointee))
2383 FromPointee = ToPointee;
2384 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2385 IncompatibleObjC))
2386 return false;
2387
2388 /// \brief Construct the type we're converting to, which is a pointer to
2389 /// __autoreleasing pointee.
2390 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2391 ConvertedType = Context.getPointerType(FromPointee);
2392 return true;
2393}
2394
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002395bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2396 QualType& ConvertedType) {
2397 QualType ToPointeeType;
2398 if (const BlockPointerType *ToBlockPtr =
2399 ToType->getAs<BlockPointerType>())
2400 ToPointeeType = ToBlockPtr->getPointeeType();
2401 else
2402 return false;
2403
2404 QualType FromPointeeType;
2405 if (const BlockPointerType *FromBlockPtr =
2406 FromType->getAs<BlockPointerType>())
2407 FromPointeeType = FromBlockPtr->getPointeeType();
2408 else
2409 return false;
2410 // We have pointer to blocks, check whether the only
2411 // differences in the argument and result types are in Objective-C
2412 // pointer conversions. If so, we permit the conversion.
2413
2414 const FunctionProtoType *FromFunctionType
2415 = FromPointeeType->getAs<FunctionProtoType>();
2416 const FunctionProtoType *ToFunctionType
2417 = ToPointeeType->getAs<FunctionProtoType>();
2418
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002419 if (!FromFunctionType || !ToFunctionType)
2420 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002421
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002422 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002423 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002424
2425 // Perform the quick checks that will tell us whether these
2426 // function types are obviously different.
2427 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2428 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2429 return false;
2430
2431 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2432 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2433 if (FromEInfo != ToEInfo)
2434 return false;
2435
2436 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002437 if (Context.hasSameType(FromFunctionType->getResultType(),
2438 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002439 // Okay, the types match exactly. Nothing to do.
2440 } else {
2441 QualType RHS = FromFunctionType->getResultType();
2442 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002443 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002444 !RHS.hasQualifiers() && LHS.hasQualifiers())
2445 LHS = LHS.getUnqualifiedType();
2446
2447 if (Context.hasSameType(RHS,LHS)) {
2448 // OK exact match.
2449 } else if (isObjCPointerConversion(RHS, LHS,
2450 ConvertedType, IncompatibleObjC)) {
2451 if (IncompatibleObjC)
2452 return false;
2453 // Okay, we have an Objective-C pointer conversion.
2454 }
2455 else
2456 return false;
2457 }
2458
2459 // Check argument types.
2460 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2461 ArgIdx != NumArgs; ++ArgIdx) {
2462 IncompatibleObjC = false;
2463 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2464 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2465 if (Context.hasSameType(FromArgType, ToArgType)) {
2466 // Okay, the types match exactly. Nothing to do.
2467 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2468 ConvertedType, IncompatibleObjC)) {
2469 if (IncompatibleObjC)
2470 return false;
2471 // Okay, we have an Objective-C pointer conversion.
2472 } else
2473 // Argument types are too different. Abort.
2474 return false;
2475 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002476 if (LangOpts.ObjCAutoRefCount &&
2477 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2478 ToFunctionType))
2479 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002480
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002481 ConvertedType = ToType;
2482 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002483}
2484
Richard Trieu6efd4c52011-11-23 22:32:32 +00002485enum {
2486 ft_default,
2487 ft_different_class,
2488 ft_parameter_arity,
2489 ft_parameter_mismatch,
2490 ft_return_type,
2491 ft_qualifer_mismatch
2492};
2493
2494/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2495/// function types. Catches different number of parameter, mismatch in
2496/// parameter types, and different return types.
2497void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2498 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002499 // If either type is not valid, include no extra info.
2500 if (FromType.isNull() || ToType.isNull()) {
2501 PDiag << ft_default;
2502 return;
2503 }
2504
Richard Trieu6efd4c52011-11-23 22:32:32 +00002505 // Get the function type from the pointers.
2506 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2507 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2508 *ToMember = ToType->getAs<MemberPointerType>();
2509 if (FromMember->getClass() != ToMember->getClass()) {
2510 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2511 << QualType(FromMember->getClass(), 0);
2512 return;
2513 }
2514 FromType = FromMember->getPointeeType();
2515 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002516 }
2517
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002518 if (FromType->isPointerType())
2519 FromType = FromType->getPointeeType();
2520 if (ToType->isPointerType())
2521 ToType = ToType->getPointeeType();
2522
2523 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002524 FromType = FromType.getNonReferenceType();
2525 ToType = ToType.getNonReferenceType();
2526
Richard Trieu6efd4c52011-11-23 22:32:32 +00002527 // Don't print extra info for non-specialized template functions.
2528 if (FromType->isInstantiationDependentType() &&
2529 !FromType->getAs<TemplateSpecializationType>()) {
2530 PDiag << ft_default;
2531 return;
2532 }
2533
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002534 // No extra info for same types.
2535 if (Context.hasSameType(FromType, ToType)) {
2536 PDiag << ft_default;
2537 return;
2538 }
2539
Richard Trieu6efd4c52011-11-23 22:32:32 +00002540 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2541 *ToFunction = ToType->getAs<FunctionProtoType>();
2542
2543 // Both types need to be function types.
2544 if (!FromFunction || !ToFunction) {
2545 PDiag << ft_default;
2546 return;
2547 }
2548
2549 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2550 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2551 << FromFunction->getNumArgs();
2552 return;
2553 }
2554
2555 // Handle different parameter types.
2556 unsigned ArgPos;
2557 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2558 PDiag << ft_parameter_mismatch << ArgPos + 1
2559 << ToFunction->getArgType(ArgPos)
2560 << FromFunction->getArgType(ArgPos);
2561 return;
2562 }
2563
2564 // Handle different return type.
2565 if (!Context.hasSameType(FromFunction->getResultType(),
2566 ToFunction->getResultType())) {
2567 PDiag << ft_return_type << ToFunction->getResultType()
2568 << FromFunction->getResultType();
2569 return;
2570 }
2571
2572 unsigned FromQuals = FromFunction->getTypeQuals(),
2573 ToQuals = ToFunction->getTypeQuals();
2574 if (FromQuals != ToQuals) {
2575 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2576 return;
2577 }
2578
2579 // Unable to find a difference, so add no extra info.
2580 PDiag << ft_default;
2581}
2582
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002583/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002584/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002585/// they have same number of arguments. If the parameters are different,
2586/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002587bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002588 const FunctionProtoType *NewType,
2589 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002590 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2591 N = NewType->arg_type_begin(),
2592 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Eli Friedman06017002013-06-18 22:41:37 +00002593 if (!Context.hasSameType(*O, *N)) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002594 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002596 }
2597 }
2598 return true;
2599}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002600
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002601/// CheckPointerConversion - Check the pointer conversion from the
2602/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002603/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002604/// conversions for which IsPointerConversion has already returned
2605/// true. It returns true and produces a diagnostic if there was an
2606/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002607bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002608 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002609 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002610 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002611 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002612 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002613
John McCalldaa8e4e2010-11-15 09:13:47 +00002614 Kind = CK_BitCast;
2615
David Blaikie50800fc2012-08-08 17:33:31 +00002616 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2617 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2618 Expr::NPCK_ZeroExpression) {
2619 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2620 DiagRuntimeBehavior(From->getExprLoc(), From,
2621 PDiag(diag::warn_impcast_bool_to_null_pointer)
2622 << ToType << From->getSourceRange());
2623 else if (!isUnevaluatedContext())
2624 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2625 << ToType << From->getSourceRange();
2626 }
John McCall1d9b3b22011-09-09 05:25:32 +00002627 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2628 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002629 QualType FromPointeeType = FromPtrType->getPointeeType(),
2630 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002631
Douglas Gregor5fccd362010-03-03 23:55:11 +00002632 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2633 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002634 // We must have a derived-to-base conversion. Check an
2635 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002636 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2637 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002638 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002639 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002640 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002641
Anders Carlsson61faec12009-09-12 04:46:44 +00002642 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002643 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002644 }
2645 }
John McCall1d9b3b22011-09-09 05:25:32 +00002646 } else if (const ObjCObjectPointerType *ToPtrType =
2647 ToType->getAs<ObjCObjectPointerType>()) {
2648 if (const ObjCObjectPointerType *FromPtrType =
2649 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002650 // Objective-C++ conversions are always okay.
2651 // FIXME: We should have a different class of conversions for the
2652 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002653 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002654 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002655 } else if (FromType->isBlockPointerType()) {
2656 Kind = CK_BlockPointerToObjCPointerCast;
2657 } else {
2658 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002659 }
John McCall1d9b3b22011-09-09 05:25:32 +00002660 } else if (ToType->isBlockPointerType()) {
2661 if (!FromType->isBlockPointerType())
2662 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002663 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002664
2665 // We shouldn't fall into this case unless it's valid for other
2666 // reasons.
2667 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2668 Kind = CK_NullToPointer;
2669
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002670 return false;
2671}
2672
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002673/// IsMemberPointerConversion - Determines whether the conversion of the
2674/// expression From, which has the (possibly adjusted) type FromType, can be
2675/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2676/// If so, returns true and places the converted type (that might differ from
2677/// ToType in its cv-qualifiers at some level) into ConvertedType.
2678bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002679 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002680 bool InOverloadResolution,
2681 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002682 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002683 if (!ToTypePtr)
2684 return false;
2685
2686 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002687 if (From->isNullPointerConstant(Context,
2688 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2689 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002690 ConvertedType = ToType;
2691 return true;
2692 }
2693
2694 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002695 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002696 if (!FromTypePtr)
2697 return false;
2698
2699 // A pointer to member of B can be converted to a pointer to member of D,
2700 // where D is derived from B (C++ 4.11p2).
2701 QualType FromClass(FromTypePtr->getClass(), 0);
2702 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002703
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002704 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002705 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002706 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002707 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2708 ToClass.getTypePtr());
2709 return true;
2710 }
2711
2712 return false;
2713}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002714
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002715/// CheckMemberPointerConversion - Check the member pointer conversion from the
2716/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002717/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002718/// for which IsMemberPointerConversion has already returned true. It returns
2719/// true and produces a diagnostic if there was an error, or returns false
2720/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002721bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002722 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002723 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002724 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002725 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002726 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002727 if (!FromPtrType) {
2728 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002729 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002730 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002731 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002732 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002733 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002734 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002735
Ted Kremenek6217b802009-07-29 21:53:49 +00002736 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002737 assert(ToPtrType && "No member pointer cast has a target type "
2738 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002739
Sebastian Redl21593ac2009-01-28 18:33:18 +00002740 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2741 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002742
Sebastian Redl21593ac2009-01-28 18:33:18 +00002743 // FIXME: What about dependent types?
2744 assert(FromClass->isRecordType() && "Pointer into non-class.");
2745 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002746
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002747 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002748 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002749 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2750 assert(DerivationOkay &&
2751 "Should not have been called if derivation isn't OK.");
2752 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002753
Sebastian Redl21593ac2009-01-28 18:33:18 +00002754 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2755 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002756 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2757 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2758 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2759 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002760 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002761
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002762 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002763 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2764 << FromClass << ToClass << QualType(VBase, 0)
2765 << From->getSourceRange();
2766 return true;
2767 }
2768
John McCall6b2accb2010-02-10 09:31:12 +00002769 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002770 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2771 Paths.front(),
2772 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002773
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002774 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002775 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002776 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002777 return false;
2778}
2779
Douglas Gregor98cd5992008-10-21 23:43:52 +00002780/// IsQualificationConversion - Determines whether the conversion from
2781/// an rvalue of type FromType to ToType is a qualification conversion
2782/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002783///
2784/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2785/// when the qualification conversion involves a change in the Objective-C
2786/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002787bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002788Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002789 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002790 FromType = Context.getCanonicalType(FromType);
2791 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002792 ObjCLifetimeConversion = false;
2793
Douglas Gregor98cd5992008-10-21 23:43:52 +00002794 // If FromType and ToType are the same type, this is not a
2795 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002796 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002797 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002798
Douglas Gregor98cd5992008-10-21 23:43:52 +00002799 // (C++ 4.4p4):
2800 // A conversion can add cv-qualifiers at levels other than the first
2801 // in multi-level pointers, subject to the following rules: [...]
2802 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002803 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002804 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002805 // Within each iteration of the loop, we check the qualifiers to
2806 // determine if this still looks like a qualification
2807 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002808 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002809 // until there are no more pointers or pointers-to-members left to
2810 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002811 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002812
Douglas Gregor621c92a2011-04-25 18:40:17 +00002813 Qualifiers FromQuals = FromType.getQualifiers();
2814 Qualifiers ToQuals = ToType.getQualifiers();
2815
John McCallf85e1932011-06-15 23:02:42 +00002816 // Objective-C ARC:
2817 // Check Objective-C lifetime conversions.
2818 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2819 UnwrappedAnyPointer) {
2820 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2821 ObjCLifetimeConversion = true;
2822 FromQuals.removeObjCLifetime();
2823 ToQuals.removeObjCLifetime();
2824 } else {
2825 // Qualification conversions cannot cast between different
2826 // Objective-C lifetime qualifiers.
2827 return false;
2828 }
2829 }
2830
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002831 // Allow addition/removal of GC attributes but not changing GC attributes.
2832 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2833 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2834 FromQuals.removeObjCGCAttr();
2835 ToQuals.removeObjCGCAttr();
2836 }
2837
Douglas Gregor98cd5992008-10-21 23:43:52 +00002838 // -- for every j > 0, if const is in cv 1,j then const is in cv
2839 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002840 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002841 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Douglas Gregor98cd5992008-10-21 23:43:52 +00002843 // -- if the cv 1,j and cv 2,j are different, then const is in
2844 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002845 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002846 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002847 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Douglas Gregor98cd5992008-10-21 23:43:52 +00002849 // Keep track of whether all prior cv-qualifiers in the "to" type
2850 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002851 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002852 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002853 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002854
2855 // We are left with FromType and ToType being the pointee types
2856 // after unwrapping the original FromType and ToType the same number
2857 // of types. If we unwrapped any pointers, and if FromType and
2858 // ToType have the same unqualified type (since we checked
2859 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002860 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002861}
2862
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002863/// \brief - Determine whether this is a conversion from a scalar type to an
2864/// atomic type.
2865///
2866/// If successful, updates \c SCS's second and third steps in the conversion
2867/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002868static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2869 bool InOverloadResolution,
2870 StandardConversionSequence &SCS,
2871 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002872 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2873 if (!ToAtomic)
2874 return false;
2875
2876 StandardConversionSequence InnerSCS;
2877 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2878 InOverloadResolution, InnerSCS,
2879 CStyle, /*AllowObjCWritebackConversion=*/false))
2880 return false;
2881
2882 SCS.Second = InnerSCS.Second;
2883 SCS.setToType(1, InnerSCS.getToType(1));
2884 SCS.Third = InnerSCS.Third;
2885 SCS.QualificationIncludesObjCLifetime
2886 = InnerSCS.QualificationIncludesObjCLifetime;
2887 SCS.setToType(2, InnerSCS.getToType(2));
2888 return true;
2889}
2890
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002891static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2892 CXXConstructorDecl *Constructor,
2893 QualType Type) {
2894 const FunctionProtoType *CtorType =
2895 Constructor->getType()->getAs<FunctionProtoType>();
2896 if (CtorType->getNumArgs() > 0) {
2897 QualType FirstArg = CtorType->getArgType(0);
2898 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2899 return true;
2900 }
2901 return false;
2902}
2903
Sebastian Redl56a04282012-02-11 23:51:08 +00002904static OverloadingResult
2905IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2906 CXXRecordDecl *To,
2907 UserDefinedConversionSequence &User,
2908 OverloadCandidateSet &CandidateSet,
2909 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002910 DeclContext::lookup_result R = S.LookupConstructors(To);
2911 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002912 Con != ConEnd; ++Con) {
2913 NamedDecl *D = *Con;
2914 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2915
2916 // Find the constructor (which may be a template).
2917 CXXConstructorDecl *Constructor = 0;
2918 FunctionTemplateDecl *ConstructorTmpl
2919 = dyn_cast<FunctionTemplateDecl>(D);
2920 if (ConstructorTmpl)
2921 Constructor
2922 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2923 else
2924 Constructor = cast<CXXConstructorDecl>(D);
2925
2926 bool Usable = !Constructor->isInvalidDecl() &&
2927 S.isInitListConstructor(Constructor) &&
2928 (AllowExplicit || !Constructor->isExplicit());
2929 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002930 // If the first argument is (a reference to) the target type,
2931 // suppress conversions.
2932 bool SuppressUserConversions =
2933 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002934 if (ConstructorTmpl)
2935 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2936 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002937 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002938 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002939 else
2940 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002941 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002942 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002943 }
2944 }
2945
2946 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2947
2948 OverloadCandidateSet::iterator Best;
2949 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2950 case OR_Success: {
2951 // Record the standard conversion we used and the conversion function.
2952 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002953 QualType ThisType = Constructor->getThisType(S.Context);
2954 // Initializer lists don't have conversions as such.
2955 User.Before.setAsIdentityConversion();
2956 User.HadMultipleCandidates = HadMultipleCandidates;
2957 User.ConversionFunction = Constructor;
2958 User.FoundConversionFunction = Best->FoundDecl;
2959 User.After.setAsIdentityConversion();
2960 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2961 User.After.setAllToTypes(ToType);
2962 return OR_Success;
2963 }
2964
2965 case OR_No_Viable_Function:
2966 return OR_No_Viable_Function;
2967 case OR_Deleted:
2968 return OR_Deleted;
2969 case OR_Ambiguous:
2970 return OR_Ambiguous;
2971 }
2972
2973 llvm_unreachable("Invalid OverloadResult!");
2974}
2975
Douglas Gregor734d9862009-01-30 23:27:23 +00002976/// Determines whether there is a user-defined conversion sequence
2977/// (C++ [over.ics.user]) that converts expression From to the type
2978/// ToType. If such a conversion exists, User will contain the
2979/// user-defined conversion sequence that performs such a conversion
2980/// and this routine will return true. Otherwise, this routine returns
2981/// false and User is unspecified.
2982///
Douglas Gregor734d9862009-01-30 23:27:23 +00002983/// \param AllowExplicit true if the conversion should consider C++0x
2984/// "explicit" conversion functions as well as non-explicit conversion
2985/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002986static OverloadingResult
2987IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002988 UserDefinedConversionSequence &User,
2989 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002990 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002991 // Whether we will only visit constructors.
2992 bool ConstructorsOnly = false;
2993
2994 // If the type we are conversion to is a class type, enumerate its
2995 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002996 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002997 // C++ [over.match.ctor]p1:
2998 // When objects of class type are direct-initialized (8.5), or
2999 // copy-initialized from an expression of the same or a
3000 // derived class type (8.5), overload resolution selects the
3001 // constructor. [...] For copy-initialization, the candidate
3002 // functions are all the converting constructors (12.3.1) of
3003 // that class. The argument list is the expression-list within
3004 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003005 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003006 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003007 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003008 ConstructorsOnly = true;
3009
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003010 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003011 // RequireCompleteType may have returned true due to some invalid decl
3012 // during template instantiation, but ToType may be complete enough now
3013 // to try to recover.
3014 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003015 // We're not going to find any constructors.
3016 } else if (CXXRecordDecl *ToRecordDecl
3017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003018
3019 Expr **Args = &From;
3020 unsigned NumArgs = 1;
3021 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003022 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003023 // But first, see if there is an init-list-contructor that will work.
3024 OverloadingResult Result = IsInitializerListConstructorConversion(
3025 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3026 if (Result != OR_No_Viable_Function)
3027 return Result;
3028 // Never mind.
3029 CandidateSet.clear();
3030
3031 // If we're list-initializing, we pass the individual elements as
3032 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003033 Args = InitList->getInits();
3034 NumArgs = InitList->getNumInits();
3035 ListInitializing = true;
3036 }
3037
David Blaikie3bc93e32012-12-19 00:45:41 +00003038 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3039 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003040 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003041 NamedDecl *D = *Con;
3042 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3043
Douglas Gregordec06662009-08-21 18:42:58 +00003044 // Find the constructor (which may be a template).
3045 CXXConstructorDecl *Constructor = 0;
3046 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003047 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003048 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003049 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003050 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3051 else
John McCall9aa472c2010-03-19 07:35:19 +00003052 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003053
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003054 bool Usable = !Constructor->isInvalidDecl();
3055 if (ListInitializing)
3056 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3057 else
3058 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3059 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003060 bool SuppressUserConversions = !ConstructorsOnly;
3061 if (SuppressUserConversions && ListInitializing) {
3062 SuppressUserConversions = false;
3063 if (NumArgs == 1) {
3064 // If the first argument is (a reference to) the target type,
3065 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003066 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3067 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003068 }
3069 }
Douglas Gregordec06662009-08-21 18:42:58 +00003070 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003071 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3072 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003073 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003074 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003075 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003076 // Allow one user-defined conversion when user specifies a
3077 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003078 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003079 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003080 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003081 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003082 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003083 }
3084 }
3085
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003086 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003087 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003088 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003089 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003090 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003091 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003092 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003093 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3094 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003095 std::pair<CXXRecordDecl::conversion_iterator,
3096 CXXRecordDecl::conversion_iterator>
3097 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3098 for (CXXRecordDecl::conversion_iterator
3099 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003100 DeclAccessPair FoundDecl = I.getPair();
3101 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003102 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3103 if (isa<UsingShadowDecl>(D))
3104 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3105
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003106 CXXConversionDecl *Conv;
3107 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003108 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3109 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003110 else
John McCall32daa422010-03-31 01:36:47 +00003111 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003112
3113 if (AllowExplicit || !Conv->isExplicit()) {
3114 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003115 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3116 ActingContext, From, ToType,
3117 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003118 else
John McCall120d63c2010-08-24 20:38:10 +00003119 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3120 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003121 }
3122 }
3123 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003124 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003125
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003126 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3127
Douglas Gregor60d62c22008-10-31 16:23:19 +00003128 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003129 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003130 case OR_Success:
3131 // Record the standard conversion we used and the conversion function.
3132 if (CXXConstructorDecl *Constructor
3133 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3134 // C++ [over.ics.user]p1:
3135 // If the user-defined conversion is specified by a
3136 // constructor (12.3.1), the initial standard conversion
3137 // sequence converts the source type to the type required by
3138 // the argument of the constructor.
3139 //
3140 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003141 if (isa<InitListExpr>(From)) {
3142 // Initializer lists don't have conversions as such.
3143 User.Before.setAsIdentityConversion();
3144 } else {
3145 if (Best->Conversions[0].isEllipsis())
3146 User.EllipsisConversion = true;
3147 else {
3148 User.Before = Best->Conversions[0].Standard;
3149 User.EllipsisConversion = false;
3150 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003151 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003152 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003153 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003154 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003155 User.After.setAsIdentityConversion();
3156 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3157 User.After.setAllToTypes(ToType);
3158 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003159 }
3160 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003161 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3162 // C++ [over.ics.user]p1:
3163 //
3164 // [...] If the user-defined conversion is specified by a
3165 // conversion function (12.3.2), the initial standard
3166 // conversion sequence converts the source type to the
3167 // implicit object parameter of the conversion function.
3168 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003169 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003170 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003171 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003172 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003173
John McCall120d63c2010-08-24 20:38:10 +00003174 // C++ [over.ics.user]p2:
3175 // The second standard conversion sequence converts the
3176 // result of the user-defined conversion to the target type
3177 // for the sequence. Since an implicit conversion sequence
3178 // is an initialization, the special rules for
3179 // initialization by user-defined conversion apply when
3180 // selecting the best user-defined conversion for a
3181 // user-defined conversion sequence (see 13.3.3 and
3182 // 13.3.3.1).
3183 User.After = Best->FinalConversion;
3184 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003185 }
David Blaikie7530c032012-01-17 06:56:22 +00003186 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003187
John McCall120d63c2010-08-24 20:38:10 +00003188 case OR_No_Viable_Function:
3189 return OR_No_Viable_Function;
3190 case OR_Deleted:
3191 // No conversion here! We're done.
3192 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193
John McCall120d63c2010-08-24 20:38:10 +00003194 case OR_Ambiguous:
3195 return OR_Ambiguous;
3196 }
3197
David Blaikie7530c032012-01-17 06:56:22 +00003198 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003199}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003200
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003201bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003202Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003203 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003204 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003205 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003206 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003207 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003208 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003209 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003210 diag::err_typecheck_ambiguous_condition)
3211 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo7419d012013-06-27 01:50:25 +00003212 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo288f76a2013-06-27 03:36:30 +00003213 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo7419d012013-06-27 01:50:25 +00003214 diag::err_typecheck_nonviable_condition_incomplete,
3215 From->getType(), From->getSourceRange()))
3216 Diag(From->getLocStart(),
3217 diag::err_typecheck_nonviable_condition)
3218 << From->getType() << From->getSourceRange() << ToType;
3219 }
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003220 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003221 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003222 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003224}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003225
Douglas Gregorb734e242012-02-22 17:32:19 +00003226/// \brief Compare the user-defined conversion functions or constructors
3227/// of two user-defined conversion sequences to determine whether any ordering
3228/// is possible.
3229static ImplicitConversionSequence::CompareKind
3230compareConversionFunctions(Sema &S,
3231 FunctionDecl *Function1,
3232 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003233 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003234 return ImplicitConversionSequence::Indistinguishable;
3235
3236 // Objective-C++:
3237 // If both conversion functions are implicitly-declared conversions from
3238 // a lambda closure type to a function pointer and a block pointer,
3239 // respectively, always prefer the conversion to a function pointer,
3240 // because the function pointer is more lightweight and is more likely
3241 // to keep code working.
3242 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3243 if (!Conv1)
3244 return ImplicitConversionSequence::Indistinguishable;
3245
3246 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3247 if (!Conv2)
3248 return ImplicitConversionSequence::Indistinguishable;
3249
3250 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3251 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3252 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3253 if (Block1 != Block2)
3254 return Block1? ImplicitConversionSequence::Worse
3255 : ImplicitConversionSequence::Better;
3256 }
3257
3258 return ImplicitConversionSequence::Indistinguishable;
3259}
3260
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003261/// CompareImplicitConversionSequences - Compare two implicit
3262/// conversion sequences to determine whether one is better than the
3263/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003264static ImplicitConversionSequence::CompareKind
3265CompareImplicitConversionSequences(Sema &S,
3266 const ImplicitConversionSequence& ICS1,
3267 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003268{
3269 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3270 // conversion sequences (as defined in 13.3.3.1)
3271 // -- a standard conversion sequence (13.3.3.1.1) is a better
3272 // conversion sequence than a user-defined conversion sequence or
3273 // an ellipsis conversion sequence, and
3274 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3275 // conversion sequence than an ellipsis conversion sequence
3276 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003277 //
John McCall1d318332010-01-12 00:44:57 +00003278 // C++0x [over.best.ics]p10:
3279 // For the purpose of ranking implicit conversion sequences as
3280 // described in 13.3.3.2, the ambiguous conversion sequence is
3281 // treated as a user-defined sequence that is indistinguishable
3282 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003283 if (ICS1.getKindRank() < ICS2.getKindRank())
3284 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003285 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003286 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003287
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003288 // The following checks require both conversion sequences to be of
3289 // the same kind.
3290 if (ICS1.getKind() != ICS2.getKind())
3291 return ImplicitConversionSequence::Indistinguishable;
3292
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003293 ImplicitConversionSequence::CompareKind Result =
3294 ImplicitConversionSequence::Indistinguishable;
3295
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003296 // Two implicit conversion sequences of the same form are
3297 // indistinguishable conversion sequences unless one of the
3298 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003299 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003300 Result = CompareStandardConversionSequences(S,
3301 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003302 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003303 // User-defined conversion sequence U1 is a better conversion
3304 // sequence than another user-defined conversion sequence U2 if
3305 // they contain the same user-defined conversion function or
3306 // constructor and if the second standard conversion sequence of
3307 // U1 is better than the second standard conversion sequence of
3308 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003309 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003310 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003311 Result = CompareStandardConversionSequences(S,
3312 ICS1.UserDefined.After,
3313 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003314 else
3315 Result = compareConversionFunctions(S,
3316 ICS1.UserDefined.ConversionFunction,
3317 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003318 }
3319
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003320 // List-initialization sequence L1 is a better conversion sequence than
3321 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3322 // for some X and L2 does not.
3323 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003324 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003325 ICS1.isListInitializationSequence() &&
3326 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003327 if (ICS1.isStdInitializerListElement() &&
3328 !ICS2.isStdInitializerListElement())
3329 return ImplicitConversionSequence::Better;
3330 if (!ICS1.isStdInitializerListElement() &&
3331 ICS2.isStdInitializerListElement())
3332 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003333 }
3334
3335 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003336}
3337
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003338static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3339 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3340 Qualifiers Quals;
3341 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003345 return Context.hasSameUnqualifiedType(T1, T2);
3346}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347
Douglas Gregorad323a82010-01-27 03:51:04 +00003348// Per 13.3.3.2p3, compare the given standard conversion sequences to
3349// determine if one is a proper subset of the other.
3350static ImplicitConversionSequence::CompareKind
3351compareStandardConversionSubsets(ASTContext &Context,
3352 const StandardConversionSequence& SCS1,
3353 const StandardConversionSequence& SCS2) {
3354 ImplicitConversionSequence::CompareKind Result
3355 = ImplicitConversionSequence::Indistinguishable;
3356
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003357 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003358 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003359 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3360 return ImplicitConversionSequence::Better;
3361 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3362 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003363
Douglas Gregorad323a82010-01-27 03:51:04 +00003364 if (SCS1.Second != SCS2.Second) {
3365 if (SCS1.Second == ICK_Identity)
3366 Result = ImplicitConversionSequence::Better;
3367 else if (SCS2.Second == ICK_Identity)
3368 Result = ImplicitConversionSequence::Worse;
3369 else
3370 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003371 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003372 return ImplicitConversionSequence::Indistinguishable;
3373
3374 if (SCS1.Third == SCS2.Third) {
3375 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3376 : ImplicitConversionSequence::Indistinguishable;
3377 }
3378
3379 if (SCS1.Third == ICK_Identity)
3380 return Result == ImplicitConversionSequence::Worse
3381 ? ImplicitConversionSequence::Indistinguishable
3382 : ImplicitConversionSequence::Better;
3383
3384 if (SCS2.Third == ICK_Identity)
3385 return Result == ImplicitConversionSequence::Better
3386 ? ImplicitConversionSequence::Indistinguishable
3387 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregorad323a82010-01-27 03:51:04 +00003389 return ImplicitConversionSequence::Indistinguishable;
3390}
3391
Douglas Gregor440a4832011-01-26 14:52:12 +00003392/// \brief Determine whether one of the given reference bindings is better
3393/// than the other based on what kind of bindings they are.
3394static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3395 const StandardConversionSequence &SCS2) {
3396 // C++0x [over.ics.rank]p3b4:
3397 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3398 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003400 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003402 // reference*.
3403 //
3404 // FIXME: Rvalue references. We're going rogue with the above edits,
3405 // because the semantics in the current C++0x working paper (N3225 at the
3406 // time of this writing) break the standard definition of std::forward
3407 // and std::reference_wrapper when dealing with references to functions.
3408 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003409 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3410 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3411 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003412
Douglas Gregor440a4832011-01-26 14:52:12 +00003413 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3414 SCS2.IsLvalueReference) ||
3415 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3416 !SCS2.IsLvalueReference);
3417}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003418
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003419/// CompareStandardConversionSequences - Compare two standard
3420/// conversion sequences to determine whether one is better than the
3421/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003422static ImplicitConversionSequence::CompareKind
3423CompareStandardConversionSequences(Sema &S,
3424 const StandardConversionSequence& SCS1,
3425 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003426{
3427 // Standard conversion sequence S1 is a better conversion sequence
3428 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3429
3430 // -- S1 is a proper subsequence of S2 (comparing the conversion
3431 // sequences in the canonical form defined by 13.3.3.1.1,
3432 // excluding any Lvalue Transformation; the identity conversion
3433 // sequence is considered to be a subsequence of any
3434 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003435 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003436 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003437 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003438
3439 // -- the rank of S1 is better than the rank of S2 (by the rules
3440 // defined below), or, if not that,
3441 ImplicitConversionRank Rank1 = SCS1.getRank();
3442 ImplicitConversionRank Rank2 = SCS2.getRank();
3443 if (Rank1 < Rank2)
3444 return ImplicitConversionSequence::Better;
3445 else if (Rank2 < Rank1)
3446 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003447
Douglas Gregor57373262008-10-22 14:17:15 +00003448 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3449 // are indistinguishable unless one of the following rules
3450 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Douglas Gregor57373262008-10-22 14:17:15 +00003452 // A conversion that is not a conversion of a pointer, or
3453 // pointer to member, to bool is better than another conversion
3454 // that is such a conversion.
3455 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3456 return SCS2.isPointerConversionToBool()
3457 ? ImplicitConversionSequence::Better
3458 : ImplicitConversionSequence::Worse;
3459
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003460 // C++ [over.ics.rank]p4b2:
3461 //
3462 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003463 // conversion of B* to A* is better than conversion of B* to
3464 // void*, and conversion of A* to void* is better than conversion
3465 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003466 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003467 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003468 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003469 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003470 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3471 // Exactly one of the conversion sequences is a conversion to
3472 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003473 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3474 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003475 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3476 // Neither conversion sequence converts to a void pointer; compare
3477 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003478 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003479 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003480 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003481 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3482 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003483 // Both conversion sequences are conversions to void
3484 // pointers. Compare the source types to determine if there's an
3485 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003486 QualType FromType1 = SCS1.getFromType();
3487 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003488
3489 // Adjust the types we're converting from via the array-to-pointer
3490 // conversion, if we need to.
3491 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003492 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003493 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003494 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003495
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003496 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3497 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003498
John McCall120d63c2010-08-24 20:38:10 +00003499 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003500 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003501 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003502 return ImplicitConversionSequence::Worse;
3503
3504 // Objective-C++: If one interface is more specific than the
3505 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003506 const ObjCObjectPointerType* FromObjCPtr1
3507 = FromType1->getAs<ObjCObjectPointerType>();
3508 const ObjCObjectPointerType* FromObjCPtr2
3509 = FromType2->getAs<ObjCObjectPointerType>();
3510 if (FromObjCPtr1 && FromObjCPtr2) {
3511 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3512 FromObjCPtr2);
3513 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3514 FromObjCPtr1);
3515 if (AssignLeft != AssignRight) {
3516 return AssignLeft? ImplicitConversionSequence::Better
3517 : ImplicitConversionSequence::Worse;
3518 }
Douglas Gregor01919692009-12-13 21:37:05 +00003519 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003520 }
Douglas Gregor57373262008-10-22 14:17:15 +00003521
3522 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3523 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003524 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003525 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003526 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003527
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003528 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003529 // Check for a better reference binding based on the kind of bindings.
3530 if (isBetterReferenceBindingKind(SCS1, SCS2))
3531 return ImplicitConversionSequence::Better;
3532 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3533 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003535 // C++ [over.ics.rank]p3b4:
3536 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3537 // which the references refer are the same type except for
3538 // top-level cv-qualifiers, and the type to which the reference
3539 // initialized by S2 refers is more cv-qualified than the type
3540 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003541 QualType T1 = SCS1.getToType(2);
3542 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003543 T1 = S.Context.getCanonicalType(T1);
3544 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003545 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003546 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3547 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003548 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003549 // Objective-C++ ARC: If the references refer to objects with different
3550 // lifetimes, prefer bindings that don't change lifetime.
3551 if (SCS1.ObjCLifetimeConversionBinding !=
3552 SCS2.ObjCLifetimeConversionBinding) {
3553 return SCS1.ObjCLifetimeConversionBinding
3554 ? ImplicitConversionSequence::Worse
3555 : ImplicitConversionSequence::Better;
3556 }
3557
Chandler Carruth6df868e2010-12-12 08:17:55 +00003558 // If the type is an array type, promote the element qualifiers to the
3559 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003560 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003561 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003562 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003563 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003564 if (T2.isMoreQualifiedThan(T1))
3565 return ImplicitConversionSequence::Better;
3566 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003567 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003568 }
3569 }
Douglas Gregor57373262008-10-22 14:17:15 +00003570
Francois Pichet1c98d622011-09-18 21:37:37 +00003571 // In Microsoft mode, prefer an integral conversion to a
3572 // floating-to-integral conversion if the integral conversion
3573 // is between types of the same size.
3574 // For example:
3575 // void f(float);
3576 // void f(int);
3577 // int main {
3578 // long a;
3579 // f(a);
3580 // }
3581 // Here, MSVC will call f(int) instead of generating a compile error
3582 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003583 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003584 SCS1.Second == ICK_Integral_Conversion &&
3585 SCS2.Second == ICK_Floating_Integral &&
3586 S.Context.getTypeSize(SCS1.getFromType()) ==
3587 S.Context.getTypeSize(SCS1.getToType(2)))
3588 return ImplicitConversionSequence::Better;
3589
Douglas Gregor57373262008-10-22 14:17:15 +00003590 return ImplicitConversionSequence::Indistinguishable;
3591}
3592
3593/// CompareQualificationConversions - Compares two standard conversion
3594/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003595/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3596ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003597CompareQualificationConversions(Sema &S,
3598 const StandardConversionSequence& SCS1,
3599 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003600 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003601 // -- S1 and S2 differ only in their qualification conversion and
3602 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3603 // cv-qualification signature of type T1 is a proper subset of
3604 // the cv-qualification signature of type T2, and S1 is not the
3605 // deprecated string literal array-to-pointer conversion (4.2).
3606 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3607 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3608 return ImplicitConversionSequence::Indistinguishable;
3609
3610 // FIXME: the example in the standard doesn't use a qualification
3611 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003612 QualType T1 = SCS1.getToType(2);
3613 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003614 T1 = S.Context.getCanonicalType(T1);
3615 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003616 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003617 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3618 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003619
3620 // If the types are the same, we won't learn anything by unwrapped
3621 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003622 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003623 return ImplicitConversionSequence::Indistinguishable;
3624
Chandler Carruth28e318c2009-12-29 07:16:59 +00003625 // If the type is an array type, promote the element qualifiers to the type
3626 // for comparison.
3627 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003628 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003629 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003630 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003631
Mike Stump1eb44332009-09-09 15:08:12 +00003632 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003633 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003634
3635 // Objective-C++ ARC:
3636 // Prefer qualification conversions not involving a change in lifetime
3637 // to qualification conversions that do not change lifetime.
3638 if (SCS1.QualificationIncludesObjCLifetime !=
3639 SCS2.QualificationIncludesObjCLifetime) {
3640 Result = SCS1.QualificationIncludesObjCLifetime
3641 ? ImplicitConversionSequence::Worse
3642 : ImplicitConversionSequence::Better;
3643 }
3644
John McCall120d63c2010-08-24 20:38:10 +00003645 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003646 // Within each iteration of the loop, we check the qualifiers to
3647 // determine if this still looks like a qualification
3648 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003649 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003650 // until there are no more pointers or pointers-to-members left
3651 // to unwrap. This essentially mimics what
3652 // IsQualificationConversion does, but here we're checking for a
3653 // strict subset of qualifiers.
3654 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3655 // The qualifiers are the same, so this doesn't tell us anything
3656 // about how the sequences rank.
3657 ;
3658 else if (T2.isMoreQualifiedThan(T1)) {
3659 // T1 has fewer qualifiers, so it could be the better sequence.
3660 if (Result == ImplicitConversionSequence::Worse)
3661 // Neither has qualifiers that are a subset of the other's
3662 // qualifiers.
3663 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Douglas Gregor57373262008-10-22 14:17:15 +00003665 Result = ImplicitConversionSequence::Better;
3666 } else if (T1.isMoreQualifiedThan(T2)) {
3667 // T2 has fewer qualifiers, so it could be the better sequence.
3668 if (Result == ImplicitConversionSequence::Better)
3669 // Neither has qualifiers that are a subset of the other's
3670 // qualifiers.
3671 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Douglas Gregor57373262008-10-22 14:17:15 +00003673 Result = ImplicitConversionSequence::Worse;
3674 } else {
3675 // Qualifiers are disjoint.
3676 return ImplicitConversionSequence::Indistinguishable;
3677 }
3678
3679 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003680 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003681 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003682 }
3683
Douglas Gregor57373262008-10-22 14:17:15 +00003684 // Check that the winning standard conversion sequence isn't using
3685 // the deprecated string literal array to pointer conversion.
3686 switch (Result) {
3687 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003688 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003689 Result = ImplicitConversionSequence::Indistinguishable;
3690 break;
3691
3692 case ImplicitConversionSequence::Indistinguishable:
3693 break;
3694
3695 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003696 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003697 Result = ImplicitConversionSequence::Indistinguishable;
3698 break;
3699 }
3700
3701 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003702}
3703
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003704/// CompareDerivedToBaseConversions - Compares two standard conversion
3705/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003706/// various kinds of derived-to-base conversions (C++
3707/// [over.ics.rank]p4b3). As part of these checks, we also look at
3708/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003709ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003710CompareDerivedToBaseConversions(Sema &S,
3711 const StandardConversionSequence& SCS1,
3712 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003713 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003714 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003715 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003716 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003717
3718 // Adjust the types we're converting from via the array-to-pointer
3719 // conversion, if we need to.
3720 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003721 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003722 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003723 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003724
3725 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003726 FromType1 = S.Context.getCanonicalType(FromType1);
3727 ToType1 = S.Context.getCanonicalType(ToType1);
3728 FromType2 = S.Context.getCanonicalType(FromType2);
3729 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003730
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003731 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003732 //
3733 // If class B is derived directly or indirectly from class A and
3734 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003735 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003736 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003737 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003738 SCS2.Second == ICK_Pointer_Conversion &&
3739 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3740 FromType1->isPointerType() && FromType2->isPointerType() &&
3741 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003742 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003743 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003744 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003745 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003746 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003747 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003748 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003749 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003750
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003751 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003753 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003754 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003755 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003756 return ImplicitConversionSequence::Worse;
3757 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003758
3759 // -- conversion of B* to A* is better than conversion of C* to A*,
3760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003761 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003762 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003763 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003764 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003765 }
3766 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3767 SCS2.Second == ICK_Pointer_Conversion) {
3768 const ObjCObjectPointerType *FromPtr1
3769 = FromType1->getAs<ObjCObjectPointerType>();
3770 const ObjCObjectPointerType *FromPtr2
3771 = FromType2->getAs<ObjCObjectPointerType>();
3772 const ObjCObjectPointerType *ToPtr1
3773 = ToType1->getAs<ObjCObjectPointerType>();
3774 const ObjCObjectPointerType *ToPtr2
3775 = ToType2->getAs<ObjCObjectPointerType>();
3776
3777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3778 // Apply the same conversion ranking rules for Objective-C pointer types
3779 // that we do for C++ pointers to class types. However, we employ the
3780 // Objective-C pseudo-subtyping relationship used for assignment of
3781 // Objective-C pointer types.
3782 bool FromAssignLeft
3783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3784 bool FromAssignRight
3785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3786 bool ToAssignLeft
3787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3788 bool ToAssignRight
3789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3790
3791 // A conversion to an a non-id object pointer type or qualified 'id'
3792 // type is better than a conversion to 'id'.
3793 if (ToPtr1->isObjCIdType() &&
3794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3795 return ImplicitConversionSequence::Worse;
3796 if (ToPtr2->isObjCIdType() &&
3797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3798 return ImplicitConversionSequence::Better;
3799
3800 // A conversion to a non-id object pointer type is better than a
3801 // conversion to a qualified 'id' type
3802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3803 return ImplicitConversionSequence::Worse;
3804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3805 return ImplicitConversionSequence::Better;
3806
3807 // A conversion to an a non-Class object pointer type or qualified 'Class'
3808 // type is better than a conversion to 'Class'.
3809 if (ToPtr1->isObjCClassType() &&
3810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3811 return ImplicitConversionSequence::Worse;
3812 if (ToPtr2->isObjCClassType() &&
3813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3814 return ImplicitConversionSequence::Better;
3815
3816 // A conversion to a non-Class object pointer type is better than a
3817 // conversion to a qualified 'Class' type.
3818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3819 return ImplicitConversionSequence::Worse;
3820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3821 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Douglas Gregor395cc372011-01-31 18:51:41 +00003823 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3824 if (S.Context.hasSameType(FromType1, FromType2) &&
3825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3826 (ToAssignLeft != ToAssignRight))
3827 return ToAssignLeft? ImplicitConversionSequence::Worse
3828 : ImplicitConversionSequence::Better;
3829
3830 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3831 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3832 (FromAssignLeft != FromAssignRight))
3833 return FromAssignLeft? ImplicitConversionSequence::Better
3834 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003835 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003836 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003837
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003838 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003839 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3840 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3841 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003843 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003845 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003847 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003849 ToType2->getAs<MemberPointerType>();
3850 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3851 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3852 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3853 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3854 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3855 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3856 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3857 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003858 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003859 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003860 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003861 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003862 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003863 return ImplicitConversionSequence::Better;
3864 }
3865 // conversion of B::* to C::* is better than conversion of A::* to C::*
3866 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003867 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003868 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003869 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003870 return ImplicitConversionSequence::Worse;
3871 }
3872 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003873
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003874 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003875 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003876 // -- binding of an expression of type C to a reference of type
3877 // B& is better than binding an expression of type C to a
3878 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003879 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3880 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3881 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003882 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003883 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003884 return ImplicitConversionSequence::Worse;
3885 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003886
Douglas Gregor225c41e2008-11-03 19:09:14 +00003887 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003888 // -- binding of an expression of type B to a reference of type
3889 // A& is better than binding an expression of type C to a
3890 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003891 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3892 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3893 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003894 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003895 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003896 return ImplicitConversionSequence::Worse;
3897 }
3898 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003899
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003900 return ImplicitConversionSequence::Indistinguishable;
3901}
3902
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003903/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3904/// C++ class.
3905static bool isTypeValid(QualType T) {
3906 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3907 return !Record->isInvalidDecl();
3908
3909 return true;
3910}
3911
Douglas Gregorabe183d2010-04-13 16:31:36 +00003912/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3913/// determine whether they are reference-related,
3914/// reference-compatible, reference-compatible with added
3915/// qualification, or incompatible, for use in C++ initialization by
3916/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3917/// type, and the first type (T1) is the pointee type of the reference
3918/// type being initialized.
3919Sema::ReferenceCompareResult
3920Sema::CompareReferenceRelationship(SourceLocation Loc,
3921 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003922 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003923 bool &ObjCConversion,
3924 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003925 assert(!OrigT1->isReferenceType() &&
3926 "T1 must be the pointee type of the reference type");
3927 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3928
3929 QualType T1 = Context.getCanonicalType(OrigT1);
3930 QualType T2 = Context.getCanonicalType(OrigT2);
3931 Qualifiers T1Quals, T2Quals;
3932 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3933 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3934
3935 // C++ [dcl.init.ref]p4:
3936 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3937 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3938 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003939 DerivedToBase = false;
3940 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003941 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003942 if (UnqualT1 == UnqualT2) {
3943 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003944 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003945 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3946 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003947 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003948 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3949 UnqualT2->isObjCObjectOrInterfaceType() &&
3950 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3951 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003952 else
3953 return Ref_Incompatible;
3954
3955 // At this point, we know that T1 and T2 are reference-related (at
3956 // least).
3957
3958 // If the type is an array type, promote the element qualifiers to the type
3959 // for comparison.
3960 if (isa<ArrayType>(T1) && T1Quals)
3961 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3962 if (isa<ArrayType>(T2) && T2Quals)
3963 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3964
3965 // C++ [dcl.init.ref]p4:
3966 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3967 // reference-related to T2 and cv1 is the same cv-qualification
3968 // as, or greater cv-qualification than, cv2. For purposes of
3969 // overload resolution, cases for which cv1 is greater
3970 // cv-qualification than cv2 are identified as
3971 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003972 //
3973 // Note that we also require equivalence of Objective-C GC and address-space
3974 // qualifiers when performing these computations, so that e.g., an int in
3975 // address space 1 is not reference-compatible with an int in address
3976 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003977 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3978 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3979 T1Quals.removeObjCLifetime();
3980 T2Quals.removeObjCLifetime();
3981 ObjCLifetimeConversion = true;
3982 }
3983
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003984 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003985 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003986 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003987 return Ref_Compatible_With_Added_Qualification;
3988 else
3989 return Ref_Related;
3990}
3991
Douglas Gregor604eb652010-08-11 02:15:33 +00003992/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003993/// with DeclType. Return true if something definite is found.
3994static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003995FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3996 QualType DeclType, SourceLocation DeclLoc,
3997 Expr *Init, QualType T2, bool AllowRvalues,
3998 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003999 assert(T2->isRecordType() && "Can only find conversions of record types.");
4000 CXXRecordDecl *T2RecordDecl
4001 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4002
4003 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004004 std::pair<CXXRecordDecl::conversion_iterator,
4005 CXXRecordDecl::conversion_iterator>
4006 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4007 for (CXXRecordDecl::conversion_iterator
4008 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004009 NamedDecl *D = *I;
4010 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4011 if (isa<UsingShadowDecl>(D))
4012 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4013
4014 FunctionTemplateDecl *ConvTemplate
4015 = dyn_cast<FunctionTemplateDecl>(D);
4016 CXXConversionDecl *Conv;
4017 if (ConvTemplate)
4018 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4019 else
4020 Conv = cast<CXXConversionDecl>(D);
4021
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004023 // explicit conversions, skip it.
4024 if (!AllowExplicit && Conv->isExplicit())
4025 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004026
Douglas Gregor604eb652010-08-11 02:15:33 +00004027 if (AllowRvalues) {
4028 bool DerivedToBase = false;
4029 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004030 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004031
4032 // If we are initializing an rvalue reference, don't permit conversion
4033 // functions that return lvalues.
4034 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4035 const ReferenceType *RefType
4036 = Conv->getConversionType()->getAs<LValueReferenceType>();
4037 if (RefType && !RefType->getPointeeType()->isFunctionType())
4038 continue;
4039 }
4040
Douglas Gregor604eb652010-08-11 02:15:33 +00004041 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004042 S.CompareReferenceRelationship(
4043 DeclLoc,
4044 Conv->getConversionType().getNonReferenceType()
4045 .getUnqualifiedType(),
4046 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004047 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004048 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004049 continue;
4050 } else {
4051 // If the conversion function doesn't return a reference type,
4052 // it can't be considered for this conversion. An rvalue reference
4053 // is only acceptable if its referencee is a function type.
4054
4055 const ReferenceType *RefType =
4056 Conv->getConversionType()->getAs<ReferenceType>();
4057 if (!RefType ||
4058 (!RefType->isLValueReferenceType() &&
4059 !RefType->getPointeeType()->isFunctionType()))
4060 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004061 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004062
Douglas Gregor604eb652010-08-11 02:15:33 +00004063 if (ConvTemplate)
4064 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004065 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004066 else
4067 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004068 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004069 }
4070
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004071 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4072
Sebastian Redl4680bf22010-06-30 18:13:39 +00004073 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004074 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004075 case OR_Success:
4076 // C++ [over.ics.ref]p1:
4077 //
4078 // [...] If the parameter binds directly to the result of
4079 // applying a conversion function to the argument
4080 // expression, the implicit conversion sequence is a
4081 // user-defined conversion sequence (13.3.3.1.2), with the
4082 // second standard conversion sequence either an identity
4083 // conversion or, if the conversion function returns an
4084 // entity of a type that is a derived class of the parameter
4085 // type, a derived-to-base Conversion.
4086 if (!Best->FinalConversion.DirectBinding)
4087 return false;
4088
4089 ICS.setUserDefined();
4090 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4091 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004092 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004093 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004094 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004095 ICS.UserDefined.EllipsisConversion = false;
4096 assert(ICS.UserDefined.After.ReferenceBinding &&
4097 ICS.UserDefined.After.DirectBinding &&
4098 "Expected a direct reference binding!");
4099 return true;
4100
4101 case OR_Ambiguous:
4102 ICS.setAmbiguous();
4103 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4104 Cand != CandidateSet.end(); ++Cand)
4105 if (Cand->Viable)
4106 ICS.Ambiguous.addConversion(Cand->Function);
4107 return true;
4108
4109 case OR_No_Viable_Function:
4110 case OR_Deleted:
4111 // There was no suitable conversion, or we found a deleted
4112 // conversion; continue with other checks.
4113 return false;
4114 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004115
David Blaikie7530c032012-01-17 06:56:22 +00004116 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004117}
4118
Douglas Gregorabe183d2010-04-13 16:31:36 +00004119/// \brief Compute an implicit conversion sequence for reference
4120/// initialization.
4121static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004122TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004123 SourceLocation DeclLoc,
4124 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004125 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004126 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4127
4128 // Most paths end in a failed conversion.
4129 ImplicitConversionSequence ICS;
4130 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4131
4132 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4133 QualType T2 = Init->getType();
4134
4135 // If the initializer is the address of an overloaded function, try
4136 // to resolve the overloaded function. If all goes well, T2 is the
4137 // type of the resulting function.
4138 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4139 DeclAccessPair Found;
4140 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4141 false, Found))
4142 T2 = Fn->getType();
4143 }
4144
4145 // Compute some basic properties of the types and the initializer.
4146 bool isRValRef = DeclType->isRValueReferenceType();
4147 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004148 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004149 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004150 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004151 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004152 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004153 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004154
Douglas Gregorabe183d2010-04-13 16:31:36 +00004155
Sebastian Redl4680bf22010-06-30 18:13:39 +00004156 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004157 // A reference to type "cv1 T1" is initialized by an expression
4158 // of type "cv2 T2" as follows:
4159
Sebastian Redl4680bf22010-06-30 18:13:39 +00004160 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004161 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004162 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4163 // reference-compatible with "cv2 T2," or
4164 //
4165 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4166 if (InitCategory.isLValue() &&
4167 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004168 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004169 // When a parameter of reference type binds directly (8.5.3)
4170 // to an argument expression, the implicit conversion sequence
4171 // is the identity conversion, unless the argument expression
4172 // has a type that is a derived class of the parameter type,
4173 // in which case the implicit conversion sequence is a
4174 // derived-to-base Conversion (13.3.3.1).
4175 ICS.setStandard();
4176 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004177 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4178 : ObjCConversion? ICK_Compatible_Conversion
4179 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004180 ICS.Standard.Third = ICK_Identity;
4181 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4182 ICS.Standard.setToType(0, T2);
4183 ICS.Standard.setToType(1, T1);
4184 ICS.Standard.setToType(2, T1);
4185 ICS.Standard.ReferenceBinding = true;
4186 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004187 ICS.Standard.IsLvalueReference = !isRValRef;
4188 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4189 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004190 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004191 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004192 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004193
Sebastian Redl4680bf22010-06-30 18:13:39 +00004194 // Nothing more to do: the inaccessibility/ambiguity check for
4195 // derived-to-base conversions is suppressed when we're
4196 // computing the implicit conversion sequence (C++
4197 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004198 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004199 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004200
Sebastian Redl4680bf22010-06-30 18:13:39 +00004201 // -- has a class type (i.e., T2 is a class type), where T1 is
4202 // not reference-related to T2, and can be implicitly
4203 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4204 // is reference-compatible with "cv3 T3" 92) (this
4205 // conversion is selected by enumerating the applicable
4206 // conversion functions (13.3.1.6) and choosing the best
4207 // one through overload resolution (13.3)),
4208 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004210 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004211 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4212 Init, T2, /*AllowRvalues=*/false,
4213 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004214 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004215 }
4216 }
4217
Sebastian Redl4680bf22010-06-30 18:13:39 +00004218 // -- Otherwise, the reference shall be an lvalue reference to a
4219 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004220 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004221 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004222 // We actually handle one oddity of C++ [over.ics.ref] at this
4223 // point, which is that, due to p2 (which short-circuits reference
4224 // binding by only attempting a simple conversion for non-direct
4225 // bindings) and p3's strange wording, we allow a const volatile
4226 // reference to bind to an rvalue. Hence the check for the presence
4227 // of "const" rather than checking for "const" being the only
4228 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004229 // This is also the point where rvalue references and lvalue inits no longer
4230 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004231 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004232 return ICS;
4233
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004234 // -- If the initializer expression
4235 //
4236 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004237 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004238 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4239 (InitCategory.isXValue() ||
4240 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4241 (InitCategory.isLValue() && T2->isFunctionType()))) {
4242 ICS.setStandard();
4243 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004245 : ObjCConversion? ICK_Compatible_Conversion
4246 : ICK_Identity;
4247 ICS.Standard.Third = ICK_Identity;
4248 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4249 ICS.Standard.setToType(0, T2);
4250 ICS.Standard.setToType(1, T1);
4251 ICS.Standard.setToType(2, T1);
4252 ICS.Standard.ReferenceBinding = true;
4253 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4254 // binding unless we're binding to a class prvalue.
4255 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4256 // allow the use of rvalue references in C++98/03 for the benefit of
4257 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004259 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004260 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004261 ICS.Standard.IsLvalueReference = !isRValRef;
4262 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004264 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004265 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004266 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004269
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004270 // -- has a class type (i.e., T2 is a class type), where T1 is not
4271 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004272 // an xvalue, class prvalue, or function lvalue of type
4273 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004274 // "cv3 T3",
4275 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004276 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004277 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004278 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004279 // class subobject).
4280 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004282 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4283 Init, T2, /*AllowRvalues=*/true,
4284 AllowExplicit)) {
4285 // In the second case, if the reference is an rvalue reference
4286 // and the second standard conversion sequence of the
4287 // user-defined conversion sequence includes an lvalue-to-rvalue
4288 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004290 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4291 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4292
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004293 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004295
Douglas Gregorabe183d2010-04-13 16:31:36 +00004296 // -- Otherwise, a temporary of type "cv1 T1" is created and
4297 // initialized from the initializer expression using the
4298 // rules for a non-reference copy initialization (8.5). The
4299 // reference is then bound to the temporary. If T1 is
4300 // reference-related to T2, cv1 must be the same
4301 // cv-qualification as, or greater cv-qualification than,
4302 // cv2; otherwise, the program is ill-formed.
4303 if (RefRelationship == Sema::Ref_Related) {
4304 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4305 // we would be reference-compatible or reference-compatible with
4306 // added qualification. But that wasn't the case, so the reference
4307 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004308 //
4309 // Note that we only want to check address spaces and cvr-qualifiers here.
4310 // ObjC GC and lifetime qualifiers aren't important.
4311 Qualifiers T1Quals = T1.getQualifiers();
4312 Qualifiers T2Quals = T2.getQualifiers();
4313 T1Quals.removeObjCGCAttr();
4314 T1Quals.removeObjCLifetime();
4315 T2Quals.removeObjCGCAttr();
4316 T2Quals.removeObjCLifetime();
4317 if (!T1Quals.compatiblyIncludes(T2Quals))
4318 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004319 }
4320
4321 // If at least one of the types is a class type, the types are not
4322 // related, and we aren't allowed any user conversions, the
4323 // reference binding fails. This case is important for breaking
4324 // recursion, since TryImplicitConversion below will attempt to
4325 // create a temporary through the use of a copy constructor.
4326 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4327 (T1->isRecordType() || T2->isRecordType()))
4328 return ICS;
4329
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004330 // If T1 is reference-related to T2 and the reference is an rvalue
4331 // reference, the initializer expression shall not be an lvalue.
4332 if (RefRelationship >= Sema::Ref_Related &&
4333 isRValRef && Init->Classify(S.Context).isLValue())
4334 return ICS;
4335
Douglas Gregorabe183d2010-04-13 16:31:36 +00004336 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004337 // When a parameter of reference type is not bound directly to
4338 // an argument expression, the conversion sequence is the one
4339 // required to convert the argument expression to the
4340 // underlying type of the reference according to
4341 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4342 // to copy-initializing a temporary of the underlying type with
4343 // the argument expression. Any difference in top-level
4344 // cv-qualification is subsumed by the initialization itself
4345 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004346 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4347 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004348 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004349 /*CStyle=*/false,
4350 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004351
4352 // Of course, that's still a reference binding.
4353 if (ICS.isStandard()) {
4354 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004355 ICS.Standard.IsLvalueReference = !isRValRef;
4356 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4357 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004358 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004359 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004360 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004361 // Don't allow rvalue references to bind to lvalues.
4362 if (DeclType->isRValueReferenceType()) {
4363 if (const ReferenceType *RefType
4364 = ICS.UserDefined.ConversionFunction->getResultType()
4365 ->getAs<LValueReferenceType>()) {
4366 if (!RefType->getPointeeType()->isFunctionType()) {
4367 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4368 DeclType);
4369 return ICS;
4370 }
4371 }
4372 }
4373
Douglas Gregorabe183d2010-04-13 16:31:36 +00004374 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004375 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4376 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4377 ICS.UserDefined.After.BindsToRvalue = true;
4378 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4379 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004380 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004381
Douglas Gregorabe183d2010-04-13 16:31:36 +00004382 return ICS;
4383}
4384
Sebastian Redl5405b812011-10-16 18:19:34 +00004385static ImplicitConversionSequence
4386TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4387 bool SuppressUserConversions,
4388 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004389 bool AllowObjCWritebackConversion,
4390 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004391
4392/// TryListConversion - Try to copy-initialize a value of type ToType from the
4393/// initializer list From.
4394static ImplicitConversionSequence
4395TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4396 bool SuppressUserConversions,
4397 bool InOverloadResolution,
4398 bool AllowObjCWritebackConversion) {
4399 // C++11 [over.ics.list]p1:
4400 // When an argument is an initializer list, it is not an expression and
4401 // special rules apply for converting it to a parameter type.
4402
4403 ImplicitConversionSequence Result;
4404 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004405 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004406
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004407 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004408 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004409 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004410 return Result;
4411
Sebastian Redl5405b812011-10-16 18:19:34 +00004412 // C++11 [over.ics.list]p2:
4413 // If the parameter type is std::initializer_list<X> or "array of X" and
4414 // all the elements can be implicitly converted to X, the implicit
4415 // conversion sequence is the worst conversion necessary to convert an
4416 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004417 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004418 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004419 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004420 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004421 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004422 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004423 if (!X.isNull()) {
4424 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4425 Expr *Init = From->getInit(i);
4426 ImplicitConversionSequence ICS =
4427 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4428 InOverloadResolution,
4429 AllowObjCWritebackConversion);
4430 // If a single element isn't convertible, fail.
4431 if (ICS.isBad()) {
4432 Result = ICS;
4433 break;
4434 }
4435 // Otherwise, look for the worst conversion.
4436 if (Result.isBad() ||
4437 CompareImplicitConversionSequences(S, ICS, Result) ==
4438 ImplicitConversionSequence::Worse)
4439 Result = ICS;
4440 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004441
4442 // For an empty list, we won't have computed any conversion sequence.
4443 // Introduce the identity conversion sequence.
4444 if (From->getNumInits() == 0) {
4445 Result.setStandard();
4446 Result.Standard.setAsIdentityConversion();
4447 Result.Standard.setFromType(ToType);
4448 Result.Standard.setAllToTypes(ToType);
4449 }
4450
Sebastian Redlfe592282012-01-17 22:49:48 +00004451 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004452 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004453 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004454 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004455
4456 // C++11 [over.ics.list]p3:
4457 // Otherwise, if the parameter is a non-aggregate class X and overload
4458 // resolution chooses a single best constructor [...] the implicit
4459 // conversion sequence is a user-defined conversion sequence. If multiple
4460 // constructors are viable but none is better than the others, the
4461 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004462 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4463 // This function can deal with initializer lists.
4464 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4465 /*AllowExplicit=*/false,
4466 InOverloadResolution, /*CStyle=*/false,
4467 AllowObjCWritebackConversion);
4468 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004469 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004470 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004471
4472 // C++11 [over.ics.list]p4:
4473 // Otherwise, if the parameter has an aggregate type which can be
4474 // initialized from the initializer list [...] the implicit conversion
4475 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004476 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004477 // Type is an aggregate, argument is an init list. At this point it comes
4478 // down to checking whether the initialization works.
4479 // FIXME: Find out whether this parameter is consumed or not.
4480 InitializedEntity Entity =
4481 InitializedEntity::InitializeParameter(S.Context, ToType,
4482 /*Consumed=*/false);
4483 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4484 Result.setUserDefined();
4485 Result.UserDefined.Before.setAsIdentityConversion();
4486 // Initializer lists don't have a type.
4487 Result.UserDefined.Before.setFromType(QualType());
4488 Result.UserDefined.Before.setAllToTypes(QualType());
4489
4490 Result.UserDefined.After.setAsIdentityConversion();
4491 Result.UserDefined.After.setFromType(ToType);
4492 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004493 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004494 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004495 return Result;
4496 }
4497
4498 // C++11 [over.ics.list]p5:
4499 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004500 if (ToType->isReferenceType()) {
4501 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4502 // mention initializer lists in any way. So we go by what list-
4503 // initialization would do and try to extrapolate from that.
4504
4505 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4506
4507 // If the initializer list has a single element that is reference-related
4508 // to the parameter type, we initialize the reference from that.
4509 if (From->getNumInits() == 1) {
4510 Expr *Init = From->getInit(0);
4511
4512 QualType T2 = Init->getType();
4513
4514 // If the initializer is the address of an overloaded function, try
4515 // to resolve the overloaded function. If all goes well, T2 is the
4516 // type of the resulting function.
4517 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4518 DeclAccessPair Found;
4519 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4520 Init, ToType, false, Found))
4521 T2 = Fn->getType();
4522 }
4523
4524 // Compute some basic properties of the types and the initializer.
4525 bool dummy1 = false;
4526 bool dummy2 = false;
4527 bool dummy3 = false;
4528 Sema::ReferenceCompareResult RefRelationship
4529 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4530 dummy2, dummy3);
4531
4532 if (RefRelationship >= Sema::Ref_Related)
4533 return TryReferenceInit(S, Init, ToType,
4534 /*FIXME:*/From->getLocStart(),
4535 SuppressUserConversions,
4536 /*AllowExplicit=*/false);
4537 }
4538
4539 // Otherwise, we bind the reference to a temporary created from the
4540 // initializer list.
4541 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4542 InOverloadResolution,
4543 AllowObjCWritebackConversion);
4544 if (Result.isFailure())
4545 return Result;
4546 assert(!Result.isEllipsis() &&
4547 "Sub-initialization cannot result in ellipsis conversion.");
4548
4549 // Can we even bind to a temporary?
4550 if (ToType->isRValueReferenceType() ||
4551 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4552 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4553 Result.UserDefined.After;
4554 SCS.ReferenceBinding = true;
4555 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4556 SCS.BindsToRvalue = true;
4557 SCS.BindsToFunctionLvalue = false;
4558 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4559 SCS.ObjCLifetimeConversionBinding = false;
4560 } else
4561 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4562 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004563 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004564 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004565
4566 // C++11 [over.ics.list]p6:
4567 // Otherwise, if the parameter type is not a class:
4568 if (!ToType->isRecordType()) {
4569 // - if the initializer list has one element, the implicit conversion
4570 // sequence is the one required to convert the element to the
4571 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004572 unsigned NumInits = From->getNumInits();
4573 if (NumInits == 1)
4574 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4575 SuppressUserConversions,
4576 InOverloadResolution,
4577 AllowObjCWritebackConversion);
4578 // - if the initializer list has no elements, the implicit conversion
4579 // sequence is the identity conversion.
4580 else if (NumInits == 0) {
4581 Result.setStandard();
4582 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004583 Result.Standard.setFromType(ToType);
4584 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004585 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004586 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004587 return Result;
4588 }
4589
4590 // C++11 [over.ics.list]p7:
4591 // In all cases other than those enumerated above, no conversion is possible
4592 return Result;
4593}
4594
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004595/// TryCopyInitialization - Try to copy-initialize a value of type
4596/// ToType from the expression From. Return the implicit conversion
4597/// sequence required to pass this argument, which may be a bad
4598/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004599/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004600/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004601static ImplicitConversionSequence
4602TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004603 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004604 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004605 bool AllowObjCWritebackConversion,
4606 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004607 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4608 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4609 InOverloadResolution,AllowObjCWritebackConversion);
4610
Douglas Gregorabe183d2010-04-13 16:31:36 +00004611 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004612 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004613 /*FIXME:*/From->getLocStart(),
4614 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004615 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004616
John McCall120d63c2010-08-24 20:38:10 +00004617 return TryImplicitConversion(S, From, ToType,
4618 SuppressUserConversions,
4619 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004620 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004621 /*CStyle=*/false,
4622 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004623}
4624
Anna Zaksf3546ee2011-07-28 19:46:48 +00004625static bool TryCopyInitialization(const CanQualType FromQTy,
4626 const CanQualType ToQTy,
4627 Sema &S,
4628 SourceLocation Loc,
4629 ExprValueKind FromVK) {
4630 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4631 ImplicitConversionSequence ICS =
4632 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4633
4634 return !ICS.isBad();
4635}
4636
Douglas Gregor96176b32008-11-18 23:14:02 +00004637/// TryObjectArgumentInitialization - Try to initialize the object
4638/// parameter of the given member function (@c Method) from the
4639/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004640static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004641TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004642 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004643 CXXMethodDecl *Method,
4644 CXXRecordDecl *ActingContext) {
4645 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004646 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4647 // const volatile object.
4648 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4649 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004650 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004651
4652 // Set up the conversion sequence as a "bad" conversion, to allow us
4653 // to exit early.
4654 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004655
4656 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004657 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004658 FromType = PT->getPointeeType();
4659
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004660 // When we had a pointer, it's implicitly dereferenced, so we
4661 // better have an lvalue.
4662 assert(FromClassification.isLValue());
4663 }
4664
Anders Carlssona552f7c2009-05-01 18:34:30 +00004665 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004666
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004667 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004668 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004669 // parameter is
4670 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004671 // - "lvalue reference to cv X" for functions declared without a
4672 // ref-qualifier or with the & ref-qualifier
4673 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004674 // ref-qualifier
4675 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004676 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004677 // cv-qualification on the member function declaration.
4678 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004679 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004680 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004681 // (C++ [over.match.funcs]p5). We perform a simplified version of
4682 // reference binding here, that allows class rvalues to bind to
4683 // non-constant references.
4684
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004685 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004686 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004687 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004688 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004689 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004690 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004691 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004692 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004693 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004694
4695 // Check that we have either the same type or a derived type. It
4696 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004697 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004698 ImplicitConversionKind SecondKind;
4699 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4700 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004701 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004702 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004703 else {
John McCallb1bdc622010-02-25 01:37:24 +00004704 ICS.setBad(BadConversionSequence::unrelated_class,
4705 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004706 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004707 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004708
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004709 // Check the ref-qualifier.
4710 switch (Method->getRefQualifier()) {
4711 case RQ_None:
4712 // Do nothing; we don't care about lvalueness or rvalueness.
4713 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004715 case RQ_LValue:
4716 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4717 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004718 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004719 ImplicitParamType);
4720 return ICS;
4721 }
4722 break;
4723
4724 case RQ_RValue:
4725 if (!FromClassification.isRValue()) {
4726 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004727 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004728 ImplicitParamType);
4729 return ICS;
4730 }
4731 break;
4732 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004733
Douglas Gregor96176b32008-11-18 23:14:02 +00004734 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004735 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004736 ICS.Standard.setAsIdentityConversion();
4737 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004738 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004739 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004740 ICS.Standard.ReferenceBinding = true;
4741 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004742 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004743 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004744 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4745 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4746 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004747 return ICS;
4748}
4749
4750/// PerformObjectArgumentInitialization - Perform initialization of
4751/// the implicit object parameter for the given Method with the given
4752/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004753ExprResult
4754Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004755 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004756 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004757 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004758 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004759 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004760 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004761
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004762 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004763 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004764 FromRecordType = PT->getPointeeType();
4765 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004766 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004767 } else {
4768 FromRecordType = From->getType();
4769 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004770 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004771 }
4772
John McCall701c89e2009-12-03 04:06:58 +00004773 // Note that we always use the true parent context when performing
4774 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004775 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004776 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4777 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004778 if (ICS.isBad()) {
4779 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4780 Qualifiers FromQs = FromRecordType.getQualifiers();
4781 Qualifiers ToQs = DestType.getQualifiers();
4782 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4783 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004784 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004785 diag::err_member_function_call_bad_cvr)
4786 << Method->getDeclName() << FromRecordType << (CVR - 1)
4787 << From->getSourceRange();
4788 Diag(Method->getLocation(), diag::note_previous_decl)
4789 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004790 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004791 }
4792 }
4793
Daniel Dunbar96a00142012-03-09 18:35:03 +00004794 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004795 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004796 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004797 }
Mike Stump1eb44332009-09-09 15:08:12 +00004798
John Wiegley429bb272011-04-08 18:41:53 +00004799 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4800 ExprResult FromRes =
4801 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4802 if (FromRes.isInvalid())
4803 return ExprError();
4804 From = FromRes.take();
4805 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004806
Douglas Gregor5fccd362010-03-03 23:55:11 +00004807 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004808 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004809 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004810 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004811}
4812
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004813/// TryContextuallyConvertToBool - Attempt to contextually convert the
4814/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004815static ImplicitConversionSequence
4816TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004817 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004818 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004819 // FIXME: Are these flags correct?
4820 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004821 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004822 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004823 /*CStyle=*/false,
4824 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004825}
4826
4827/// PerformContextuallyConvertToBool - Perform a contextual conversion
4828/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004829ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004830 if (checkPlaceholderForOverload(*this, From))
4831 return ExprError();
4832
John McCall120d63c2010-08-24 20:38:10 +00004833 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004834 if (!ICS.isBad())
4835 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004836
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004837 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004838 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004839 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004840 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004841 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004842}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004843
Richard Smith8ef7b202012-01-18 23:55:52 +00004844/// Check that the specified conversion is permitted in a converted constant
4845/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4846/// is acceptable.
4847static bool CheckConvertedConstantConversions(Sema &S,
4848 StandardConversionSequence &SCS) {
4849 // Since we know that the target type is an integral or unscoped enumeration
4850 // type, most conversion kinds are impossible. All possible First and Third
4851 // conversions are fine.
4852 switch (SCS.Second) {
4853 case ICK_Identity:
4854 case ICK_Integral_Promotion:
4855 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004856 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004857 return true;
4858
4859 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004860 // Conversion from an integral or unscoped enumeration type to bool is
4861 // classified as ICK_Boolean_Conversion, but it's also an integral
4862 // conversion, so it's permitted in a converted constant expression.
4863 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4864 SCS.getToType(2)->isBooleanType();
4865
Richard Smith8ef7b202012-01-18 23:55:52 +00004866 case ICK_Floating_Integral:
4867 case ICK_Complex_Real:
4868 return false;
4869
4870 case ICK_Lvalue_To_Rvalue:
4871 case ICK_Array_To_Pointer:
4872 case ICK_Function_To_Pointer:
4873 case ICK_NoReturn_Adjustment:
4874 case ICK_Qualification:
4875 case ICK_Compatible_Conversion:
4876 case ICK_Vector_Conversion:
4877 case ICK_Vector_Splat:
4878 case ICK_Derived_To_Base:
4879 case ICK_Pointer_Conversion:
4880 case ICK_Pointer_Member:
4881 case ICK_Block_Pointer_Conversion:
4882 case ICK_Writeback_Conversion:
4883 case ICK_Floating_Promotion:
4884 case ICK_Complex_Promotion:
4885 case ICK_Complex_Conversion:
4886 case ICK_Floating_Conversion:
4887 case ICK_TransparentUnionConversion:
4888 llvm_unreachable("unexpected second conversion kind");
4889
4890 case ICK_Num_Conversion_Kinds:
4891 break;
4892 }
4893
4894 llvm_unreachable("unknown conversion kind");
4895}
4896
4897/// CheckConvertedConstantExpression - Check that the expression From is a
4898/// converted constant expression of type T, perform the conversion and produce
4899/// the converted expression, per C++11 [expr.const]p3.
4900ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4901 llvm::APSInt &Value,
4902 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004903 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004904 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4905
4906 if (checkPlaceholderForOverload(*this, From))
4907 return ExprError();
4908
4909 // C++11 [expr.const]p3 with proposed wording fixes:
4910 // A converted constant expression of type T is a core constant expression,
4911 // implicitly converted to a prvalue of type T, where the converted
4912 // expression is a literal constant expression and the implicit conversion
4913 // sequence contains only user-defined conversions, lvalue-to-rvalue
4914 // conversions, integral promotions, and integral conversions other than
4915 // narrowing conversions.
4916 ImplicitConversionSequence ICS =
4917 TryImplicitConversion(From, T,
4918 /*SuppressUserConversions=*/false,
4919 /*AllowExplicit=*/false,
4920 /*InOverloadResolution=*/false,
4921 /*CStyle=*/false,
4922 /*AllowObjcWritebackConversion=*/false);
4923 StandardConversionSequence *SCS = 0;
4924 switch (ICS.getKind()) {
4925 case ImplicitConversionSequence::StandardConversion:
4926 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004927 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004928 diag::err_typecheck_converted_constant_expression_disallowed)
4929 << From->getType() << From->getSourceRange() << T;
4930 SCS = &ICS.Standard;
4931 break;
4932 case ImplicitConversionSequence::UserDefinedConversion:
4933 // We are converting from class type to an integral or enumeration type, so
4934 // the Before sequence must be trivial.
4935 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004936 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004937 diag::err_typecheck_converted_constant_expression_disallowed)
4938 << From->getType() << From->getSourceRange() << T;
4939 SCS = &ICS.UserDefined.After;
4940 break;
4941 case ImplicitConversionSequence::AmbiguousConversion:
4942 case ImplicitConversionSequence::BadConversion:
4943 if (!DiagnoseMultipleUserDefinedConversion(From, T))
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)
4946 << From->getType() << From->getSourceRange() << T;
4947 return ExprError();
4948
4949 case ImplicitConversionSequence::EllipsisConversion:
4950 llvm_unreachable("ellipsis conversion in converted constant expression");
4951 }
4952
4953 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4954 if (Result.isInvalid())
4955 return Result;
4956
4957 // Check for a narrowing implicit conversion.
4958 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004959 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004960 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4961 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004962 case NK_Variable_Narrowing:
4963 // Implicit conversion to a narrower type, and the value is not a constant
4964 // expression. We'll diagnose this in a moment.
4965 case NK_Not_Narrowing:
4966 break;
4967
4968 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004969 Diag(From->getLocStart(),
4970 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4971 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004972 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004973 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004974 break;
4975
4976 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004977 Diag(From->getLocStart(),
4978 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4979 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004980 << CCE << /*Constant*/0 << From->getType() << T;
4981 break;
4982 }
4983
4984 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004985 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00004986 Expr::EvalResult Eval;
4987 Eval.Diag = &Notes;
4988
Douglas Gregor484f6fa2013-04-08 23:24:07 +00004989 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004990 // The expression can't be folded, so we can't keep it at this position in
4991 // the AST.
4992 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004993 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004994 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004995
4996 if (Notes.empty()) {
4997 // It's a constant expression.
4998 return Result;
4999 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005000 }
5001
5002 // It's not a constant expression. Produce an appropriate diagnostic.
5003 if (Notes.size() == 1 &&
5004 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5005 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5006 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005007 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005008 << CCE << From->getSourceRange();
5009 for (unsigned I = 0; I < Notes.size(); ++I)
5010 Diag(Notes[I].first, Notes[I].second);
5011 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005012 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005013}
5014
John McCall0bcc9bc2011-09-09 06:11:02 +00005015/// dropPointerConversions - If the given standard conversion sequence
5016/// involves any pointer conversions, remove them. This may change
5017/// the result type of the conversion sequence.
5018static void dropPointerConversion(StandardConversionSequence &SCS) {
5019 if (SCS.Second == ICK_Pointer_Conversion) {
5020 SCS.Second = ICK_Identity;
5021 SCS.Third = ICK_Identity;
5022 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5023 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005024}
John McCall120d63c2010-08-24 20:38:10 +00005025
John McCall0bcc9bc2011-09-09 06:11:02 +00005026/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5027/// convert the expression From to an Objective-C pointer type.
5028static ImplicitConversionSequence
5029TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5030 // Do an implicit conversion to 'id'.
5031 QualType Ty = S.Context.getObjCIdType();
5032 ImplicitConversionSequence ICS
5033 = TryImplicitConversion(S, From, Ty,
5034 // FIXME: Are these flags correct?
5035 /*SuppressUserConversions=*/false,
5036 /*AllowExplicit=*/true,
5037 /*InOverloadResolution=*/false,
5038 /*CStyle=*/false,
5039 /*AllowObjCWritebackConversion=*/false);
5040
5041 // Strip off any final conversions to 'id'.
5042 switch (ICS.getKind()) {
5043 case ImplicitConversionSequence::BadConversion:
5044 case ImplicitConversionSequence::AmbiguousConversion:
5045 case ImplicitConversionSequence::EllipsisConversion:
5046 break;
5047
5048 case ImplicitConversionSequence::UserDefinedConversion:
5049 dropPointerConversion(ICS.UserDefined.After);
5050 break;
5051
5052 case ImplicitConversionSequence::StandardConversion:
5053 dropPointerConversion(ICS.Standard);
5054 break;
5055 }
5056
5057 return ICS;
5058}
5059
5060/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5061/// conversion of the expression From to an Objective-C pointer type.
5062ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005063 if (checkPlaceholderForOverload(*this, From))
5064 return ExprError();
5065
John McCallc12c5bb2010-05-15 11:32:37 +00005066 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005067 ImplicitConversionSequence ICS =
5068 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005069 if (!ICS.isBad())
5070 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005071 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005072}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005073
Richard Smithf39aec12012-02-04 07:07:42 +00005074/// Determine whether the provided type is an integral type, or an enumeration
5075/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005076bool Sema::ICEConvertDiagnoser::match(QualType T) {
5077 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5078 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005079}
5080
Larisse Voufo50b60b32013-06-10 06:50:24 +00005081static ExprResult
5082diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5083 Sema::ContextualImplicitConverter &Converter,
5084 QualType T, UnresolvedSetImpl &ViableConversions) {
5085
5086 if (Converter.Suppress)
5087 return ExprError();
5088
5089 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5090 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5091 CXXConversionDecl *Conv =
5092 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5093 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5094 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5095 }
5096 return SemaRef.Owned(From);
5097}
5098
5099static bool
5100diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5101 Sema::ContextualImplicitConverter &Converter,
5102 QualType T, bool HadMultipleCandidates,
5103 UnresolvedSetImpl &ExplicitConversions) {
5104 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5105 DeclAccessPair Found = ExplicitConversions[0];
5106 CXXConversionDecl *Conversion =
5107 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5108
5109 // The user probably meant to invoke the given explicit
5110 // conversion; use it.
5111 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5112 std::string TypeStr;
5113 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5114
5115 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5116 << FixItHint::CreateInsertion(From->getLocStart(),
5117 "static_cast<" + TypeStr + ">(")
5118 << FixItHint::CreateInsertion(
5119 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5120 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5121
5122 // If we aren't in a SFINAE context, build a call to the
5123 // explicit conversion function.
5124 if (SemaRef.isSFINAEContext())
5125 return true;
5126
5127 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5128 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5129 HadMultipleCandidates);
5130 if (Result.isInvalid())
5131 return true;
5132 // Record usage of conversion in an implicit cast.
5133 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5134 CK_UserDefinedConversion, Result.get(), 0,
5135 Result.get()->getValueKind());
5136 }
5137 return false;
5138}
5139
5140static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5141 Sema::ContextualImplicitConverter &Converter,
5142 QualType T, bool HadMultipleCandidates,
5143 DeclAccessPair &Found) {
5144 CXXConversionDecl *Conversion =
5145 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5146 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5147
5148 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5149 if (!Converter.SuppressConversion) {
5150 if (SemaRef.isSFINAEContext())
5151 return true;
5152
5153 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5154 << From->getSourceRange();
5155 }
5156
5157 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5158 HadMultipleCandidates);
5159 if (Result.isInvalid())
5160 return true;
5161 // Record usage of conversion in an implicit cast.
5162 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5163 CK_UserDefinedConversion, Result.get(), 0,
5164 Result.get()->getValueKind());
5165 return false;
5166}
5167
5168static ExprResult finishContextualImplicitConversion(
5169 Sema &SemaRef, SourceLocation Loc, Expr *From,
5170 Sema::ContextualImplicitConverter &Converter) {
5171 if (!Converter.match(From->getType()) && !Converter.Suppress)
5172 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5173 << From->getSourceRange();
5174
5175 return SemaRef.DefaultLvalueConversion(From);
5176}
5177
5178static void
5179collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5180 UnresolvedSetImpl &ViableConversions,
5181 OverloadCandidateSet &CandidateSet) {
5182 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5183 DeclAccessPair FoundDecl = ViableConversions[I];
5184 NamedDecl *D = FoundDecl.getDecl();
5185 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5186 if (isa<UsingShadowDecl>(D))
5187 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5188
5189 CXXConversionDecl *Conv;
5190 FunctionTemplateDecl *ConvTemplate;
5191 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5192 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5193 else
5194 Conv = cast<CXXConversionDecl>(D);
5195
5196 if (ConvTemplate)
5197 SemaRef.AddTemplateConversionCandidate(
5198 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5199 else
5200 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5201 ToType, CandidateSet);
5202 }
5203}
5204
Richard Smith097e0a22013-05-21 19:05:48 +00005205/// \brief Attempt to convert the given expression to a type which is accepted
5206/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005207///
Richard Smith097e0a22013-05-21 19:05:48 +00005208/// This routine will attempt to convert an expression of class type to a
5209/// type accepted by the specified converter. In C++11 and before, the class
5210/// must have a single non-explicit conversion function converting to a matching
5211/// type. In C++1y, there can be multiple such conversion functions, but only
5212/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005213///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005214/// \param Loc The source location of the construct that requires the
5215/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005216///
James Dennett40ae6662012-06-22 08:52:37 +00005217/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005218///
Richard Smith097e0a22013-05-21 19:05:48 +00005219/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005220///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005221/// \returns The expression, converted to an integral or enumeration type if
5222/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005223ExprResult Sema::PerformContextualImplicitConversion(
5224 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005225 // We can't perform any more checking for type-dependent expressions.
5226 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005227 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005228
Eli Friedmanceccab92012-01-26 00:26:18 +00005229 // Process placeholders immediately.
5230 if (From->hasPlaceholderType()) {
5231 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005232 if (result.isInvalid())
5233 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005234 From = result.take();
5235 }
5236
Richard Smith097e0a22013-05-21 19:05:48 +00005237 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005238 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005239 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005240 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005241
5242 // FIXME: Check for missing '()' if T is a function type?
5243
Richard Smith097e0a22013-05-21 19:05:48 +00005244 // We can only perform contextual implicit conversions on objects of class
5245 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005246 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005247 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005248 if (!Converter.Suppress)
5249 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005250 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005251 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005252
Douglas Gregorc30614b2010-06-29 23:17:37 +00005253 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005254 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005255 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005256 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005257
5258 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5259 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5260
Douglas Gregord10099e2012-05-04 16:32:21 +00005261 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005262 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005263 }
Richard Smith097e0a22013-05-21 19:05:48 +00005264 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005265
5266 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005267 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005268
Douglas Gregorc30614b2010-06-29 23:17:37 +00005269 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005270 UnresolvedSet<4>
5271 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005272 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005273 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005274 CXXRecordDecl::conversion_iterator> Conversions =
5275 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005276
Larisse Voufo50b60b32013-06-10 06:50:24 +00005277 bool HadMultipleCandidates =
5278 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005279
Larisse Voufo50b60b32013-06-10 06:50:24 +00005280 // To check that there is only one target type, in C++1y:
5281 QualType ToType;
5282 bool HasUniqueTargetType = true;
5283
5284 // Collect explicit or viable (potentially in C++1y) conversions.
5285 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5286 E = Conversions.second;
5287 I != E; ++I) {
5288 NamedDecl *D = (*I)->getUnderlyingDecl();
5289 CXXConversionDecl *Conversion;
5290 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5291 if (ConvTemplate) {
5292 if (getLangOpts().CPlusPlus1y)
5293 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5294 else
5295 continue; // C++11 does not consider conversion operator templates(?).
5296 } else
5297 Conversion = cast<CXXConversionDecl>(D);
5298
5299 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5300 "Conversion operator templates are considered potentially "
5301 "viable in C++1y");
5302
5303 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5304 if (Converter.match(CurToType) || ConvTemplate) {
5305
5306 if (Conversion->isExplicit()) {
5307 // FIXME: For C++1y, do we need this restriction?
5308 // cf. diagnoseNoViableConversion()
5309 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005310 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005311 } else {
5312 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5313 if (ToType.isNull())
5314 ToType = CurToType.getUnqualifiedType();
5315 else if (HasUniqueTargetType &&
5316 (CurToType.getUnqualifiedType() != ToType))
5317 HasUniqueTargetType = false;
5318 }
5319 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005320 }
Richard Smithf39aec12012-02-04 07:07:42 +00005321 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005322 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005323
Larisse Voufo50b60b32013-06-10 06:50:24 +00005324 if (getLangOpts().CPlusPlus1y) {
5325 // C++1y [conv]p6:
5326 // ... An expression e of class type E appearing in such a context
5327 // is said to be contextually implicitly converted to a specified
5328 // type T and is well-formed if and only if e can be implicitly
5329 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005330 // for conversion functions whose return type is cv T or reference to
5331 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005332 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005333
Larisse Voufo50b60b32013-06-10 06:50:24 +00005334 // If no unique T is found:
5335 if (ToType.isNull()) {
5336 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5337 HadMultipleCandidates,
5338 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005339 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005340 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005341 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005342
Larisse Voufo50b60b32013-06-10 06:50:24 +00005343 // If more than one unique Ts are found:
5344 if (!HasUniqueTargetType)
5345 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5346 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005347
Larisse Voufo50b60b32013-06-10 06:50:24 +00005348 // If one unique T is found:
5349 // First, build a candidate set from the previously recorded
5350 // potentially viable conversions.
5351 OverloadCandidateSet CandidateSet(Loc);
5352 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5353 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005354
Larisse Voufo50b60b32013-06-10 06:50:24 +00005355 // Then, perform overload resolution over the candidate set.
5356 OverloadCandidateSet::iterator Best;
5357 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5358 case OR_Success: {
5359 // Apply this conversion.
5360 DeclAccessPair Found =
5361 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5362 if (recordConversion(*this, Loc, From, Converter, T,
5363 HadMultipleCandidates, Found))
5364 return ExprError();
5365 break;
5366 }
5367 case OR_Ambiguous:
5368 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5369 ViableConversions);
5370 case OR_No_Viable_Function:
5371 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5372 HadMultipleCandidates,
5373 ExplicitConversions))
5374 return ExprError();
5375 // fall through 'OR_Deleted' case.
5376 case OR_Deleted:
5377 // We'll complain below about a non-integral condition type.
5378 break;
5379 }
5380 } else {
5381 switch (ViableConversions.size()) {
5382 case 0: {
5383 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5384 HadMultipleCandidates,
5385 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005386 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005387
Larisse Voufo50b60b32013-06-10 06:50:24 +00005388 // We'll complain below about a non-integral condition type.
5389 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005390 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005391 case 1: {
5392 // Apply this conversion.
5393 DeclAccessPair Found = ViableConversions[0];
5394 if (recordConversion(*this, Loc, From, Converter, T,
5395 HadMultipleCandidates, Found))
5396 return ExprError();
5397 break;
5398 }
5399 default:
5400 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5401 ViableConversions);
5402 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005404
Larisse Voufo50b60b32013-06-10 06:50:24 +00005405 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005406}
5407
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005408/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005409/// candidate functions, using the given function call arguments. If
5410/// @p SuppressUserConversions, then don't allow user-defined
5411/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005412///
James Dennett699c9042012-06-15 07:13:21 +00005413/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005414/// based on an incomplete set of function arguments. This feature is used by
5415/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005416void
5417Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005418 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005419 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005420 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005421 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005422 bool PartialOverloading,
5423 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005424 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005425 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005426 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005427 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005428 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005429
Douglas Gregor88a35142008-12-22 05:46:06 +00005430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005431 if (!isa<CXXConstructorDecl>(Method)) {
5432 // If we get here, it's because we're calling a member function
5433 // that is named without a member access expression (e.g.,
5434 // "this->f") that was either written explicitly or created
5435 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005436 // function, e.g., X::f(). We use an empty type for the implied
5437 // object argument (C++ [over.call.func]p3), and the acting context
5438 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005439 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005440 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005441 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005442 return;
5443 }
5444 // We treat a constructor like a non-member function, since its object
5445 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005446 }
5447
Douglas Gregorfd476482009-11-13 23:59:09 +00005448 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005449 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005450
Douglas Gregor7edfb692009-11-23 12:27:39 +00005451 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005452 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005453
Douglas Gregor66724ea2009-11-14 01:20:54 +00005454 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5455 // C++ [class.copy]p3:
5456 // A member function template is never instantiated to perform the copy
5457 // of a class object to an object of its class type.
5458 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005459 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005460 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005461 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5462 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005463 return;
5464 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005465
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005466 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005467 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005468 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005469 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005470 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005471 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005472 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005473 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005474
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005475 unsigned NumArgsInProto = Proto->getNumArgs();
5476
5477 // (C++ 13.3.2p2): A candidate function having fewer than m
5478 // parameters is viable only if it has an ellipsis in its parameter
5479 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005480 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005481 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005482 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005483 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005484 return;
5485 }
5486
5487 // (C++ 13.3.2p2): A candidate function having more than m parameters
5488 // is viable only if the (m+1)st parameter has a default argument
5489 // (8.3.6). For the purposes of overload resolution, the
5490 // parameter list is truncated on the right, so that there are
5491 // exactly m parameters.
5492 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005493 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005494 // Not enough arguments.
5495 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005496 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005497 return;
5498 }
5499
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005500 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005501 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005502 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5503 if (CheckCUDATarget(Caller, Function)) {
5504 Candidate.Viable = false;
5505 Candidate.FailureKind = ovl_fail_bad_target;
5506 return;
5507 }
5508
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005509 // Determine the implicit conversion sequences for each of the
5510 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005511 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005512 if (ArgIdx < NumArgsInProto) {
5513 // (C++ 13.3.2p3): for F to be a viable function, there shall
5514 // exist for each argument an implicit conversion sequence
5515 // (13.3.3.1) that converts that argument to the corresponding
5516 // parameter of F.
5517 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005518 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005519 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005520 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005521 /*InOverloadResolution=*/true,
5522 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005523 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005524 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005525 if (Candidate.Conversions[ArgIdx].isBad()) {
5526 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005527 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005528 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005529 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005530 } else {
5531 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5532 // argument for which there is no corresponding parameter is
5533 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005534 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005535 }
5536 }
5537}
5538
Douglas Gregor063daf62009-03-13 18:40:31 +00005539/// \brief Add all of the function declarations in the given function set to
5540/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005541void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005542 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005543 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005544 bool SuppressUserConversions,
5545 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005546 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005547 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005549 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005550 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005551 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005552 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005553 Args.slice(1), CandidateSet,
5554 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005555 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005556 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005557 SuppressUserConversions);
5558 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005559 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005560 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5561 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005562 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005563 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005564 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005565 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005566 Args[0]->Classify(Context), Args.slice(1),
5567 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005568 else
John McCall9aa472c2010-03-19 07:35:19 +00005569 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005570 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005571 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005572 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005573 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005574}
5575
John McCall314be4e2009-11-17 07:50:12 +00005576/// AddMethodCandidate - Adds a named decl (which is some kind of
5577/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005578void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005579 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005580 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005581 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005582 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005583 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005584 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005585 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005586
5587 if (isa<UsingShadowDecl>(Decl))
5588 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005589
John McCall314be4e2009-11-17 07:50:12 +00005590 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5591 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5592 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005593 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5594 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005595 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005596 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005597 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005598 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005599 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005600 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005601 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005602 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005603 }
5604}
5605
Douglas Gregor96176b32008-11-18 23:14:02 +00005606/// AddMethodCandidate - Adds the given C++ member function to the set
5607/// of candidate functions, using the given function call arguments
5608/// and the object argument (@c Object). For example, in a call
5609/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5610/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5611/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005612/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005613void
John McCall9aa472c2010-03-19 07:35:19 +00005614Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005615 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005616 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005617 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005618 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005619 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005620 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005621 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005622 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005623 assert(!isa<CXXConstructorDecl>(Method) &&
5624 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005625
Douglas Gregor3f396022009-09-28 04:47:19 +00005626 if (!CandidateSet.isNewCandidate(Method))
5627 return;
5628
Douglas Gregor7edfb692009-11-23 12:27:39 +00005629 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005630 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005631
Douglas Gregor96176b32008-11-18 23:14:02 +00005632 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005633 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005634 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005635 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005636 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005637 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005638 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005639
5640 unsigned NumArgsInProto = Proto->getNumArgs();
5641
5642 // (C++ 13.3.2p2): A candidate function having fewer than m
5643 // parameters is viable only if it has an ellipsis in its parameter
5644 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005645 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005646 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005647 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005648 return;
5649 }
5650
5651 // (C++ 13.3.2p2): A candidate function having more than m parameters
5652 // is viable only if the (m+1)st parameter has a default argument
5653 // (8.3.6). For the purposes of overload resolution, the
5654 // parameter list is truncated on the right, so that there are
5655 // exactly m parameters.
5656 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005657 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005658 // Not enough arguments.
5659 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005660 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005661 return;
5662 }
5663
5664 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005665
John McCall701c89e2009-12-03 04:06:58 +00005666 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005667 // The implicit object argument is ignored.
5668 Candidate.IgnoreObjectArgument = true;
5669 else {
5670 // Determine the implicit conversion sequence for the object
5671 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005672 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005673 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5674 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005675 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005676 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005677 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005678 return;
5679 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005680 }
5681
5682 // Determine the implicit conversion sequences for each of the
5683 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005684 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005685 if (ArgIdx < NumArgsInProto) {
5686 // (C++ 13.3.2p3): for F to be a viable function, there shall
5687 // exist for each argument an implicit conversion sequence
5688 // (13.3.3.1) that converts that argument to the corresponding
5689 // parameter of F.
5690 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005691 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005692 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005693 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005694 /*InOverloadResolution=*/true,
5695 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005696 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005697 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005698 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005699 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005700 break;
5701 }
5702 } else {
5703 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5704 // argument for which there is no corresponding parameter is
5705 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005706 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005707 }
5708 }
5709}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005710
Douglas Gregor6b906862009-08-21 00:16:32 +00005711/// \brief Add a C++ member function template as a candidate to the candidate
5712/// set, using template argument deduction to produce an appropriate member
5713/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005714void
Douglas Gregor6b906862009-08-21 00:16:32 +00005715Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005716 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005717 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005718 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005719 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005720 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005721 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005722 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005723 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005724 if (!CandidateSet.isNewCandidate(MethodTmpl))
5725 return;
5726
Douglas Gregor6b906862009-08-21 00:16:32 +00005727 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005728 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005729 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005730 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005731 // candidate functions in the usual way.113) A given name can refer to one
5732 // or more function templates and also to a set of overloaded non-template
5733 // functions. In such a case, the candidate functions generated from each
5734 // function template are combined with the set of non-template candidate
5735 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005736 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005737 FunctionDecl *Specialization = 0;
5738 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005739 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5740 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005741 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005742 Candidate.FoundDecl = FoundDecl;
5743 Candidate.Function = MethodTmpl->getTemplatedDecl();
5744 Candidate.Viable = false;
5745 Candidate.FailureKind = ovl_fail_bad_deduction;
5746 Candidate.IsSurrogate = false;
5747 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005748 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005749 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005750 Info);
5751 return;
5752 }
Mike Stump1eb44332009-09-09 15:08:12 +00005753
Douglas Gregor6b906862009-08-21 00:16:32 +00005754 // Add the function template specialization produced by template argument
5755 // deduction as a candidate.
5756 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005757 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005758 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005759 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005760 ActingContext, ObjectType, ObjectClassification, Args,
5761 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005762}
5763
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005764/// \brief Add a C++ function template specialization as a candidate
5765/// in the candidate set, using template argument deduction to produce
5766/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005767void
Douglas Gregore53060f2009-06-25 22:08:12 +00005768Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005769 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005770 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005771 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005772 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005773 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005774 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5775 return;
5776
Douglas Gregore53060f2009-06-25 22:08:12 +00005777 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005778 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005779 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005780 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005781 // candidate functions in the usual way.113) A given name can refer to one
5782 // or more function templates and also to a set of overloaded non-template
5783 // functions. In such a case, the candidate functions generated from each
5784 // function template are combined with the set of non-template candidate
5785 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005786 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005787 FunctionDecl *Specialization = 0;
5788 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005789 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5790 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005791 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005792 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005793 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5794 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005795 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005796 Candidate.IsSurrogate = false;
5797 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005798 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005799 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005800 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005801 return;
5802 }
Mike Stump1eb44332009-09-09 15:08:12 +00005803
Douglas Gregore53060f2009-06-25 22:08:12 +00005804 // Add the function template specialization produced by template argument
5805 // deduction as a candidate.
5806 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005807 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005808 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005809}
Mike Stump1eb44332009-09-09 15:08:12 +00005810
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005811/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005812/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005813/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005814/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005815/// (which may or may not be the same type as the type that the
5816/// conversion function produces).
5817void
5818Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005819 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005820 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005821 Expr *From, QualType ToType,
5822 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005823 assert(!Conversion->getDescribedFunctionTemplate() &&
5824 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005825 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005826 if (!CandidateSet.isNewCandidate(Conversion))
5827 return;
5828
Richard Smith60e141e2013-05-04 07:00:32 +00005829 // If the conversion function has an undeduced return type, trigger its
5830 // deduction now.
5831 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5832 if (DeduceReturnType(Conversion, From->getExprLoc()))
5833 return;
5834 ConvType = Conversion->getConversionType().getNonReferenceType();
5835 }
5836
Douglas Gregor7edfb692009-11-23 12:27:39 +00005837 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005838 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005839
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005840 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005841 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005842 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005843 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005844 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005845 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005846 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005847 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005848 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005849 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005850 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005851
Douglas Gregorbca39322010-08-19 15:37:02 +00005852 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005853 // For conversion functions, the function is considered to be a member of
5854 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005855 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005856 //
5857 // Determine the implicit conversion sequence for the implicit
5858 // object parameter.
5859 QualType ImplicitParamType = From->getType();
5860 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5861 ImplicitParamType = FromPtrType->getPointeeType();
5862 CXXRecordDecl *ConversionContext
5863 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005865 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005866 = TryObjectArgumentInitialization(*this, From->getType(),
5867 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005868 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005869
John McCall1d318332010-01-12 00:44:57 +00005870 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005871 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005872 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005873 return;
5874 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005875
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005876 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005877 // derived to base as such conversions are given Conversion Rank. They only
5878 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5879 QualType FromCanon
5880 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5881 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5882 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5883 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005884 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005885 return;
5886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005887
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005888 // To determine what the conversion from the result of calling the
5889 // conversion function to the type we're eventually trying to
5890 // convert to (ToType), we need to synthesize a call to the
5891 // conversion function and attempt copy initialization from it. This
5892 // makes sure that we get the right semantics with respect to
5893 // lvalues/rvalues and the type. Fortunately, we can allocate this
5894 // call on the stack and we don't need its arguments to be
5895 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005896 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005897 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005898 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5899 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005900 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005901 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005902
Richard Smith87c1f1f2011-07-13 22:53:21 +00005903 QualType ConversionType = Conversion->getConversionType();
5904 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005905 Candidate.Viable = false;
5906 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5907 return;
5908 }
5909
Richard Smith87c1f1f2011-07-13 22:53:21 +00005910 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005911
Mike Stump1eb44332009-09-09 15:08:12 +00005912 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005913 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5914 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005915 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005916 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005917 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005918 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005919 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005920 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005921 /*InOverloadResolution=*/false,
5922 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005923
John McCall1d318332010-01-12 00:44:57 +00005924 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005925 case ImplicitConversionSequence::StandardConversion:
5926 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005927
Douglas Gregorc520c842010-04-12 23:42:09 +00005928 // C++ [over.ics.user]p3:
5929 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005930 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005931 // shall have exact match rank.
5932 if (Conversion->getPrimaryTemplate() &&
5933 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5934 Candidate.Viable = false;
5935 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5936 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005937
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005938 // C++0x [dcl.init.ref]p5:
5939 // In the second case, if the reference is an rvalue reference and
5940 // the second standard conversion sequence of the user-defined
5941 // conversion sequence includes an lvalue-to-rvalue conversion, the
5942 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005943 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005944 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5945 Candidate.Viable = false;
5946 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5947 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005948 break;
5949
5950 case ImplicitConversionSequence::BadConversion:
5951 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005952 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005953 break;
5954
5955 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005956 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005957 "Can only end up with a standard conversion sequence or failure");
5958 }
5959}
5960
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005961/// \brief Adds a conversion function template specialization
5962/// candidate to the overload set, using template argument deduction
5963/// to deduce the template arguments of the conversion function
5964/// template from the type that we are converting to (C++
5965/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005966void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005967Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005968 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005969 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005970 Expr *From, QualType ToType,
5971 OverloadCandidateSet &CandidateSet) {
5972 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5973 "Only conversion function templates permitted here");
5974
Douglas Gregor3f396022009-09-28 04:47:19 +00005975 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5976 return;
5977
Craig Topper93e45992012-09-19 02:26:47 +00005978 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005979 CXXConversionDecl *Specialization = 0;
5980 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005981 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005982 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005983 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005984 Candidate.FoundDecl = FoundDecl;
5985 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5986 Candidate.Viable = false;
5987 Candidate.FailureKind = ovl_fail_bad_deduction;
5988 Candidate.IsSurrogate = false;
5989 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005990 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005991 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005992 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005993 return;
5994 }
Mike Stump1eb44332009-09-09 15:08:12 +00005995
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005996 // Add the conversion function template specialization produced by
5997 // template argument deduction as a candidate.
5998 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005999 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00006000 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006001}
6002
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006003/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6004/// converts the given @c Object to a function pointer via the
6005/// conversion function @c Conversion, and then attempts to call it
6006/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6007/// the type of function that we'll eventually be calling.
6008void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006009 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006010 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006011 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006012 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006013 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006014 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006015 if (!CandidateSet.isNewCandidate(Conversion))
6016 return;
6017
Douglas Gregor7edfb692009-11-23 12:27:39 +00006018 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006019 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006020
Ahmed Charles13a140c2012-02-25 11:00:22 +00006021 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006022 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006023 Candidate.Function = 0;
6024 Candidate.Surrogate = Conversion;
6025 Candidate.Viable = true;
6026 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006027 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006028 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006029
6030 // Determine the implicit conversion sequence for the implicit
6031 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006032 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006033 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006034 Object->Classify(Context),
6035 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006036 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006037 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006038 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006039 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006040 return;
6041 }
6042
6043 // The first conversion is actually a user-defined conversion whose
6044 // first conversion is ObjectInit's standard conversion (which is
6045 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006046 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006047 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006048 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006049 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006050 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006051 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006052 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006053 = Candidate.Conversions[0].UserDefined.Before;
6054 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6055
Mike Stump1eb44332009-09-09 15:08:12 +00006056 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006057 unsigned NumArgsInProto = Proto->getNumArgs();
6058
6059 // (C++ 13.3.2p2): A candidate function having fewer than m
6060 // parameters is viable only if it has an ellipsis in its parameter
6061 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006062 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006063 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006064 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006065 return;
6066 }
6067
6068 // Function types don't have any default arguments, so just check if
6069 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006070 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006071 // Not enough arguments.
6072 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006073 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006074 return;
6075 }
6076
6077 // Determine the implicit conversion sequences for each of the
6078 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006079 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006080 if (ArgIdx < NumArgsInProto) {
6081 // (C++ 13.3.2p3): for F to be a viable function, there shall
6082 // exist for each argument an implicit conversion sequence
6083 // (13.3.3.1) that converts that argument to the corresponding
6084 // parameter of F.
6085 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006086 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006087 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006088 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006089 /*InOverloadResolution=*/false,
6090 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006091 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006092 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006093 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006094 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006095 break;
6096 }
6097 } else {
6098 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6099 // argument for which there is no corresponding parameter is
6100 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006101 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006102 }
6103 }
6104}
6105
Douglas Gregor063daf62009-03-13 18:40:31 +00006106/// \brief Add overload candidates for overloaded operators that are
6107/// member functions.
6108///
6109/// Add the overloaded operator candidates that are member functions
6110/// for the operator Op that was used in an operator expression such
6111/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6112/// CandidateSet will store the added overload candidates. (C++
6113/// [over.match.oper]).
6114void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6115 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006116 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006117 OverloadCandidateSet& CandidateSet,
6118 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006119 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6120
6121 // C++ [over.match.oper]p3:
6122 // For a unary operator @ with an operand of a type whose
6123 // cv-unqualified version is T1, and for a binary operator @ with
6124 // a left operand of a type whose cv-unqualified version is T1 and
6125 // a right operand of a type whose cv-unqualified version is T2,
6126 // three sets of candidate functions, designated member
6127 // candidates, non-member candidates and built-in candidates, are
6128 // constructed as follows:
6129 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006130
Richard Smithe410be92013-04-20 12:41:22 +00006131 // -- If T1 is a complete class type or a class currently being
6132 // defined, the set of member candidates is the result of the
6133 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6134 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006135 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006136 // Complete the type if it can be completed.
6137 RequireCompleteType(OpLoc, T1, 0);
6138 // If the type is neither complete nor being defined, bail out now.
6139 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006141
John McCalla24dc2e2009-11-17 02:14:36 +00006142 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6143 LookupQualifiedName(Operators, T1Rec->getDecl());
6144 Operators.suppressDiagnostics();
6145
Mike Stump1eb44332009-09-09 15:08:12 +00006146 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006147 OperEnd = Operators.end();
6148 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006149 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006150 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006151 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006152 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006153 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006154 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006155 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006156}
6157
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006158/// AddBuiltinCandidate - Add a candidate for a built-in
6159/// operator. ResultTy and ParamTys are the result and parameter types
6160/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006161/// arguments being passed to the candidate. IsAssignmentOperator
6162/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006163/// operator. NumContextualBoolArguments is the number of arguments
6164/// (at the beginning of the argument list) that will be contextually
6165/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006166void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006167 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006168 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006169 bool IsAssignmentOperator,
6170 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006171 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006172 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006173
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006174 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006175 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006176 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006177 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006178 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006179 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006180 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006181 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006182 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6183
6184 // Determine the implicit conversion sequences for each of the
6185 // arguments.
6186 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006187 Candidate.ExplicitCallArguments = Args.size();
6188 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006189 // C++ [over.match.oper]p4:
6190 // For the built-in assignment operators, conversions of the
6191 // left operand are restricted as follows:
6192 // -- no temporaries are introduced to hold the left operand, and
6193 // -- no user-defined conversions are applied to the left
6194 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006195 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006196 //
6197 // We block these conversions by turning off user-defined
6198 // conversions, since that is the only way that initialization of
6199 // a reference to a non-class type can occur from something that
6200 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006201 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006202 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006203 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006204 Candidate.Conversions[ArgIdx]
6205 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006206 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006207 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006208 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006209 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006210 /*InOverloadResolution=*/false,
6211 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006212 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006213 }
John McCall1d318332010-01-12 00:44:57 +00006214 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006215 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006216 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006217 break;
6218 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006219 }
6220}
6221
Craig Topperfe09f3f2013-07-01 06:29:40 +00006222namespace {
6223
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006224/// BuiltinCandidateTypeSet - A set of types that will be used for the
6225/// candidate operator functions for built-in operators (C++
6226/// [over.built]). The types are separated into pointer types and
6227/// enumeration types.
6228class BuiltinCandidateTypeSet {
6229 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006230 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006231
6232 /// PointerTypes - The set of pointer types that will be used in the
6233 /// built-in candidates.
6234 TypeSet PointerTypes;
6235
Sebastian Redl78eb8742009-04-19 21:53:20 +00006236 /// MemberPointerTypes - The set of member pointer types that will be
6237 /// used in the built-in candidates.
6238 TypeSet MemberPointerTypes;
6239
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006240 /// EnumerationTypes - The set of enumeration types that will be
6241 /// used in the built-in candidates.
6242 TypeSet EnumerationTypes;
6243
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006244 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006245 /// candidates.
6246 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006247
6248 /// \brief A flag indicating non-record types are viable candidates
6249 bool HasNonRecordTypes;
6250
6251 /// \brief A flag indicating whether either arithmetic or enumeration types
6252 /// were present in the candidate set.
6253 bool HasArithmeticOrEnumeralTypes;
6254
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006255 /// \brief A flag indicating whether the nullptr type was present in the
6256 /// candidate set.
6257 bool HasNullPtrType;
6258
Douglas Gregor5842ba92009-08-24 15:23:48 +00006259 /// Sema - The semantic analysis instance where we are building the
6260 /// candidate type set.
6261 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006262
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006263 /// Context - The AST context in which we will build the type sets.
6264 ASTContext &Context;
6265
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006266 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6267 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006268 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006269
6270public:
6271 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006272 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006273
Mike Stump1eb44332009-09-09 15:08:12 +00006274 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006275 : HasNonRecordTypes(false),
6276 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006277 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006278 SemaRef(SemaRef),
6279 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006280
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006281 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006282 SourceLocation Loc,
6283 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006284 bool AllowExplicitConversions,
6285 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006286
6287 /// pointer_begin - First pointer type found;
6288 iterator pointer_begin() { return PointerTypes.begin(); }
6289
Sebastian Redl78eb8742009-04-19 21:53:20 +00006290 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006291 iterator pointer_end() { return PointerTypes.end(); }
6292
Sebastian Redl78eb8742009-04-19 21:53:20 +00006293 /// member_pointer_begin - First member pointer type found;
6294 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6295
6296 /// member_pointer_end - Past the last member pointer type found;
6297 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6298
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006299 /// enumeration_begin - First enumeration type found;
6300 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6301
Sebastian Redl78eb8742009-04-19 21:53:20 +00006302 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006303 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006304
Douglas Gregor26bcf672010-05-19 03:21:00 +00006305 iterator vector_begin() { return VectorTypes.begin(); }
6306 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006307
6308 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6309 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006310 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006311};
6312
Craig Topperfe09f3f2013-07-01 06:29:40 +00006313} // end anonymous namespace
6314
Sebastian Redl78eb8742009-04-19 21:53:20 +00006315/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006316/// the set of pointer types along with any more-qualified variants of
6317/// that type. For example, if @p Ty is "int const *", this routine
6318/// will add "int const *", "int const volatile *", "int const
6319/// restrict *", and "int const volatile restrict *" to the set of
6320/// pointer types. Returns true if the add of @p Ty itself succeeded,
6321/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006322///
6323/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006324bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006325BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6326 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006327
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006328 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006329 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006330 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006331
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006332 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006333 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006334 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006335 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006336 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6337 PointeeTy = PTy->getPointeeType();
6338 buildObjCPtr = true;
6339 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006340 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006341 }
6342
Sebastian Redla9efada2009-11-18 20:39:26 +00006343 // Don't add qualified variants of arrays. For one, they're not allowed
6344 // (the qualifier would sink to the element type), and for another, the
6345 // only overload situation where it matters is subscript or pointer +- int,
6346 // and those shouldn't have qualifier variants anyway.
6347 if (PointeeTy->isArrayType())
6348 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006349
John McCall0953e762009-09-24 19:53:00 +00006350 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006351 bool hasVolatile = VisibleQuals.hasVolatile();
6352 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006353
John McCall0953e762009-09-24 19:53:00 +00006354 // Iterate through all strict supersets of BaseCVR.
6355 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6356 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006357 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006358 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006359
6360 // Skip over restrict if no restrict found anywhere in the types, or if
6361 // the type cannot be restrict-qualified.
6362 if ((CVR & Qualifiers::Restrict) &&
6363 (!hasRestrict ||
6364 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6365 continue;
6366
6367 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006368 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006369
6370 // Build qualified pointer type.
6371 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006372 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006373 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006374 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006375 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6376
6377 // Insert qualified pointer type.
6378 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006379 }
6380
6381 return true;
6382}
6383
Sebastian Redl78eb8742009-04-19 21:53:20 +00006384/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6385/// to the set of pointer types along with any more-qualified variants of
6386/// that type. For example, if @p Ty is "int const *", this routine
6387/// will add "int const *", "int const volatile *", "int const
6388/// restrict *", and "int const volatile restrict *" to the set of
6389/// pointer types. Returns true if the add of @p Ty itself succeeded,
6390/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006391///
6392/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006393bool
6394BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6395 QualType Ty) {
6396 // Insert this type.
6397 if (!MemberPointerTypes.insert(Ty))
6398 return false;
6399
John McCall0953e762009-09-24 19:53:00 +00006400 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6401 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006402
John McCall0953e762009-09-24 19:53:00 +00006403 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006404 // Don't add qualified variants of arrays. For one, they're not allowed
6405 // (the qualifier would sink to the element type), and for another, the
6406 // only overload situation where it matters is subscript or pointer +- int,
6407 // and those shouldn't have qualifier variants anyway.
6408 if (PointeeTy->isArrayType())
6409 return true;
John McCall0953e762009-09-24 19:53:00 +00006410 const Type *ClassTy = PointerTy->getClass();
6411
6412 // Iterate through all strict supersets of the pointee type's CVR
6413 // qualifiers.
6414 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6415 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6416 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006417
John McCall0953e762009-09-24 19:53:00 +00006418 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006419 MemberPointerTypes.insert(
6420 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006421 }
6422
6423 return true;
6424}
6425
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006426/// AddTypesConvertedFrom - Add each of the types to which the type @p
6427/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006428/// primarily interested in pointer types and enumeration types. We also
6429/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006430/// AllowUserConversions is true if we should look at the conversion
6431/// functions of a class type, and AllowExplicitConversions if we
6432/// should also include the explicit conversion functions of a class
6433/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006434void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006435BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006436 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006437 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006438 bool AllowExplicitConversions,
6439 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006440 // Only deal with canonical types.
6441 Ty = Context.getCanonicalType(Ty);
6442
6443 // Look through reference types; they aren't part of the type of an
6444 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006445 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006446 Ty = RefTy->getPointeeType();
6447
John McCall3b657512011-01-19 10:06:00 +00006448 // If we're dealing with an array type, decay to the pointer.
6449 if (Ty->isArrayType())
6450 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6451
6452 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006453 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006454
Chandler Carruth6a577462010-12-13 01:44:01 +00006455 // Flag if we ever add a non-record type.
6456 const RecordType *TyRec = Ty->getAs<RecordType>();
6457 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6458
Chandler Carruth6a577462010-12-13 01:44:01 +00006459 // Flag if we encounter an arithmetic type.
6460 HasArithmeticOrEnumeralTypes =
6461 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6462
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006463 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6464 PointerTypes.insert(Ty);
6465 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006466 // Insert our type, and its more-qualified variants, into the set
6467 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006468 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006469 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006470 } else if (Ty->isMemberPointerType()) {
6471 // Member pointers are far easier, since the pointee can't be converted.
6472 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6473 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006474 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006475 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006476 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006477 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006478 // We treat vector types as arithmetic types in many contexts as an
6479 // extension.
6480 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006481 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006482 } else if (Ty->isNullPtrType()) {
6483 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006484 } else if (AllowUserConversions && TyRec) {
6485 // No conversion functions in incomplete types.
6486 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6487 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006488
Chandler Carruth6a577462010-12-13 01:44:01 +00006489 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006490 std::pair<CXXRecordDecl::conversion_iterator,
6491 CXXRecordDecl::conversion_iterator>
6492 Conversions = ClassDecl->getVisibleConversionFunctions();
6493 for (CXXRecordDecl::conversion_iterator
6494 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006495 NamedDecl *D = I.getDecl();
6496 if (isa<UsingShadowDecl>(D))
6497 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006498
Chandler Carruth6a577462010-12-13 01:44:01 +00006499 // Skip conversion function templates; they don't tell us anything
6500 // about which builtin types we can convert to.
6501 if (isa<FunctionTemplateDecl>(D))
6502 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006503
Chandler Carruth6a577462010-12-13 01:44:01 +00006504 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6505 if (AllowExplicitConversions || !Conv->isExplicit()) {
6506 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6507 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006508 }
6509 }
6510 }
6511}
6512
Douglas Gregor19b7b152009-08-24 13:43:27 +00006513/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6514/// the volatile- and non-volatile-qualified assignment operators for the
6515/// given type to the candidate set.
6516static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6517 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006518 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006519 OverloadCandidateSet &CandidateSet) {
6520 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006521
Douglas Gregor19b7b152009-08-24 13:43:27 +00006522 // T& operator=(T&, T)
6523 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6524 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006525 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006526 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006527
Douglas Gregor19b7b152009-08-24 13:43:27 +00006528 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6529 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006530 ParamTypes[0]
6531 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006532 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006533 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006534 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006535 }
6536}
Mike Stump1eb44332009-09-09 15:08:12 +00006537
Sebastian Redl9994a342009-10-25 17:03:50 +00006538/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6539/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006540static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6541 Qualifiers VRQuals;
6542 const RecordType *TyRec;
6543 if (const MemberPointerType *RHSMPType =
6544 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006545 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006546 else
6547 TyRec = ArgExpr->getType()->getAs<RecordType>();
6548 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006549 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006550 VRQuals.addVolatile();
6551 VRQuals.addRestrict();
6552 return VRQuals;
6553 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006554
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006555 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006556 if (!ClassDecl->hasDefinition())
6557 return VRQuals;
6558
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006559 std::pair<CXXRecordDecl::conversion_iterator,
6560 CXXRecordDecl::conversion_iterator>
6561 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006562
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006563 for (CXXRecordDecl::conversion_iterator
6564 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006565 NamedDecl *D = I.getDecl();
6566 if (isa<UsingShadowDecl>(D))
6567 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6568 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006569 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6570 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6571 CanTy = ResTypeRef->getPointeeType();
6572 // Need to go down the pointer/mempointer chain and add qualifiers
6573 // as see them.
6574 bool done = false;
6575 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006576 if (CanTy.isRestrictQualified())
6577 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006578 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6579 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006580 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006581 CanTy->getAs<MemberPointerType>())
6582 CanTy = ResTypeMPtr->getPointeeType();
6583 else
6584 done = true;
6585 if (CanTy.isVolatileQualified())
6586 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006587 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6588 return VRQuals;
6589 }
6590 }
6591 }
6592 return VRQuals;
6593}
John McCall00071ec2010-11-13 05:51:15 +00006594
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006595namespace {
John McCall00071ec2010-11-13 05:51:15 +00006596
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006597/// \brief Helper class to manage the addition of builtin operator overload
6598/// candidates. It provides shared state and utility methods used throughout
6599/// the process, as well as a helper method to add each group of builtin
6600/// operator overloads from the standard to a candidate set.
6601class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006602 // Common instance state available to all overload candidate addition methods.
6603 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006604 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006605 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006606 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006607 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006608 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006609
Chandler Carruth6d695582010-12-12 10:35:00 +00006610 // Define some constants used to index and iterate over the arithemetic types
6611 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006612 // The "promoted arithmetic types" are the arithmetic
6613 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006614 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006615 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006616 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006617 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006618 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006619 LastPromotedArithmeticType = 11;
6620 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006621
Chandler Carruth6d695582010-12-12 10:35:00 +00006622 /// \brief Get the canonical type for a given arithmetic type index.
6623 CanQualType getArithmeticType(unsigned index) {
6624 assert(index < NumArithmeticTypes);
6625 static CanQualType ASTContext::* const
6626 ArithmeticTypes[NumArithmeticTypes] = {
6627 // Start of promoted types.
6628 &ASTContext::FloatTy,
6629 &ASTContext::DoubleTy,
6630 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006631
Chandler Carruth6d695582010-12-12 10:35:00 +00006632 // Start of integral types.
6633 &ASTContext::IntTy,
6634 &ASTContext::LongTy,
6635 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006636 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006637 &ASTContext::UnsignedIntTy,
6638 &ASTContext::UnsignedLongTy,
6639 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006640 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006641 // End of promoted types.
6642
6643 &ASTContext::BoolTy,
6644 &ASTContext::CharTy,
6645 &ASTContext::WCharTy,
6646 &ASTContext::Char16Ty,
6647 &ASTContext::Char32Ty,
6648 &ASTContext::SignedCharTy,
6649 &ASTContext::ShortTy,
6650 &ASTContext::UnsignedCharTy,
6651 &ASTContext::UnsignedShortTy,
6652 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006653 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006654 };
6655 return S.Context.*ArithmeticTypes[index];
6656 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006657
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006658 /// \brief Gets the canonical type resulting from the usual arithemetic
6659 /// converions for the given arithmetic types.
6660 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6661 // Accelerator table for performing the usual arithmetic conversions.
6662 // The rules are basically:
6663 // - if either is floating-point, use the wider floating-point
6664 // - if same signedness, use the higher rank
6665 // - if same size, use unsigned of the higher rank
6666 // - use the larger type
6667 // These rules, together with the axiom that higher ranks are
6668 // never smaller, are sufficient to precompute all of these results
6669 // *except* when dealing with signed types of higher rank.
6670 // (we could precompute SLL x UI for all known platforms, but it's
6671 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006672 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006673 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006674 Dep=-1,
6675 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006676 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006677 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006678 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006679/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6680/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6681/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6682/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6683/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6684/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6685/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6686/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6687/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6688/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6689/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006690 };
6691
6692 assert(L < LastPromotedArithmeticType);
6693 assert(R < LastPromotedArithmeticType);
6694 int Idx = ConversionsTable[L][R];
6695
6696 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006697 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006698
6699 // Slow path: we need to compare widths.
6700 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006701 CanQualType LT = getArithmeticType(L),
6702 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006703 unsigned LW = S.Context.getIntWidth(LT),
6704 RW = S.Context.getIntWidth(RT);
6705
6706 // If they're different widths, use the signed type.
6707 if (LW > RW) return LT;
6708 else if (LW < RW) return RT;
6709
6710 // Otherwise, use the unsigned type of the signed type's rank.
6711 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6712 assert(L == SLL || R == SLL);
6713 return S.Context.UnsignedLongLongTy;
6714 }
6715
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006716 /// \brief Helper method to factor out the common pattern of adding overloads
6717 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006718 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006719 bool HasVolatile,
6720 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006721 QualType ParamTypes[2] = {
6722 S.Context.getLValueReferenceType(CandidateTy),
6723 S.Context.IntTy
6724 };
6725
6726 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006727 if (Args.size() == 1)
6728 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006729 else
Richard Smith958ba642013-05-05 15:51:06 +00006730 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006731
6732 // Use a heuristic to reduce number of builtin candidates in the set:
6733 // add volatile version only if there are conversions to a volatile type.
6734 if (HasVolatile) {
6735 ParamTypes[0] =
6736 S.Context.getLValueReferenceType(
6737 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006738 if (Args.size() == 1)
6739 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006740 else
Richard Smith958ba642013-05-05 15:51:06 +00006741 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006742 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006743
6744 // Add restrict version only if there are conversions to a restrict type
6745 // and our candidate type is a non-restrict-qualified pointer.
6746 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6747 !CandidateTy.isRestrictQualified()) {
6748 ParamTypes[0]
6749 = S.Context.getLValueReferenceType(
6750 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006751 if (Args.size() == 1)
6752 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006753 else
Richard Smith958ba642013-05-05 15:51:06 +00006754 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006755
6756 if (HasVolatile) {
6757 ParamTypes[0]
6758 = S.Context.getLValueReferenceType(
6759 S.Context.getCVRQualifiedType(CandidateTy,
6760 (Qualifiers::Volatile |
6761 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006762 if (Args.size() == 1)
6763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006764 else
Richard Smith958ba642013-05-05 15:51:06 +00006765 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006766 }
6767 }
6768
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006769 }
6770
6771public:
6772 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006773 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006774 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006775 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006776 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006777 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006778 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006779 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006780 HasArithmeticOrEnumeralCandidateType(
6781 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006782 CandidateTypes(CandidateTypes),
6783 CandidateSet(CandidateSet) {
6784 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006785 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006786 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006787 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006788 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006789 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006790 assert(getArithmeticType(FirstPromotedArithmeticType)
6791 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006792 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006793 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006794 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006795 "Invalid last promoted arithmetic type");
6796 }
6797
6798 // C++ [over.built]p3:
6799 //
6800 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6801 // is either volatile or empty, there exist candidate operator
6802 // functions of the form
6803 //
6804 // VQ T& operator++(VQ T&);
6805 // T operator++(VQ T&, int);
6806 //
6807 // C++ [over.built]p4:
6808 //
6809 // For every pair (T, VQ), where T is an arithmetic type other
6810 // than bool, and VQ is either volatile or empty, there exist
6811 // candidate operator functions of the form
6812 //
6813 // VQ T& operator--(VQ T&);
6814 // T operator--(VQ T&, int);
6815 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006816 if (!HasArithmeticOrEnumeralCandidateType)
6817 return;
6818
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006819 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6820 Arith < NumArithmeticTypes; ++Arith) {
6821 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006822 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006823 VisibleTypeConversionsQuals.hasVolatile(),
6824 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006825 }
6826 }
6827
6828 // C++ [over.built]p5:
6829 //
6830 // For every pair (T, VQ), where T is a cv-qualified or
6831 // cv-unqualified object type, and VQ is either volatile or
6832 // empty, there exist candidate operator functions of the form
6833 //
6834 // T*VQ& operator++(T*VQ&);
6835 // T*VQ& operator--(T*VQ&);
6836 // T* operator++(T*VQ&, int);
6837 // T* operator--(T*VQ&, int);
6838 void addPlusPlusMinusMinusPointerOverloads() {
6839 for (BuiltinCandidateTypeSet::iterator
6840 Ptr = CandidateTypes[0].pointer_begin(),
6841 PtrEnd = CandidateTypes[0].pointer_end();
6842 Ptr != PtrEnd; ++Ptr) {
6843 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006844 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006845 continue;
6846
6847 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006848 (!(*Ptr).isVolatileQualified() &&
6849 VisibleTypeConversionsQuals.hasVolatile()),
6850 (!(*Ptr).isRestrictQualified() &&
6851 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006852 }
6853 }
6854
6855 // C++ [over.built]p6:
6856 // For every cv-qualified or cv-unqualified object type T, there
6857 // exist candidate operator functions of the form
6858 //
6859 // T& operator*(T*);
6860 //
6861 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006862 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006863 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006864 // T& operator*(T*);
6865 void addUnaryStarPointerOverloads() {
6866 for (BuiltinCandidateTypeSet::iterator
6867 Ptr = CandidateTypes[0].pointer_begin(),
6868 PtrEnd = CandidateTypes[0].pointer_end();
6869 Ptr != PtrEnd; ++Ptr) {
6870 QualType ParamTy = *Ptr;
6871 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006872 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6873 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006874
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006875 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6876 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6877 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006878
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006879 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006880 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006881 }
6882 }
6883
6884 // C++ [over.built]p9:
6885 // For every promoted arithmetic type T, there exist candidate
6886 // operator functions of the form
6887 //
6888 // T operator+(T);
6889 // T operator-(T);
6890 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006891 if (!HasArithmeticOrEnumeralCandidateType)
6892 return;
6893
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006894 for (unsigned Arith = FirstPromotedArithmeticType;
6895 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006896 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006897 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006898 }
6899
6900 // Extension: We also add these operators for vector types.
6901 for (BuiltinCandidateTypeSet::iterator
6902 Vec = CandidateTypes[0].vector_begin(),
6903 VecEnd = CandidateTypes[0].vector_end();
6904 Vec != VecEnd; ++Vec) {
6905 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006906 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006907 }
6908 }
6909
6910 // C++ [over.built]p8:
6911 // For every type T, there exist candidate operator functions of
6912 // the form
6913 //
6914 // T* operator+(T*);
6915 void addUnaryPlusPointerOverloads() {
6916 for (BuiltinCandidateTypeSet::iterator
6917 Ptr = CandidateTypes[0].pointer_begin(),
6918 PtrEnd = CandidateTypes[0].pointer_end();
6919 Ptr != PtrEnd; ++Ptr) {
6920 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006921 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006922 }
6923 }
6924
6925 // C++ [over.built]p10:
6926 // For every promoted integral type T, there exist candidate
6927 // operator functions of the form
6928 //
6929 // T operator~(T);
6930 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006931 if (!HasArithmeticOrEnumeralCandidateType)
6932 return;
6933
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006934 for (unsigned Int = FirstPromotedIntegralType;
6935 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006936 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006937 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006938 }
6939
6940 // Extension: We also add this operator for vector types.
6941 for (BuiltinCandidateTypeSet::iterator
6942 Vec = CandidateTypes[0].vector_begin(),
6943 VecEnd = CandidateTypes[0].vector_end();
6944 Vec != VecEnd; ++Vec) {
6945 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006946 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006947 }
6948 }
6949
6950 // C++ [over.match.oper]p16:
6951 // For every pointer to member type T, there exist candidate operator
6952 // functions of the form
6953 //
6954 // bool operator==(T,T);
6955 // bool operator!=(T,T);
6956 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6957 /// Set of (canonical) types that we've already handled.
6958 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6959
Richard Smith958ba642013-05-05 15:51:06 +00006960 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006961 for (BuiltinCandidateTypeSet::iterator
6962 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6963 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6964 MemPtr != MemPtrEnd;
6965 ++MemPtr) {
6966 // Don't add the same builtin candidate twice.
6967 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6968 continue;
6969
6970 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006971 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006972 }
6973 }
6974 }
6975
6976 // C++ [over.built]p15:
6977 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006978 // For every T, where T is an enumeration type, a pointer type, or
6979 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006980 //
6981 // bool operator<(T, T);
6982 // bool operator>(T, T);
6983 // bool operator<=(T, T);
6984 // bool operator>=(T, T);
6985 // bool operator==(T, T);
6986 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006987 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006988 // C++ [over.match.oper]p3:
6989 // [...]the built-in candidates include all of the candidate operator
6990 // functions defined in 13.6 that, compared to the given operator, [...]
6991 // do not have the same parameter-type-list as any non-template non-member
6992 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006993 //
Eli Friedman97c67392012-09-18 21:52:24 +00006994 // Note that in practice, this only affects enumeration types because there
6995 // aren't any built-in candidates of record type, and a user-defined operator
6996 // must have an operand of record or enumeration type. Also, the only other
6997 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006998 // cannot be overloaded for enumeration types, so this is the only place
6999 // where we must suppress candidates like this.
7000 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7001 UserDefinedBinaryOperators;
7002
Richard Smith958ba642013-05-05 15:51:06 +00007003 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007004 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7005 CandidateTypes[ArgIdx].enumeration_end()) {
7006 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7007 CEnd = CandidateSet.end();
7008 C != CEnd; ++C) {
7009 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7010 continue;
7011
Eli Friedman97c67392012-09-18 21:52:24 +00007012 if (C->Function->isFunctionTemplateSpecialization())
7013 continue;
7014
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007015 QualType FirstParamType =
7016 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7017 QualType SecondParamType =
7018 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7019
7020 // Skip if either parameter isn't of enumeral type.
7021 if (!FirstParamType->isEnumeralType() ||
7022 !SecondParamType->isEnumeralType())
7023 continue;
7024
7025 // Add this operator to the set of known user-defined operators.
7026 UserDefinedBinaryOperators.insert(
7027 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7028 S.Context.getCanonicalType(SecondParamType)));
7029 }
7030 }
7031 }
7032
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007033 /// Set of (canonical) types that we've already handled.
7034 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7035
Richard Smith958ba642013-05-05 15:51:06 +00007036 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007037 for (BuiltinCandidateTypeSet::iterator
7038 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7039 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7040 Ptr != PtrEnd; ++Ptr) {
7041 // Don't add the same builtin candidate twice.
7042 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7043 continue;
7044
7045 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007046 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007047 }
7048 for (BuiltinCandidateTypeSet::iterator
7049 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7050 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7051 Enum != EnumEnd; ++Enum) {
7052 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7053
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007054 // Don't add the same builtin candidate twice, or if a user defined
7055 // candidate exists.
7056 if (!AddedTypes.insert(CanonType) ||
7057 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7058 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007059 continue;
7060
7061 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007062 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007063 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007064
7065 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7066 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7067 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007068 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007069 NullPtrTy))) {
7070 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007071 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007072 CandidateSet);
7073 }
7074 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007075 }
7076 }
7077
7078 // C++ [over.built]p13:
7079 //
7080 // For every cv-qualified or cv-unqualified object type T
7081 // there exist candidate operator functions of the form
7082 //
7083 // T* operator+(T*, ptrdiff_t);
7084 // T& operator[](T*, ptrdiff_t); [BELOW]
7085 // T* operator-(T*, ptrdiff_t);
7086 // T* operator+(ptrdiff_t, T*);
7087 // T& operator[](ptrdiff_t, T*); [BELOW]
7088 //
7089 // C++ [over.built]p14:
7090 //
7091 // For every T, where T is a pointer to object type, there
7092 // exist candidate operator functions of the form
7093 //
7094 // ptrdiff_t operator-(T, T);
7095 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7096 /// Set of (canonical) types that we've already handled.
7097 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7098
7099 for (int Arg = 0; Arg < 2; ++Arg) {
7100 QualType AsymetricParamTypes[2] = {
7101 S.Context.getPointerDiffType(),
7102 S.Context.getPointerDiffType(),
7103 };
7104 for (BuiltinCandidateTypeSet::iterator
7105 Ptr = CandidateTypes[Arg].pointer_begin(),
7106 PtrEnd = CandidateTypes[Arg].pointer_end();
7107 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007108 QualType PointeeTy = (*Ptr)->getPointeeType();
7109 if (!PointeeTy->isObjectType())
7110 continue;
7111
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007112 AsymetricParamTypes[Arg] = *Ptr;
7113 if (Arg == 0 || Op == OO_Plus) {
7114 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7115 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007116 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007117 }
7118 if (Op == OO_Minus) {
7119 // ptrdiff_t operator-(T, T);
7120 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7121 continue;
7122
7123 QualType ParamTypes[2] = { *Ptr, *Ptr };
7124 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007125 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007126 }
7127 }
7128 }
7129 }
7130
7131 // C++ [over.built]p12:
7132 //
7133 // For every pair of promoted arithmetic types L and R, there
7134 // exist candidate operator functions of the form
7135 //
7136 // LR operator*(L, R);
7137 // LR operator/(L, R);
7138 // LR operator+(L, R);
7139 // LR operator-(L, R);
7140 // bool operator<(L, R);
7141 // bool operator>(L, R);
7142 // bool operator<=(L, R);
7143 // bool operator>=(L, R);
7144 // bool operator==(L, R);
7145 // bool operator!=(L, R);
7146 //
7147 // where LR is the result of the usual arithmetic conversions
7148 // between types L and R.
7149 //
7150 // C++ [over.built]p24:
7151 //
7152 // For every pair of promoted arithmetic types L and R, there exist
7153 // candidate operator functions of the form
7154 //
7155 // LR operator?(bool, L, R);
7156 //
7157 // where LR is the result of the usual arithmetic conversions
7158 // between types L and R.
7159 // Our candidates ignore the first parameter.
7160 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007161 if (!HasArithmeticOrEnumeralCandidateType)
7162 return;
7163
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007164 for (unsigned Left = FirstPromotedArithmeticType;
7165 Left < LastPromotedArithmeticType; ++Left) {
7166 for (unsigned Right = FirstPromotedArithmeticType;
7167 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007168 QualType LandR[2] = { getArithmeticType(Left),
7169 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007170 QualType Result =
7171 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007172 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007173 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007174 }
7175 }
7176
7177 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7178 // conditional operator for vector types.
7179 for (BuiltinCandidateTypeSet::iterator
7180 Vec1 = CandidateTypes[0].vector_begin(),
7181 Vec1End = CandidateTypes[0].vector_end();
7182 Vec1 != Vec1End; ++Vec1) {
7183 for (BuiltinCandidateTypeSet::iterator
7184 Vec2 = CandidateTypes[1].vector_begin(),
7185 Vec2End = CandidateTypes[1].vector_end();
7186 Vec2 != Vec2End; ++Vec2) {
7187 QualType LandR[2] = { *Vec1, *Vec2 };
7188 QualType Result = S.Context.BoolTy;
7189 if (!isComparison) {
7190 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7191 Result = *Vec1;
7192 else
7193 Result = *Vec2;
7194 }
7195
Richard Smith958ba642013-05-05 15:51:06 +00007196 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007197 }
7198 }
7199 }
7200
7201 // C++ [over.built]p17:
7202 //
7203 // For every pair of promoted integral types L and R, there
7204 // exist candidate operator functions of the form
7205 //
7206 // LR operator%(L, R);
7207 // LR operator&(L, R);
7208 // LR operator^(L, R);
7209 // LR operator|(L, R);
7210 // L operator<<(L, R);
7211 // L operator>>(L, R);
7212 //
7213 // where LR is the result of the usual arithmetic conversions
7214 // between types L and R.
7215 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007216 if (!HasArithmeticOrEnumeralCandidateType)
7217 return;
7218
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007219 for (unsigned Left = FirstPromotedIntegralType;
7220 Left < LastPromotedIntegralType; ++Left) {
7221 for (unsigned Right = FirstPromotedIntegralType;
7222 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007223 QualType LandR[2] = { getArithmeticType(Left),
7224 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007225 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7226 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007227 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007228 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007229 }
7230 }
7231 }
7232
7233 // C++ [over.built]p20:
7234 //
7235 // For every pair (T, VQ), where T is an enumeration or
7236 // pointer to member type and VQ is either volatile or
7237 // empty, there exist candidate operator functions of the form
7238 //
7239 // VQ T& operator=(VQ T&, T);
7240 void addAssignmentMemberPointerOrEnumeralOverloads() {
7241 /// Set of (canonical) types that we've already handled.
7242 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7243
7244 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7245 for (BuiltinCandidateTypeSet::iterator
7246 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7247 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7248 Enum != EnumEnd; ++Enum) {
7249 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7250 continue;
7251
Richard Smith958ba642013-05-05 15:51:06 +00007252 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007253 }
7254
7255 for (BuiltinCandidateTypeSet::iterator
7256 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7257 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7258 MemPtr != MemPtrEnd; ++MemPtr) {
7259 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7260 continue;
7261
Richard Smith958ba642013-05-05 15:51:06 +00007262 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007263 }
7264 }
7265 }
7266
7267 // C++ [over.built]p19:
7268 //
7269 // For every pair (T, VQ), where T is any type and VQ is either
7270 // volatile or empty, there exist candidate operator functions
7271 // of the form
7272 //
7273 // T*VQ& operator=(T*VQ&, T*);
7274 //
7275 // C++ [over.built]p21:
7276 //
7277 // For every pair (T, VQ), where T is a cv-qualified or
7278 // cv-unqualified object type and VQ is either volatile or
7279 // empty, there exist candidate operator functions of the form
7280 //
7281 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7282 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7283 void addAssignmentPointerOverloads(bool isEqualOp) {
7284 /// Set of (canonical) types that we've already handled.
7285 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7286
7287 for (BuiltinCandidateTypeSet::iterator
7288 Ptr = CandidateTypes[0].pointer_begin(),
7289 PtrEnd = CandidateTypes[0].pointer_end();
7290 Ptr != PtrEnd; ++Ptr) {
7291 // If this is operator=, keep track of the builtin candidates we added.
7292 if (isEqualOp)
7293 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007294 else if (!(*Ptr)->getPointeeType()->isObjectType())
7295 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007296
7297 // non-volatile version
7298 QualType ParamTypes[2] = {
7299 S.Context.getLValueReferenceType(*Ptr),
7300 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7301 };
Richard Smith958ba642013-05-05 15:51:06 +00007302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007303 /*IsAssigmentOperator=*/ isEqualOp);
7304
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007305 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7306 VisibleTypeConversionsQuals.hasVolatile();
7307 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007308 // volatile version
7309 ParamTypes[0] =
7310 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007311 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007312 /*IsAssigmentOperator=*/isEqualOp);
7313 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007314
7315 if (!(*Ptr).isRestrictQualified() &&
7316 VisibleTypeConversionsQuals.hasRestrict()) {
7317 // restrict version
7318 ParamTypes[0]
7319 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007321 /*IsAssigmentOperator=*/isEqualOp);
7322
7323 if (NeedVolatile) {
7324 // volatile restrict version
7325 ParamTypes[0]
7326 = S.Context.getLValueReferenceType(
7327 S.Context.getCVRQualifiedType(*Ptr,
7328 (Qualifiers::Volatile |
7329 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007330 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007331 /*IsAssigmentOperator=*/isEqualOp);
7332 }
7333 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007334 }
7335
7336 if (isEqualOp) {
7337 for (BuiltinCandidateTypeSet::iterator
7338 Ptr = CandidateTypes[1].pointer_begin(),
7339 PtrEnd = CandidateTypes[1].pointer_end();
7340 Ptr != PtrEnd; ++Ptr) {
7341 // Make sure we don't add the same candidate twice.
7342 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7343 continue;
7344
Chandler Carruth6df868e2010-12-12 08:17:55 +00007345 QualType ParamTypes[2] = {
7346 S.Context.getLValueReferenceType(*Ptr),
7347 *Ptr,
7348 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007349
7350 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007352 /*IsAssigmentOperator=*/true);
7353
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007354 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7355 VisibleTypeConversionsQuals.hasVolatile();
7356 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007357 // volatile version
7358 ParamTypes[0] =
7359 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007360 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7361 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007362 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007363
7364 if (!(*Ptr).isRestrictQualified() &&
7365 VisibleTypeConversionsQuals.hasRestrict()) {
7366 // restrict version
7367 ParamTypes[0]
7368 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007369 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7370 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007371
7372 if (NeedVolatile) {
7373 // volatile restrict version
7374 ParamTypes[0]
7375 = S.Context.getLValueReferenceType(
7376 S.Context.getCVRQualifiedType(*Ptr,
7377 (Qualifiers::Volatile |
7378 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007379 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7380 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007381 }
7382 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007383 }
7384 }
7385 }
7386
7387 // C++ [over.built]p18:
7388 //
7389 // For every triple (L, VQ, R), where L is an arithmetic type,
7390 // VQ is either volatile or empty, and R is a promoted
7391 // arithmetic type, there exist candidate operator functions of
7392 // the form
7393 //
7394 // VQ L& operator=(VQ L&, R);
7395 // VQ L& operator*=(VQ L&, R);
7396 // VQ L& operator/=(VQ L&, R);
7397 // VQ L& operator+=(VQ L&, R);
7398 // VQ L& operator-=(VQ L&, R);
7399 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007400 if (!HasArithmeticOrEnumeralCandidateType)
7401 return;
7402
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007403 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7404 for (unsigned Right = FirstPromotedArithmeticType;
7405 Right < LastPromotedArithmeticType; ++Right) {
7406 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007407 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007408
7409 // Add this built-in operator as a candidate (VQ is empty).
7410 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007411 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007412 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007413 /*IsAssigmentOperator=*/isEqualOp);
7414
7415 // Add this built-in operator as a candidate (VQ is 'volatile').
7416 if (VisibleTypeConversionsQuals.hasVolatile()) {
7417 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007418 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007419 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007420 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007421 /*IsAssigmentOperator=*/isEqualOp);
7422 }
7423 }
7424 }
7425
7426 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7427 for (BuiltinCandidateTypeSet::iterator
7428 Vec1 = CandidateTypes[0].vector_begin(),
7429 Vec1End = CandidateTypes[0].vector_end();
7430 Vec1 != Vec1End; ++Vec1) {
7431 for (BuiltinCandidateTypeSet::iterator
7432 Vec2 = CandidateTypes[1].vector_begin(),
7433 Vec2End = CandidateTypes[1].vector_end();
7434 Vec2 != Vec2End; ++Vec2) {
7435 QualType ParamTypes[2];
7436 ParamTypes[1] = *Vec2;
7437 // Add this built-in operator as a candidate (VQ is empty).
7438 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007439 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007440 /*IsAssigmentOperator=*/isEqualOp);
7441
7442 // Add this built-in operator as a candidate (VQ is 'volatile').
7443 if (VisibleTypeConversionsQuals.hasVolatile()) {
7444 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7445 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007446 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007447 /*IsAssigmentOperator=*/isEqualOp);
7448 }
7449 }
7450 }
7451 }
7452
7453 // C++ [over.built]p22:
7454 //
7455 // For every triple (L, VQ, R), where L is an integral type, VQ
7456 // is either volatile or empty, and R is a promoted integral
7457 // type, there exist candidate operator functions of the form
7458 //
7459 // VQ L& operator%=(VQ L&, R);
7460 // VQ L& operator<<=(VQ L&, R);
7461 // VQ L& operator>>=(VQ L&, R);
7462 // VQ L& operator&=(VQ L&, R);
7463 // VQ L& operator^=(VQ L&, R);
7464 // VQ L& operator|=(VQ L&, R);
7465 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007466 if (!HasArithmeticOrEnumeralCandidateType)
7467 return;
7468
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007469 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7470 for (unsigned Right = FirstPromotedIntegralType;
7471 Right < LastPromotedIntegralType; ++Right) {
7472 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007473 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007474
7475 // Add this built-in operator as a candidate (VQ is empty).
7476 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007477 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007478 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007479 if (VisibleTypeConversionsQuals.hasVolatile()) {
7480 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007481 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007482 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7483 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007484 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007485 }
7486 }
7487 }
7488 }
7489
7490 // C++ [over.operator]p23:
7491 //
7492 // There also exist candidate operator functions of the form
7493 //
7494 // bool operator!(bool);
7495 // bool operator&&(bool, bool);
7496 // bool operator||(bool, bool);
7497 void addExclaimOverload() {
7498 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007499 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007500 /*IsAssignmentOperator=*/false,
7501 /*NumContextualBoolArguments=*/1);
7502 }
7503 void addAmpAmpOrPipePipeOverload() {
7504 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007505 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007506 /*IsAssignmentOperator=*/false,
7507 /*NumContextualBoolArguments=*/2);
7508 }
7509
7510 // C++ [over.built]p13:
7511 //
7512 // For every cv-qualified or cv-unqualified object type T there
7513 // exist candidate operator functions of the form
7514 //
7515 // T* operator+(T*, ptrdiff_t); [ABOVE]
7516 // T& operator[](T*, ptrdiff_t);
7517 // T* operator-(T*, ptrdiff_t); [ABOVE]
7518 // T* operator+(ptrdiff_t, T*); [ABOVE]
7519 // T& operator[](ptrdiff_t, T*);
7520 void addSubscriptOverloads() {
7521 for (BuiltinCandidateTypeSet::iterator
7522 Ptr = CandidateTypes[0].pointer_begin(),
7523 PtrEnd = CandidateTypes[0].pointer_end();
7524 Ptr != PtrEnd; ++Ptr) {
7525 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7526 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007527 if (!PointeeType->isObjectType())
7528 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007529
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007530 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7531
7532 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007533 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007534 }
7535
7536 for (BuiltinCandidateTypeSet::iterator
7537 Ptr = CandidateTypes[1].pointer_begin(),
7538 PtrEnd = CandidateTypes[1].pointer_end();
7539 Ptr != PtrEnd; ++Ptr) {
7540 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7541 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007542 if (!PointeeType->isObjectType())
7543 continue;
7544
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007545 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7546
7547 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007548 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007549 }
7550 }
7551
7552 // C++ [over.built]p11:
7553 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7554 // C1 is the same type as C2 or is a derived class of C2, T is an object
7555 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7556 // there exist candidate operator functions of the form
7557 //
7558 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7559 //
7560 // where CV12 is the union of CV1 and CV2.
7561 void addArrowStarOverloads() {
7562 for (BuiltinCandidateTypeSet::iterator
7563 Ptr = CandidateTypes[0].pointer_begin(),
7564 PtrEnd = CandidateTypes[0].pointer_end();
7565 Ptr != PtrEnd; ++Ptr) {
7566 QualType C1Ty = (*Ptr);
7567 QualType C1;
7568 QualifierCollector Q1;
7569 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7570 if (!isa<RecordType>(C1))
7571 continue;
7572 // heuristic to reduce number of builtin candidates in the set.
7573 // Add volatile/restrict version only if there are conversions to a
7574 // volatile/restrict type.
7575 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7576 continue;
7577 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7578 continue;
7579 for (BuiltinCandidateTypeSet::iterator
7580 MemPtr = CandidateTypes[1].member_pointer_begin(),
7581 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7582 MemPtr != MemPtrEnd; ++MemPtr) {
7583 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7584 QualType C2 = QualType(mptr->getClass(), 0);
7585 C2 = C2.getUnqualifiedType();
7586 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7587 break;
7588 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7589 // build CV12 T&
7590 QualType T = mptr->getPointeeType();
7591 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7592 T.isVolatileQualified())
7593 continue;
7594 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7595 T.isRestrictQualified())
7596 continue;
7597 T = Q1.apply(S.Context, T);
7598 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007599 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007600 }
7601 }
7602 }
7603
7604 // Note that we don't consider the first argument, since it has been
7605 // contextually converted to bool long ago. The candidates below are
7606 // therefore added as binary.
7607 //
7608 // C++ [over.built]p25:
7609 // For every type T, where T is a pointer, pointer-to-member, or scoped
7610 // enumeration type, there exist candidate operator functions of the form
7611 //
7612 // T operator?(bool, T, T);
7613 //
7614 void addConditionalOperatorOverloads() {
7615 /// Set of (canonical) types that we've already handled.
7616 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7617
7618 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7619 for (BuiltinCandidateTypeSet::iterator
7620 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7621 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7622 Ptr != PtrEnd; ++Ptr) {
7623 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7624 continue;
7625
7626 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007627 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007628 }
7629
7630 for (BuiltinCandidateTypeSet::iterator
7631 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7632 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7633 MemPtr != MemPtrEnd; ++MemPtr) {
7634 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7635 continue;
7636
7637 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007638 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007639 }
7640
Richard Smith80ad52f2013-01-02 11:42:31 +00007641 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007642 for (BuiltinCandidateTypeSet::iterator
7643 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7644 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7645 Enum != EnumEnd; ++Enum) {
7646 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7647 continue;
7648
7649 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7650 continue;
7651
7652 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007653 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007654 }
7655 }
7656 }
7657 }
7658};
7659
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007660} // end anonymous namespace
7661
7662/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7663/// operator overloads to the candidate set (C++ [over.built]), based
7664/// on the operator @p Op and the arguments given. For example, if the
7665/// operator is a binary '+', this routine might add "int
7666/// operator+(int, int)" to cover integer addition.
7667void
7668Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7669 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00007670 llvm::ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007671 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007672 // Find all of the types that the arguments can convert to, but only
7673 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007674 // that make use of these types. Also record whether we encounter non-record
7675 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007676 Qualifiers VisibleTypeConversionsQuals;
7677 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007678 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007679 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007680
7681 bool HasNonRecordCandidateType = false;
7682 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007683 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007684 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007685 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7686 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7687 OpLoc,
7688 true,
7689 (Op == OO_Exclaim ||
7690 Op == OO_AmpAmp ||
7691 Op == OO_PipePipe),
7692 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007693 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7694 CandidateTypes[ArgIdx].hasNonRecordTypes();
7695 HasArithmeticOrEnumeralCandidateType =
7696 HasArithmeticOrEnumeralCandidateType ||
7697 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007698 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007699
Chandler Carruth6a577462010-12-13 01:44:01 +00007700 // Exit early when no non-record types have been added to the candidate set
7701 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007702 //
7703 // We can't exit early for !, ||, or &&, since there we have always have
7704 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007705 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007706 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007707 return;
7708
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007709 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007710 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007711 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007712 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007713 CandidateTypes, CandidateSet);
7714
7715 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007716 switch (Op) {
7717 case OO_None:
7718 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007719 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007720
Chandler Carruthabb71842010-12-12 08:51:33 +00007721 case OO_New:
7722 case OO_Delete:
7723 case OO_Array_New:
7724 case OO_Array_Delete:
7725 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007726 llvm_unreachable(
7727 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007728
7729 case OO_Comma:
7730 case OO_Arrow:
7731 // C++ [over.match.oper]p3:
7732 // -- For the operator ',', the unary operator '&', or the
7733 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007734 break;
7735
7736 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007737 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007738 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007739 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007740
7741 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007742 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007743 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007744 } else {
7745 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7746 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7747 }
Douglas Gregor74253732008-11-19 15:42:04 +00007748 break;
7749
Chandler Carruthabb71842010-12-12 08:51:33 +00007750 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007751 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007752 OpBuilder.addUnaryStarPointerOverloads();
7753 else
7754 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7755 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007756
Chandler Carruthabb71842010-12-12 08:51:33 +00007757 case OO_Slash:
7758 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007759 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007760
7761 case OO_PlusPlus:
7762 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007763 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7764 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007765 break;
7766
Douglas Gregor19b7b152009-08-24 13:43:27 +00007767 case OO_EqualEqual:
7768 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007769 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007770 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007771
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007772 case OO_Less:
7773 case OO_Greater:
7774 case OO_LessEqual:
7775 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007776 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007777 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7778 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007779
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007780 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007781 case OO_Caret:
7782 case OO_Pipe:
7783 case OO_LessLess:
7784 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007785 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007786 break;
7787
Chandler Carruthabb71842010-12-12 08:51:33 +00007788 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007789 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007790 // C++ [over.match.oper]p3:
7791 // -- For the operator ',', the unary operator '&', or the
7792 // operator '->', the built-in candidates set is empty.
7793 break;
7794
7795 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7796 break;
7797
7798 case OO_Tilde:
7799 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7800 break;
7801
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007802 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007803 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007804 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007805
7806 case OO_PlusEqual:
7807 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007808 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007809 // Fall through.
7810
7811 case OO_StarEqual:
7812 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007813 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007814 break;
7815
7816 case OO_PercentEqual:
7817 case OO_LessLessEqual:
7818 case OO_GreaterGreaterEqual:
7819 case OO_AmpEqual:
7820 case OO_CaretEqual:
7821 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007822 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007823 break;
7824
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007825 case OO_Exclaim:
7826 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007827 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007828
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007829 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007830 case OO_PipePipe:
7831 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007832 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007833
7834 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007835 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007836 break;
7837
7838 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007839 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007840 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007841
7842 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007843 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007844 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7845 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007846 }
7847}
7848
Douglas Gregorfa047642009-02-04 00:32:51 +00007849/// \brief Add function candidates found via argument-dependent lookup
7850/// to the set of overloading candidates.
7851///
7852/// This routine performs argument-dependent name lookup based on the
7853/// given function name (which may also be an operator name) and adds
7854/// all of the overload candidates found by ADL to the overload
7855/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007856void
Douglas Gregorfa047642009-02-04 00:32:51 +00007857Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007858 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007859 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007860 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007861 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007862 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007863 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007864
John McCalla113e722010-01-26 06:04:06 +00007865 // FIXME: This approach for uniquing ADL results (and removing
7866 // redundant candidates from the set) relies on pointer-equality,
7867 // which means we need to key off the canonical decl. However,
7868 // always going back to the canonical decl might not get us the
7869 // right set of default arguments. What default arguments are
7870 // we supposed to consider on ADL candidates, anyway?
7871
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007872 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007873 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007874
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007875 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007876 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7877 CandEnd = CandidateSet.end();
7878 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007879 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007880 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007881 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007882 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007883 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007884
7885 // For each of the ADL candidates we found, add it to the overload
7886 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007887 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007888 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007889 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007890 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007891 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007892
Ahmed Charles13a140c2012-02-25 11:00:22 +00007893 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7894 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007895 } else
John McCall6e266892010-01-26 03:27:55 +00007896 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007897 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007898 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007899 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007900}
7901
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007902/// isBetterOverloadCandidate - Determines whether the first overload
7903/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007904bool
John McCall120d63c2010-08-24 20:38:10 +00007905isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007906 const OverloadCandidate &Cand1,
7907 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007908 SourceLocation Loc,
7909 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007910 // Define viable functions to be better candidates than non-viable
7911 // functions.
7912 if (!Cand2.Viable)
7913 return Cand1.Viable;
7914 else if (!Cand1.Viable)
7915 return false;
7916
Douglas Gregor88a35142008-12-22 05:46:06 +00007917 // C++ [over.match.best]p1:
7918 //
7919 // -- if F is a static member function, ICS1(F) is defined such
7920 // that ICS1(F) is neither better nor worse than ICS1(G) for
7921 // any function G, and, symmetrically, ICS1(G) is neither
7922 // better nor worse than ICS1(F).
7923 unsigned StartArg = 0;
7924 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7925 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007926
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007927 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007928 // A viable function F1 is defined to be a better function than another
7929 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007930 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007931 unsigned NumArgs = Cand1.NumConversions;
7932 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007933 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007934 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007935 switch (CompareImplicitConversionSequences(S,
7936 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007937 Cand2.Conversions[ArgIdx])) {
7938 case ImplicitConversionSequence::Better:
7939 // Cand1 has a better conversion sequence.
7940 HasBetterConversion = true;
7941 break;
7942
7943 case ImplicitConversionSequence::Worse:
7944 // Cand1 can't be better than Cand2.
7945 return false;
7946
7947 case ImplicitConversionSequence::Indistinguishable:
7948 // Do nothing.
7949 break;
7950 }
7951 }
7952
Mike Stump1eb44332009-09-09 15:08:12 +00007953 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007954 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007955 if (HasBetterConversion)
7956 return true;
7957
Mike Stump1eb44332009-09-09 15:08:12 +00007958 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007959 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007960 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007961 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7962 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007963
7964 // -- F1 and F2 are function template specializations, and the function
7965 // template for F1 is more specialized than the template for F2
7966 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007967 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007968 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007969 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007970 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007971 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7972 Cand2.Function->getPrimaryTemplate(),
7973 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007974 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007975 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007976 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007977 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007978 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007979
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007980 // -- the context is an initialization by user-defined conversion
7981 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7982 // from the return type of F1 to the destination type (i.e.,
7983 // the type of the entity being initialized) is a better
7984 // conversion sequence than the standard conversion sequence
7985 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007986 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007987 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007988 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007989 // First check whether we prefer one of the conversion functions over the
7990 // other. This only distinguishes the results in non-standard, extension
7991 // cases such as the conversion from a lambda closure type to a function
7992 // pointer or block.
7993 ImplicitConversionSequence::CompareKind FuncResult
7994 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7995 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7996 return FuncResult;
7997
John McCall120d63c2010-08-24 20:38:10 +00007998 switch (CompareStandardConversionSequences(S,
7999 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008000 Cand2.FinalConversion)) {
8001 case ImplicitConversionSequence::Better:
8002 // Cand1 has a better conversion sequence.
8003 return true;
8004
8005 case ImplicitConversionSequence::Worse:
8006 // Cand1 can't be better than Cand2.
8007 return false;
8008
8009 case ImplicitConversionSequence::Indistinguishable:
8010 // Do nothing
8011 break;
8012 }
8013 }
8014
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008015 return false;
8016}
8017
Mike Stump1eb44332009-09-09 15:08:12 +00008018/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008019/// within an overload candidate set.
8020///
James Dennettefce31f2012-06-22 08:10:18 +00008021/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008022/// which overload resolution occurs.
8023///
James Dennettefce31f2012-06-22 08:10:18 +00008024/// \param Best If overload resolution was successful or found a deleted
8025/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008026///
8027/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008028OverloadingResult
8029OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008030 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008031 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008032 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008033 Best = end();
8034 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8035 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008036 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008037 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008038 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008039 }
8040
8041 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008042 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008043 return OR_No_Viable_Function;
8044
8045 // Make sure that this function is better than every other viable
8046 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008047 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008048 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008049 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008050 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008051 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008052 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008053 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008054 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008055 }
Mike Stump1eb44332009-09-09 15:08:12 +00008056
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008057 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008058 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008059 (Best->Function->isDeleted() ||
8060 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008061 return OR_Deleted;
8062
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008063 return OR_Success;
8064}
8065
John McCall3c80f572010-01-12 02:15:36 +00008066namespace {
8067
8068enum OverloadCandidateKind {
8069 oc_function,
8070 oc_method,
8071 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008072 oc_function_template,
8073 oc_method_template,
8074 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008075 oc_implicit_default_constructor,
8076 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008077 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008078 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008079 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008080 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008081};
8082
John McCall220ccbf2010-01-13 00:25:19 +00008083OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8084 FunctionDecl *Fn,
8085 std::string &Description) {
8086 bool isTemplate = false;
8087
8088 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8089 isTemplate = true;
8090 Description = S.getTemplateArgumentBindingsText(
8091 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8092 }
John McCallb1622a12010-01-06 09:43:14 +00008093
8094 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008095 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008096 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008097
Sebastian Redlf677ea32011-02-05 19:23:19 +00008098 if (Ctor->getInheritedConstructor())
8099 return oc_implicit_inherited_constructor;
8100
Sean Hunt82713172011-05-25 23:16:36 +00008101 if (Ctor->isDefaultConstructor())
8102 return oc_implicit_default_constructor;
8103
8104 if (Ctor->isMoveConstructor())
8105 return oc_implicit_move_constructor;
8106
8107 assert(Ctor->isCopyConstructor() &&
8108 "unexpected sort of implicit constructor");
8109 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008110 }
8111
8112 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8113 // This actually gets spelled 'candidate function' for now, but
8114 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008115 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008116 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008117
Sean Hunt82713172011-05-25 23:16:36 +00008118 if (Meth->isMoveAssignmentOperator())
8119 return oc_implicit_move_assignment;
8120
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008121 if (Meth->isCopyAssignmentOperator())
8122 return oc_implicit_copy_assignment;
8123
8124 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8125 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008126 }
8127
John McCall220ccbf2010-01-13 00:25:19 +00008128 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008129}
8130
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008131void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00008132 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8133 if (!Ctor) return;
8134
8135 Ctor = Ctor->getInheritedConstructor();
8136 if (!Ctor) return;
8137
8138 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8139}
8140
John McCall3c80f572010-01-12 02:15:36 +00008141} // end anonymous namespace
8142
8143// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008144void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008145 std::string FnDesc;
8146 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008147 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8148 << (unsigned) K << FnDesc;
8149 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8150 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008151 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008152}
8153
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008154//Notes the location of all overload candidates designated through
8155// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008156void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008157 assert(OverloadedExpr->getType() == Context.OverloadTy);
8158
8159 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8160 OverloadExpr *OvlExpr = Ovl.Expression;
8161
8162 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8163 IEnd = OvlExpr->decls_end();
8164 I != IEnd; ++I) {
8165 if (FunctionTemplateDecl *FunTmpl =
8166 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008167 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008168 } else if (FunctionDecl *Fun
8169 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008170 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008171 }
8172 }
8173}
8174
John McCall1d318332010-01-12 00:44:57 +00008175/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8176/// "lead" diagnostic; it will be given two arguments, the source and
8177/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008178void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8179 Sema &S,
8180 SourceLocation CaretLoc,
8181 const PartialDiagnostic &PDiag) const {
8182 S.Diag(CaretLoc, PDiag)
8183 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008184 // FIXME: The note limiting machinery is borrowed from
8185 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8186 // refactoring here.
8187 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8188 unsigned CandsShown = 0;
8189 AmbiguousConversionSequence::const_iterator I, E;
8190 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8191 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8192 break;
8193 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008194 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008195 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008196 if (I != E)
8197 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008198}
8199
John McCall1d318332010-01-12 00:44:57 +00008200namespace {
8201
John McCalladbb8f82010-01-13 09:16:55 +00008202void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8203 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8204 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008205 assert(Cand->Function && "for now, candidate must be a function");
8206 FunctionDecl *Fn = Cand->Function;
8207
8208 // There's a conversion slot for the object argument if this is a
8209 // non-constructor method. Note that 'I' corresponds the
8210 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008211 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008212 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008213 if (I == 0)
8214 isObjectArgument = true;
8215 else
8216 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008217 }
8218
John McCall220ccbf2010-01-13 00:25:19 +00008219 std::string FnDesc;
8220 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8221
John McCalladbb8f82010-01-13 09:16:55 +00008222 Expr *FromExpr = Conv.Bad.FromExpr;
8223 QualType FromTy = Conv.Bad.getFromType();
8224 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008225
John McCall5920dbb2010-02-02 02:42:52 +00008226 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008227 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008228 Expr *E = FromExpr->IgnoreParens();
8229 if (isa<UnaryOperator>(E))
8230 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008231 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008232
8233 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8234 << (unsigned) FnKind << FnDesc
8235 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8236 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008237 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008238 return;
8239 }
8240
John McCall258b2032010-01-23 08:10:49 +00008241 // Do some hand-waving analysis to see if the non-viability is due
8242 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008243 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8244 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8245 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8246 CToTy = RT->getPointeeType();
8247 else {
8248 // TODO: detect and diagnose the full richness of const mismatches.
8249 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8250 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8251 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8252 }
8253
8254 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8255 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008256 Qualifiers FromQs = CFromTy.getQualifiers();
8257 Qualifiers ToQs = CToTy.getQualifiers();
8258
8259 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8261 << (unsigned) FnKind << FnDesc
8262 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8263 << FromTy
8264 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8265 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008266 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008267 return;
8268 }
8269
John McCallf85e1932011-06-15 23:02:42 +00008270 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008271 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008272 << (unsigned) FnKind << FnDesc
8273 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8274 << FromTy
8275 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8276 << (unsigned) isObjectArgument << I+1;
8277 MaybeEmitInheritedConstructorNote(S, Fn);
8278 return;
8279 }
8280
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008281 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8282 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8283 << (unsigned) FnKind << FnDesc
8284 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8285 << FromTy
8286 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8287 << (unsigned) isObjectArgument << I+1;
8288 MaybeEmitInheritedConstructorNote(S, Fn);
8289 return;
8290 }
8291
John McCall651f3ee2010-01-14 03:28:57 +00008292 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8293 assert(CVR && "unexpected qualifiers mismatch");
8294
8295 if (isObjectArgument) {
8296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8297 << (unsigned) FnKind << FnDesc
8298 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8299 << FromTy << (CVR - 1);
8300 } else {
8301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8302 << (unsigned) FnKind << FnDesc
8303 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8304 << FromTy << (CVR - 1) << I+1;
8305 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008306 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008307 return;
8308 }
8309
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008310 // Special diagnostic for failure to convert an initializer list, since
8311 // telling the user that it has type void is not useful.
8312 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8314 << (unsigned) FnKind << FnDesc
8315 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8316 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8317 MaybeEmitInheritedConstructorNote(S, Fn);
8318 return;
8319 }
8320
John McCall258b2032010-01-23 08:10:49 +00008321 // Diagnose references or pointers to incomplete types differently,
8322 // since it's far from impossible that the incompleteness triggered
8323 // the failure.
8324 QualType TempFromTy = FromTy.getNonReferenceType();
8325 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8326 TempFromTy = PTy->getPointeeType();
8327 if (TempFromTy->isIncompleteType()) {
8328 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8329 << (unsigned) FnKind << FnDesc
8330 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8331 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008332 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008333 return;
8334 }
8335
Douglas Gregor85789812010-06-30 23:01:39 +00008336 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008337 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008338 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8339 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8340 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8341 FromPtrTy->getPointeeType()) &&
8342 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8343 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008344 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008345 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008346 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008347 }
8348 } else if (const ObjCObjectPointerType *FromPtrTy
8349 = FromTy->getAs<ObjCObjectPointerType>()) {
8350 if (const ObjCObjectPointerType *ToPtrTy
8351 = ToTy->getAs<ObjCObjectPointerType>())
8352 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8353 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8354 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8355 FromPtrTy->getPointeeType()) &&
8356 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008357 BaseToDerivedConversion = 2;
8358 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008359 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8360 !FromTy->isIncompleteType() &&
8361 !ToRefTy->getPointeeType()->isIncompleteType() &&
8362 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8363 BaseToDerivedConversion = 3;
8364 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8365 ToTy.getNonReferenceType().getCanonicalType() ==
8366 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008367 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8368 << (unsigned) FnKind << FnDesc
8369 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8370 << (unsigned) isObjectArgument << I + 1;
8371 MaybeEmitInheritedConstructorNote(S, Fn);
8372 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008373 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008374 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008375
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008376 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008377 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008378 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008379 << (unsigned) FnKind << FnDesc
8380 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008381 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008382 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008383 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008384 return;
8385 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008386
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008387 if (isa<ObjCObjectPointerType>(CFromTy) &&
8388 isa<PointerType>(CToTy)) {
8389 Qualifiers FromQs = CFromTy.getQualifiers();
8390 Qualifiers ToQs = CToTy.getQualifiers();
8391 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8392 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8393 << (unsigned) FnKind << FnDesc
8394 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8395 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8396 MaybeEmitInheritedConstructorNote(S, Fn);
8397 return;
8398 }
8399 }
8400
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008401 // Emit the generic diagnostic and, optionally, add the hints to it.
8402 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8403 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008404 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008405 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8406 << (unsigned) (Cand->Fix.Kind);
8407
8408 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008409 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8410 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008411 FDiag << *HI;
8412 S.Diag(Fn->getLocation(), FDiag);
8413
Sebastian Redlf677ea32011-02-05 19:23:19 +00008414 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008415}
8416
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008417void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8418 unsigned NumFormalArgs) {
8419 // TODO: treat calls to a missing default constructor as a special case
8420
John McCalladbb8f82010-01-13 09:16:55 +00008421 FunctionDecl *Fn = Cand->Function;
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008422 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8423
John McCalladbb8f82010-01-13 09:16:55 +00008424 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008425
Douglas Gregor439d3c32011-05-05 00:13:13 +00008426 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008427 // have an arity mismatch when it fact it looks like we have the
Douglas Gregor439d3c32011-05-05 00:13:13 +00008428 // right number of arguments, because only overloaded operators have
8429 // the weird behavior of overloading member and non-member functions.
8430 // Just don't report anything.
8431 if (Fn->isInvalidDecl() &&
8432 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008433 return;
Douglas Gregor439d3c32011-05-05 00:13:13 +00008434
John McCalladbb8f82010-01-13 09:16:55 +00008435 // at least / at most / exactly
8436 unsigned mode, modeCount;
8437 if (NumFormalArgs < MinParams) {
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008438 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8439 (Cand->FailureKind == ovl_fail_bad_deduction &&
8440 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008441 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008442 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008443 mode = 0; // "at least"
8444 else
8445 mode = 2; // "exactly"
8446 modeCount = MinParams;
8447 } else {
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008448 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8449 (Cand->FailureKind == ovl_fail_bad_deduction &&
8450 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008451 if (MinParams != FnTy->getNumArgs())
8452 mode = 1; // "at most"
8453 else
8454 mode = 2; // "exactly"
8455 modeCount = FnTy->getNumArgs();
8456 }
8457
8458 std::string Description;
8459 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8460
Richard Smithf7b80562012-05-11 05:16:41 +00008461 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8462 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8463 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8464 << Fn->getParamDecl(0) << NumFormalArgs;
8465 else
8466 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8467 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8468 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008469 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008470}
8471
Larisse Voufoa730f542013-07-19 22:34:32 +00008472/// Diagnose a failed template-argument deduction.
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008473void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Larisse Voufoa730f542013-07-19 22:34:32 +00008474 unsigned NumArgs) {
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008475 FunctionDecl *Fn = Cand->Function; // pattern
8476
8477 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008478 NamedDecl *ParamD;
8479 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8480 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8481 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008482 switch (Cand->DeductionFailure.Result) {
John McCall342fec42010-02-01 18:53:26 +00008483 case Sema::TDK_Success:
8484 llvm_unreachable("TDK_success while diagnosing bad deduction");
8485
8486 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008487 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008488 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8489 << ParamD->getDeclName();
8490 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008491 return;
8492 }
8493
John McCall57e97782010-08-05 09:05:08 +00008494 case Sema::TDK_Underqualified: {
8495 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8496 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8497
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008498 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008499
8500 // Param will have been canonicalized, but it should just be a
8501 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008502 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008503 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008504 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008505 assert(S.Context.hasSameType(Param, NonCanonParam));
8506
8507 // Arg has also been canonicalized, but there's nothing we can do
8508 // about that. It also doesn't matter as much, because it won't
8509 // have any template parameters in it (because deduction isn't
8510 // done on dependent types).
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008511 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008512
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008513 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8514 << ParamD->getDeclName() << Arg << NonCanonParam;
8515 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008516 return;
8517 }
8518
8519 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008520 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008521 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008522 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008523 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008524 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008525 which = 1;
8526 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008527 which = 2;
8528 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008529
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008530 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8531 << which << ParamD->getDeclName()
8532 << *Cand->DeductionFailure.getFirstArg()
8533 << *Cand->DeductionFailure.getSecondArg();
8534 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008535 return;
8536 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008537
Douglas Gregorf1a84452010-05-08 19:15:54 +00008538 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008539 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008540 if (ParamD->getDeclName())
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008541 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008542 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008543 << ParamD->getDeclName();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008544 else {
8545 int index = 0;
8546 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8547 index = TTP->getIndex();
8548 else if (NonTypeTemplateParmDecl *NTTP
8549 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8550 index = NTTP->getIndex();
8551 else
8552 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008553 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008554 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008555 << (index + 1);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008556 }
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008557 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008558 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008559
Douglas Gregora18592e2010-05-08 18:13:28 +00008560 case Sema::TDK_TooManyArguments:
8561 case Sema::TDK_TooFewArguments:
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008562 DiagnoseArityMismatch(S, Cand, NumArgs);
Douglas Gregora18592e2010-05-08 18:13:28 +00008563 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008564
8565 case Sema::TDK_InstantiationDepth:
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008566 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8567 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008568 return;
8569
8570 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008571 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008572 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008573 if (TemplateArgumentList *Args =
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008574 Cand->DeductionFailure.getTemplateArgumentList()) {
Richard Smithb8590f32012-05-07 09:03:25 +00008575 TemplateArgString = " ";
8576 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008577 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
Richard Smithb8590f32012-05-07 09:03:25 +00008578 }
8579
Richard Smith4493c0a2012-05-09 05:17:00 +00008580 // If this candidate was disabled by enable_if, say so.
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008581 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
Richard Smith4493c0a2012-05-09 05:17:00 +00008582 if (PDiag && PDiag->second.getDiagID() ==
8583 diag::err_typename_nested_not_found_enable_if) {
8584 // FIXME: Use the source range of the condition, and the fully-qualified
8585 // name of the enable_if template. These are both present in PDiag.
8586 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8587 << "'enable_if'" << TemplateArgString;
8588 return;
8589 }
8590
Richard Smithb8590f32012-05-07 09:03:25 +00008591 // Format the SFINAE diagnostic into the argument string.
8592 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8593 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008594 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008595 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008596 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008597 SFINAEArgString = ": ";
8598 R = SourceRange(PDiag->first, PDiag->first);
8599 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8600 }
8601
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008602 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8603 << TemplateArgString << SFINAEArgString << R;
8604 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008605 return;
8606 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008607
Richard Smith0efa62f2013-01-31 04:03:12 +00008608 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008609 OverloadExpr::FindResult R =
8610 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8611 S.Diag(Fn->getLocation(),
Richard Smith0efa62f2013-01-31 04:03:12 +00008612 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008613 << R.Expression->getName();
Richard Smith0efa62f2013-01-31 04:03:12 +00008614 return;
8615 }
8616
Richard Trieueef35f82013-04-08 21:11:40 +00008617 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008618 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008619 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8620 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
Richard Trieueef35f82013-04-08 21:11:40 +00008621 if (FirstTA.getKind() == TemplateArgument::Template &&
8622 SecondTA.getKind() == TemplateArgument::Template) {
8623 TemplateName FirstTN = FirstTA.getAsTemplate();
8624 TemplateName SecondTN = SecondTA.getAsTemplate();
8625 if (FirstTN.getKind() == TemplateName::Template &&
8626 SecondTN.getKind() == TemplateName::Template) {
8627 if (FirstTN.getAsTemplateDecl()->getName() ==
8628 SecondTN.getAsTemplateDecl()->getName()) {
8629 // FIXME: This fixes a bad diagnostic where both templates are named
8630 // the same. This particular case is a bit difficult since:
8631 // 1) It is passed as a string to the diagnostic printer.
8632 // 2) The diagnostic printer only attempts to find a better
8633 // name for types, not decls.
8634 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008635 S.Diag(Fn->getLocation(),
Richard Trieueef35f82013-04-08 21:11:40 +00008636 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8637 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8638 return;
8639 }
8640 }
8641 }
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008642 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8643 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008644 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008645 }
John McCall342fec42010-02-01 18:53:26 +00008646 // TODO: diagnose these individually, then kill off
8647 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008648 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008649 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8650 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008651 return;
8652 }
8653}
8654
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008655/// CUDA: diagnose an invalid call across targets.
8656void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8657 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8658 FunctionDecl *Callee = Cand->Function;
8659
8660 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8661 CalleeTarget = S.IdentifyCUDATarget(Callee);
8662
8663 std::string FnDesc;
8664 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8665
8666 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8667 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8668}
8669
John McCall342fec42010-02-01 18:53:26 +00008670/// Generates a 'note' diagnostic for an overload candidate. We've
8671/// already generated a primary error at the call site.
8672///
8673/// It really does need to be a single diagnostic with its caret
8674/// pointed at the candidate declaration. Yes, this creates some
8675/// major challenges of technical writing. Yes, this makes pointing
8676/// out problems with specific arguments quite awkward. It's still
8677/// better than generating twenty screens of text for every failed
8678/// overload.
8679///
8680/// It would be great to be able to express per-candidate problems
8681/// more richly for those diagnostic clients that cared, but we'd
8682/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008683void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008684 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008685 FunctionDecl *Fn = Cand->Function;
8686
John McCall81201622010-01-08 04:41:39 +00008687 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008688 if (Cand->Viable && (Fn->isDeleted() ||
8689 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008690 std::string FnDesc;
8691 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008692
8693 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008694 << FnKind << FnDesc
8695 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008696 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008697 return;
John McCall81201622010-01-08 04:41:39 +00008698 }
8699
John McCall220ccbf2010-01-13 00:25:19 +00008700 // We don't really have anything else to say about viable candidates.
8701 if (Cand->Viable) {
8702 S.NoteOverloadCandidate(Fn);
8703 return;
8704 }
John McCall1d318332010-01-12 00:44:57 +00008705
John McCalladbb8f82010-01-13 09:16:55 +00008706 switch (Cand->FailureKind) {
8707 case ovl_fail_too_many_arguments:
8708 case ovl_fail_too_few_arguments:
8709 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008710
John McCalladbb8f82010-01-13 09:16:55 +00008711 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008712 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008713
John McCall717e8912010-01-23 05:17:32 +00008714 case ovl_fail_trivial_conversion:
8715 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008716 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008717 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008718
John McCallb1bdc622010-02-25 01:37:24 +00008719 case ovl_fail_bad_conversion: {
8720 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008721 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008722 if (Cand->Conversions[I].isBad())
8723 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008724
John McCalladbb8f82010-01-13 09:16:55 +00008725 // FIXME: this currently happens when we're called from SemaInit
8726 // when user-conversion overload fails. Figure out how to handle
8727 // those conditions and diagnose them well.
8728 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008729 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008730
8731 case ovl_fail_bad_target:
8732 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008733 }
John McCalla1d7d622010-01-08 00:58:21 +00008734}
8735
8736void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8737 // Desugar the type of the surrogate down to a function type,
8738 // retaining as many typedefs as possible while still showing
8739 // the function type (and, therefore, its parameter types).
8740 QualType FnType = Cand->Surrogate->getConversionType();
8741 bool isLValueReference = false;
8742 bool isRValueReference = false;
8743 bool isPointer = false;
8744 if (const LValueReferenceType *FnTypeRef =
8745 FnType->getAs<LValueReferenceType>()) {
8746 FnType = FnTypeRef->getPointeeType();
8747 isLValueReference = true;
8748 } else if (const RValueReferenceType *FnTypeRef =
8749 FnType->getAs<RValueReferenceType>()) {
8750 FnType = FnTypeRef->getPointeeType();
8751 isRValueReference = true;
8752 }
8753 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8754 FnType = FnTypePtr->getPointeeType();
8755 isPointer = true;
8756 }
8757 // Desugar down to a function type.
8758 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8759 // Reconstruct the pointer/reference as appropriate.
8760 if (isPointer) FnType = S.Context.getPointerType(FnType);
8761 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8762 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8763
8764 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8765 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008766 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008767}
8768
8769void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008770 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008771 SourceLocation OpLoc,
8772 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008773 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008774 std::string TypeStr("operator");
8775 TypeStr += Opc;
8776 TypeStr += "(";
8777 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008778 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008779 TypeStr += ")";
8780 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8781 } else {
8782 TypeStr += ", ";
8783 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8784 TypeStr += ")";
8785 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8786 }
8787}
8788
8789void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8790 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008791 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008792 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8793 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008794 if (ICS.isBad()) break; // all meaningless after first invalid
8795 if (!ICS.isAmbiguous()) continue;
8796
John McCall120d63c2010-08-24 20:38:10 +00008797 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008798 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008799 }
8800}
8801
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008802SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall1b77e732010-01-15 23:32:50 +00008803 if (Cand->Function)
8804 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008805 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008806 return Cand->Surrogate->getLocation();
8807 return SourceLocation();
8808}
8809
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008810static unsigned
8811RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008812 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008813 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008814 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008815
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008816 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008817 case Sema::TDK_Incomplete:
8818 return 1;
8819
8820 case Sema::TDK_Underqualified:
8821 case Sema::TDK_Inconsistent:
8822 return 2;
8823
8824 case Sema::TDK_SubstitutionFailure:
8825 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008826 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008827 return 3;
8828
8829 case Sema::TDK_InstantiationDepth:
8830 case Sema::TDK_FailedOverloadResolution:
8831 return 4;
8832
8833 case Sema::TDK_InvalidExplicitArguments:
8834 return 5;
8835
8836 case Sema::TDK_TooManyArguments:
8837 case Sema::TDK_TooFewArguments:
8838 return 6;
8839 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008840 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008841}
8842
John McCallbf65c0b2010-01-12 00:48:53 +00008843struct CompareOverloadCandidatesForDisplay {
8844 Sema &S;
8845 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008846
8847 bool operator()(const OverloadCandidate *L,
8848 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008849 // Fast-path this check.
8850 if (L == R) return false;
8851
John McCall81201622010-01-08 04:41:39 +00008852 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008853 if (L->Viable) {
8854 if (!R->Viable) return true;
8855
8856 // TODO: introduce a tri-valued comparison for overload
8857 // candidates. Would be more worthwhile if we had a sort
8858 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008859 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8860 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008861 } else if (R->Viable)
8862 return false;
John McCall81201622010-01-08 04:41:39 +00008863
John McCall1b77e732010-01-15 23:32:50 +00008864 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008865
John McCall1b77e732010-01-15 23:32:50 +00008866 // Criteria by which we can sort non-viable candidates:
8867 if (!L->Viable) {
8868 // 1. Arity mismatches come after other candidates.
8869 if (L->FailureKind == ovl_fail_too_many_arguments ||
8870 L->FailureKind == ovl_fail_too_few_arguments)
8871 return false;
8872 if (R->FailureKind == ovl_fail_too_many_arguments ||
8873 R->FailureKind == ovl_fail_too_few_arguments)
8874 return true;
John McCall81201622010-01-08 04:41:39 +00008875
John McCall717e8912010-01-23 05:17:32 +00008876 // 2. Bad conversions come first and are ordered by the number
8877 // of bad conversions and quality of good conversions.
8878 if (L->FailureKind == ovl_fail_bad_conversion) {
8879 if (R->FailureKind != ovl_fail_bad_conversion)
8880 return true;
8881
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008882 // The conversion that can be fixed with a smaller number of changes,
8883 // comes first.
8884 unsigned numLFixes = L->Fix.NumConversionsFixed;
8885 unsigned numRFixes = R->Fix.NumConversionsFixed;
8886 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8887 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008888 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008889 if (numLFixes < numRFixes)
8890 return true;
8891 else
8892 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008893 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008894
John McCall717e8912010-01-23 05:17:32 +00008895 // If there's any ordering between the defined conversions...
8896 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008897 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008898
8899 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008900 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008901 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008902 switch (CompareImplicitConversionSequences(S,
8903 L->Conversions[I],
8904 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008905 case ImplicitConversionSequence::Better:
8906 leftBetter++;
8907 break;
8908
8909 case ImplicitConversionSequence::Worse:
8910 leftBetter--;
8911 break;
8912
8913 case ImplicitConversionSequence::Indistinguishable:
8914 break;
8915 }
8916 }
8917 if (leftBetter > 0) return true;
8918 if (leftBetter < 0) return false;
8919
8920 } else if (R->FailureKind == ovl_fail_bad_conversion)
8921 return false;
8922
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008923 if (L->FailureKind == ovl_fail_bad_deduction) {
8924 if (R->FailureKind != ovl_fail_bad_deduction)
8925 return true;
8926
8927 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8928 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008929 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008930 } else if (R->FailureKind == ovl_fail_bad_deduction)
8931 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008932
John McCall1b77e732010-01-15 23:32:50 +00008933 // TODO: others?
8934 }
8935
8936 // Sort everything else by location.
8937 SourceLocation LLoc = GetLocationForCandidate(L);
8938 SourceLocation RLoc = GetLocationForCandidate(R);
8939
8940 // Put candidates without locations (e.g. builtins) at the end.
8941 if (LLoc.isInvalid()) return false;
8942 if (RLoc.isInvalid()) return true;
8943
8944 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008945 }
8946};
8947
John McCall717e8912010-01-23 05:17:32 +00008948/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008949/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008950void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008951 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008952 assert(!Cand->Viable);
8953
8954 // Don't do anything on failures other than bad conversion.
8955 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8956
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008957 // We only want the FixIts if all the arguments can be corrected.
8958 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008959 // Use a implicit copy initialization to check conversion fixes.
8960 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008961
John McCall717e8912010-01-23 05:17:32 +00008962 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008963 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008964 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008965 while (true) {
8966 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8967 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008968 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008969 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008970 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008971 }
John McCall717e8912010-01-23 05:17:32 +00008972 }
8973
8974 if (ConvIdx == ConvCount)
8975 return;
8976
John McCallb1bdc622010-02-25 01:37:24 +00008977 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8978 "remaining conversion is initialized?");
8979
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008980 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008981 // operation somehow.
8982 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008983
8984 const FunctionProtoType* Proto;
8985 unsigned ArgIdx = ConvIdx;
8986
8987 if (Cand->IsSurrogate) {
8988 QualType ConvType
8989 = Cand->Surrogate->getConversionType().getNonReferenceType();
8990 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8991 ConvType = ConvPtrType->getPointeeType();
8992 Proto = ConvType->getAs<FunctionProtoType>();
8993 ArgIdx--;
8994 } else if (Cand->Function) {
8995 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8996 if (isa<CXXMethodDecl>(Cand->Function) &&
8997 !isa<CXXConstructorDecl>(Cand->Function))
8998 ArgIdx--;
8999 } else {
9000 // Builtin binary operator with a bad first conversion.
9001 assert(ConvCount <= 3);
9002 for (; ConvIdx != ConvCount; ++ConvIdx)
9003 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009004 = TryCopyInitialization(S, Args[ConvIdx],
9005 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009006 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009007 /*InOverloadResolution*/ true,
9008 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009009 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009010 return;
9011 }
9012
9013 // Fill in the rest of the conversions.
9014 unsigned NumArgsInProto = Proto->getNumArgs();
9015 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009016 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009017 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009018 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
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);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009023 // Store the FixIt in the candidate if it exists.
9024 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009025 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009026 }
John McCall717e8912010-01-23 05:17:32 +00009027 else
9028 Cand->Conversions[ConvIdx].setEllipsis();
9029 }
9030}
9031
John McCalla1d7d622010-01-08 00:58:21 +00009032} // end anonymous namespace
9033
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009034/// PrintOverloadCandidates - When overload resolution fails, prints
9035/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009036/// set.
John McCall120d63c2010-08-24 20:38:10 +00009037void OverloadCandidateSet::NoteCandidates(Sema &S,
9038 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009039 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009040 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009041 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009042 // Sort the candidates by viability and position. Sorting directly would
9043 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009044 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009045 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9046 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009047 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009048 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009049 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009050 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009051 if (Cand->Function || Cand->IsSurrogate)
9052 Cands.push_back(Cand);
9053 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9054 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009055 }
9056 }
9057
John McCallbf65c0b2010-01-12 00:48:53 +00009058 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009059 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009060
John McCall1d318332010-01-12 00:44:57 +00009061 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009062
Chris Lattner5f9e2722011-07-23 10:55:15 +00009063 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009064 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009065 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009066 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9067 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009068
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009069 // Set an arbitrary limit on the number of candidate functions we'll spam
9070 // the user with. FIXME: This limit should depend on details of the
9071 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009072 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009073 break;
9074 }
9075 ++CandsShown;
9076
John McCalla1d7d622010-01-08 00:58:21 +00009077 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009078 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009079 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009080 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009081 else {
9082 assert(Cand->Viable &&
9083 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009084 // Generally we only see ambiguities including viable builtin
9085 // operators if overload resolution got screwed up by an
9086 // ambiguous user-defined conversion.
9087 //
9088 // FIXME: It's quite possible for different conversions to see
9089 // different ambiguities, though.
9090 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009091 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009092 ReportedAmbiguousConversions = true;
9093 }
John McCalla1d7d622010-01-08 00:58:21 +00009094
John McCall1d318332010-01-12 00:44:57 +00009095 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009096 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009097 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009098 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009099
9100 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009101 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009102}
9103
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009104// [PossiblyAFunctionType] --> [Return]
9105// NonFunctionType --> NonFunctionType
9106// R (A) --> R(A)
9107// R (*)(A) --> R (A)
9108// R (&)(A) --> R (A)
9109// R (S::*)(A) --> R (A)
9110QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9111 QualType Ret = PossiblyAFunctionType;
9112 if (const PointerType *ToTypePtr =
9113 PossiblyAFunctionType->getAs<PointerType>())
9114 Ret = ToTypePtr->getPointeeType();
9115 else if (const ReferenceType *ToTypeRef =
9116 PossiblyAFunctionType->getAs<ReferenceType>())
9117 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009118 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009119 PossiblyAFunctionType->getAs<MemberPointerType>())
9120 Ret = MemTypePtr->getPointeeType();
9121 Ret =
9122 Context.getCanonicalType(Ret).getUnqualifiedType();
9123 return Ret;
9124}
Douglas Gregor904eed32008-11-10 20:40:00 +00009125
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009126// A helper class to help with address of function resolution
9127// - allows us to avoid passing around all those ugly parameters
9128class AddressOfFunctionResolver
9129{
9130 Sema& S;
9131 Expr* SourceExpr;
9132 const QualType& TargetType;
9133 QualType TargetFunctionType; // Extracted function type from target type
9134
9135 bool Complain;
9136 //DeclAccessPair& ResultFunctionAccessPair;
9137 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009138
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009139 bool TargetTypeIsNonStaticMemberFunction;
9140 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009141
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009142 OverloadExpr::FindResult OvlExprInfo;
9143 OverloadExpr *OvlExpr;
9144 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009145 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009146
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009147public:
Larisse Voufo8c5d4072013-07-19 22:53:23 +00009148 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9149 const QualType& TargetType, bool Complain)
9150 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9151 Complain(Complain), Context(S.getASTContext()),
9152 TargetTypeIsNonStaticMemberFunction(
9153 !!TargetType->getAs<MemberPointerType>()),
9154 FoundNonTemplateFunction(false),
9155 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9156 OvlExpr(OvlExprInfo.Expression)
9157 {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009158 ExtractUnqualifiedFunctionTypeFromTargetType();
9159
9160 if (!TargetFunctionType->isFunctionType()) {
9161 if (OvlExpr->hasExplicitTemplateArgs()) {
9162 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009163 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009164 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009165
9166 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9167 if (!Method->isStatic()) {
9168 // If the target type is a non-function type and the function
9169 // found is a non-static member function, pretend as if that was
9170 // the target, it's the only possible type to end up with.
9171 TargetTypeIsNonStaticMemberFunction = true;
9172
9173 // And skip adding the function if its not in the proper form.
9174 // We'll diagnose this due to an empty set of functions.
9175 if (!OvlExprInfo.HasFormOfMemberPointer)
9176 return;
9177 }
9178 }
9179
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009180 Matches.push_back(std::make_pair(dap,Fn));
9181 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009182 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009183 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009184 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009185
9186 if (OvlExpr->hasExplicitTemplateArgs())
9187 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009188
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009189 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9190 // C++ [over.over]p4:
9191 // If more than one function is selected, [...]
9192 if (Matches.size() > 1) {
9193 if (FoundNonTemplateFunction)
9194 EliminateAllTemplateMatches();
9195 else
9196 EliminateAllExceptMostSpecializedTemplate();
9197 }
9198 }
9199 }
9200
9201private:
9202 bool isTargetTypeAFunction() const {
9203 return TargetFunctionType->isFunctionType();
9204 }
9205
9206 // [ToType] [Return]
9207
9208 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9209 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9210 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9211 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9212 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9213 }
9214
9215 // return true if any matching specializations were found
9216 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9217 const DeclAccessPair& CurAccessFunPair) {
9218 if (CXXMethodDecl *Method
9219 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9220 // Skip non-static function templates when converting to pointer, and
9221 // static when converting to member pointer.
9222 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9223 return false;
9224 }
9225 else if (TargetTypeIsNonStaticMemberFunction)
9226 return false;
9227
9228 // C++ [over.over]p2:
9229 // If the name is a function template, template argument deduction is
9230 // done (14.8.2.2), and if the argument deduction succeeds, the
9231 // resulting template argument list is used to generate a single
9232 // function template specialization, which is added to the set of
9233 // overloaded functions considered.
9234 FunctionDecl *Specialization = 0;
Larisse Voufo8c5d4072013-07-19 22:53:23 +00009235 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009236 if (Sema::TemplateDeductionResult Result
9237 = S.DeduceTemplateArguments(FunctionTemplate,
9238 &OvlExplicitTemplateArgs,
9239 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009240 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo8c5d4072013-07-19 22:53:23 +00009241 // FIXME: make a note of the failed deduction for diagnostics.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009242 (void)Result;
9243 return false;
9244 }
9245
Douglas Gregor092140a2013-04-17 08:45:07 +00009246 // Template argument deduction ensures that we have an exact match or
9247 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009248 // This function template specicalization works.
9249 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009250 assert(S.isSameOrCompatibleFunctionType(
9251 Context.getCanonicalType(Specialization->getType()),
9252 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009253 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9254 return true;
9255 }
9256
9257 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9258 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009259 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009260 // Skip non-static functions when converting to pointer, and static
9261 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009262 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9263 return false;
9264 }
9265 else if (TargetTypeIsNonStaticMemberFunction)
9266 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009267
Chandler Carruthbd647292009-12-29 06:17:27 +00009268 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009269 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009270 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9271 if (S.CheckCUDATarget(Caller, FunDecl))
9272 return false;
9273
Richard Smith60e141e2013-05-04 07:00:32 +00009274 // If any candidate has a placeholder return type, trigger its deduction
9275 // now.
9276 if (S.getLangOpts().CPlusPlus1y &&
9277 FunDecl->getResultType()->isUndeducedType() &&
9278 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9279 return false;
9280
Douglas Gregor43c79c22009-12-09 00:47:37 +00009281 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009282 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9283 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009284 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9285 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009286 Matches.push_back(std::make_pair(CurAccessFunPair,
9287 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009288 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009289 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009290 }
Mike Stump1eb44332009-09-09 15:08:12 +00009291 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009292
9293 return false;
9294 }
9295
9296 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9297 bool Ret = false;
9298
9299 // If the overload expression doesn't have the form of a pointer to
9300 // member, don't try to convert it to a pointer-to-member type.
9301 if (IsInvalidFormOfPointerToMemberFunction())
9302 return false;
9303
9304 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9305 E = OvlExpr->decls_end();
9306 I != E; ++I) {
9307 // Look through any using declarations to find the underlying function.
9308 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9309
9310 // C++ [over.over]p3:
9311 // Non-member functions and static member functions match
9312 // targets of type "pointer-to-function" or "reference-to-function."
9313 // Nonstatic member functions match targets of
9314 // type "pointer-to-member-function."
9315 // Note that according to DR 247, the containing class does not matter.
9316 if (FunctionTemplateDecl *FunctionTemplate
9317 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9318 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9319 Ret = true;
9320 }
9321 // If we have explicit template arguments supplied, skip non-templates.
9322 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9323 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9324 Ret = true;
9325 }
9326 assert(Ret || Matches.empty());
9327 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009328 }
9329
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009330 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009331 // [...] and any given function template specialization F1 is
9332 // eliminated if the set contains a second function template
9333 // specialization whose function template is more specialized
9334 // than the function template of F1 according to the partial
9335 // ordering rules of 14.5.5.2.
9336
9337 // The algorithm specified above is quadratic. We instead use a
9338 // two-pass algorithm (similar to the one used to identify the
9339 // best viable function in an overload set) that identifies the
9340 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009341
9342 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9343 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9344 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009345
Larisse Voufo8c5d4072013-07-19 22:53:23 +00009346 UnresolvedSetIterator Result =
9347 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9348 TPOC_Other, 0, SourceExpr->getLocStart(),
9349 S.PDiag(),
9350 S.PDiag(diag::err_addr_ovl_ambiguous)
9351 << Matches[0].second->getDeclName(),
9352 S.PDiag(diag::note_ovl_candidate)
9353 << (unsigned) oc_function_template,
9354 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009355
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009356 if (Result != MatchesCopy.end()) {
9357 // Make it the first and only element
9358 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9359 Matches[0].second = cast<FunctionDecl>(*Result);
9360 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009361 }
9362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009363
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009364 void EliminateAllTemplateMatches() {
9365 // [...] any function template specializations in the set are
9366 // eliminated if the set also contains a non-template function, [...]
9367 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9368 if (Matches[I].second->getPrimaryTemplate() == 0)
9369 ++I;
9370 else {
9371 Matches[I] = Matches[--N];
9372 Matches.set_size(N);
9373 }
9374 }
9375 }
9376
9377public:
9378 void ComplainNoMatchesFound() const {
9379 assert(Matches.empty());
9380 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9381 << OvlExpr->getName() << TargetFunctionType
9382 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009383 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009384 }
9385
9386 bool IsInvalidFormOfPointerToMemberFunction() const {
9387 return TargetTypeIsNonStaticMemberFunction &&
9388 !OvlExprInfo.HasFormOfMemberPointer;
9389 }
9390
9391 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9392 // TODO: Should we condition this on whether any functions might
9393 // have matched, or is it more appropriate to do that in callers?
9394 // TODO: a fixit wouldn't hurt.
9395 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9396 << TargetType << OvlExpr->getSourceRange();
9397 }
9398
9399 void ComplainOfInvalidConversion() const {
9400 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9401 << OvlExpr->getName() << TargetType;
9402 }
9403
9404 void ComplainMultipleMatchesFound() const {
9405 assert(Matches.size() > 1);
9406 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9407 << OvlExpr->getName()
9408 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009409 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009410 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009411
9412 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9413
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009414 int getNumMatches() const { return Matches.size(); }
9415
9416 FunctionDecl* getMatchingFunctionDecl() const {
9417 if (Matches.size() != 1) return 0;
9418 return Matches[0].second;
9419 }
9420
9421 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9422 if (Matches.size() != 1) return 0;
9423 return &Matches[0].first;
9424 }
9425};
9426
9427/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9428/// an overloaded function (C++ [over.over]), where @p From is an
9429/// expression with overloaded function type and @p ToType is the type
9430/// we're trying to resolve to. For example:
9431///
9432/// @code
9433/// int f(double);
9434/// int f(int);
9435///
9436/// int (*pfd)(double) = f; // selects f(double)
9437/// @endcode
9438///
9439/// This routine returns the resulting FunctionDecl if it could be
9440/// resolved, and NULL otherwise. When @p Complain is true, this
9441/// routine will emit diagnostics if there is an error.
9442FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009443Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9444 QualType TargetType,
9445 bool Complain,
9446 DeclAccessPair &FoundResult,
9447 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009448 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009449
9450 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9451 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009452 int NumMatches = Resolver.getNumMatches();
9453 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009454 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009455 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9456 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9457 else
9458 Resolver.ComplainNoMatchesFound();
9459 }
9460 else if (NumMatches > 1 && Complain)
9461 Resolver.ComplainMultipleMatchesFound();
9462 else if (NumMatches == 1) {
9463 Fn = Resolver.getMatchingFunctionDecl();
9464 assert(Fn);
9465 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009466 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009467 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009468 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009469
9470 if (pHadMultipleCandidates)
9471 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009472 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009473}
9474
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009475/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009476/// resolve that overloaded function expression down to a single function.
9477///
9478/// This routine can only resolve template-ids that refer to a single function
9479/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009480/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009481/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009482FunctionDecl *
9483Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9484 bool Complain,
9485 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009486 // C++ [over.over]p1:
9487 // [...] [Note: any redundant set of parentheses surrounding the
9488 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009489 // C++ [over.over]p1:
9490 // [...] The overloaded function name can be preceded by the &
9491 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009492
Douglas Gregor4b52e252009-12-21 23:17:24 +00009493 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009494 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009495 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009496
9497 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009498 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009499
Douglas Gregor4b52e252009-12-21 23:17:24 +00009500 // Look through all of the overloaded functions, searching for one
9501 // whose type matches exactly.
9502 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009503 for (UnresolvedSetIterator I = ovl->decls_begin(),
9504 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009505 // C++0x [temp.arg.explicit]p3:
9506 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009507 // where deduction is not done, if a template argument list is
9508 // specified and it, along with any default template arguments,
9509 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009510 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009511 FunctionTemplateDecl *FunctionTemplate
9512 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009513
Douglas Gregor4b52e252009-12-21 23:17:24 +00009514 // C++ [over.over]p2:
9515 // If the name is a function template, template argument deduction is
9516 // done (14.8.2.2), and if the argument deduction succeeds, the
9517 // resulting template argument list is used to generate a single
9518 // function template specialization, which is added to the set of
9519 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009520 FunctionDecl *Specialization = 0;
Larisse Voufo8c5d4072013-07-19 22:53:23 +00009521 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009522 if (TemplateDeductionResult Result
9523 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009524 Specialization, Info,
9525 /*InOverloadResolution=*/true)) {
Larisse Voufo8c5d4072013-07-19 22:53:23 +00009526 // FIXME: make a note of the failed deduction for diagnostics.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009527 (void)Result;
9528 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009529 }
9530
John McCall864c0412011-04-26 20:42:42 +00009531 assert(Specialization && "no specialization and no error?");
9532
Douglas Gregor4b52e252009-12-21 23:17:24 +00009533 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009534 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009535 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009536 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9537 << ovl->getName();
9538 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009539 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009540 return 0;
John McCall864c0412011-04-26 20:42:42 +00009541 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009542
John McCall864c0412011-04-26 20:42:42 +00009543 Matched = Specialization;
9544 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009545 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009546
Richard Smith60e141e2013-05-04 07:00:32 +00009547 if (Matched && getLangOpts().CPlusPlus1y &&
9548 Matched->getResultType()->isUndeducedType() &&
9549 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9550 return 0;
9551
Douglas Gregor4b52e252009-12-21 23:17:24 +00009552 return Matched;
9553}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009554
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009555
9556
9557
John McCall6dbba4f2011-10-11 23:14:30 +00009558// Resolve and fix an overloaded expression that can be resolved
9559// because it identifies a single function template specialization.
9560//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009561// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009562//
9563// Return true if it was logically possible to so resolve the
9564// expression, regardless of whether or not it succeeded. Always
9565// returns true if 'complain' is set.
9566bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9567 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9568 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009569 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009570 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009571 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009572
John McCall6dbba4f2011-10-11 23:14:30 +00009573 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009574
John McCall864c0412011-04-26 20:42:42 +00009575 DeclAccessPair found;
9576 ExprResult SingleFunctionExpression;
9577 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9578 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009579 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009580 SrcExpr = ExprError();
9581 return true;
9582 }
John McCall864c0412011-04-26 20:42:42 +00009583
9584 // It is only correct to resolve to an instance method if we're
9585 // resolving a form that's permitted to be a pointer to member.
9586 // Otherwise we'll end up making a bound member expression, which
9587 // is illegal in all the contexts we resolve like this.
9588 if (!ovl.HasFormOfMemberPointer &&
9589 isa<CXXMethodDecl>(fn) &&
9590 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009591 if (!complain) return false;
9592
9593 Diag(ovl.Expression->getExprLoc(),
9594 diag::err_bound_member_function)
9595 << 0 << ovl.Expression->getSourceRange();
9596
9597 // TODO: I believe we only end up here if there's a mix of
9598 // static and non-static candidates (otherwise the expression
9599 // would have 'bound member' type, not 'overload' type).
9600 // Ideally we would note which candidate was chosen and why
9601 // the static candidates were rejected.
9602 SrcExpr = ExprError();
9603 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009604 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009605
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009606 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009607 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009608 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009609
9610 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009611 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009612 SingleFunctionExpression =
9613 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009614 if (SingleFunctionExpression.isInvalid()) {
9615 SrcExpr = ExprError();
9616 return true;
9617 }
9618 }
John McCall864c0412011-04-26 20:42:42 +00009619 }
9620
9621 if (!SingleFunctionExpression.isUsable()) {
9622 if (complain) {
9623 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9624 << ovl.Expression->getName()
9625 << DestTypeForComplaining
9626 << OpRangeForComplaining
9627 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009628 NoteAllOverloadCandidates(SrcExpr.get());
9629
9630 SrcExpr = ExprError();
9631 return true;
9632 }
9633
9634 return false;
John McCall864c0412011-04-26 20:42:42 +00009635 }
9636
John McCall6dbba4f2011-10-11 23:14:30 +00009637 SrcExpr = SingleFunctionExpression;
9638 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009639}
9640
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009641/// \brief Add a single candidate to the overload set.
9642static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009643 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009644 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009645 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009646 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009647 bool PartialOverloading,
9648 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009649 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009650 if (isa<UsingShadowDecl>(Callee))
9651 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9652
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009653 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009654 if (ExplicitTemplateArgs) {
9655 assert(!KnownValid && "Explicit template arguments?");
9656 return;
9657 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009658 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9659 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009660 return;
John McCallba135432009-11-21 08:51:07 +00009661 }
9662
9663 if (FunctionTemplateDecl *FuncTemplate
9664 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009665 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009666 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009667 return;
9668 }
9669
Richard Smith2ced0442011-06-26 22:19:54 +00009670 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009671}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009672
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009673/// \brief Add the overload candidates named by callee and/or found by argument
9674/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009675void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009676 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009677 OverloadCandidateSet &CandidateSet,
9678 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009679
9680#ifndef NDEBUG
9681 // Verify that ArgumentDependentLookup is consistent with the rules
9682 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009683 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009684 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9685 // and let Y be the lookup set produced by argument dependent
9686 // lookup (defined as follows). If X contains
9687 //
9688 // -- a declaration of a class member, or
9689 //
9690 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009691 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009692 //
9693 // -- a declaration that is neither a function or a function
9694 // template
9695 //
9696 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009697
John McCall3b4294e2009-12-16 12:17:52 +00009698 if (ULE->requiresADL()) {
9699 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9700 E = ULE->decls_end(); I != E; ++I) {
9701 assert(!(*I)->getDeclContext()->isRecord());
9702 assert(isa<UsingShadowDecl>(*I) ||
9703 !(*I)->getDeclContext()->isFunctionOrMethod());
9704 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009705 }
9706 }
9707#endif
9708
John McCall3b4294e2009-12-16 12:17:52 +00009709 // It would be nice to avoid this copy.
9710 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009711 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009712 if (ULE->hasExplicitTemplateArgs()) {
9713 ULE->copyTemplateArgumentsInto(TABuffer);
9714 ExplicitTemplateArgs = &TABuffer;
9715 }
9716
9717 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9718 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009719 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9720 CandidateSet, PartialOverloading,
9721 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009722
John McCall3b4294e2009-12-16 12:17:52 +00009723 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009724 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009725 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009726 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009727 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009728}
John McCall578b69b2009-12-16 08:11:27 +00009729
Richard Smithd3ff3252013-06-12 22:56:54 +00009730/// Determine whether a declaration with the specified name could be moved into
9731/// a different namespace.
9732static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9733 switch (Name.getCXXOverloadedOperator()) {
9734 case OO_New: case OO_Array_New:
9735 case OO_Delete: case OO_Array_Delete:
9736 return false;
9737
9738 default:
9739 return true;
9740 }
9741}
9742
Richard Smithf50e88a2011-06-05 22:42:48 +00009743/// Attempt to recover from an ill-formed use of a non-dependent name in a
9744/// template, where the non-dependent name was declared after the template
9745/// was defined. This is common in code written for a compilers which do not
9746/// correctly implement two-stage name lookup.
9747///
9748/// Returns true if a viable candidate was found and a diagnostic was issued.
9749static bool
9750DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9751 const CXXScopeSpec &SS, LookupResult &R,
9752 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009753 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009754 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9755 return false;
9756
9757 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009758 if (DC->isTransparentContext())
9759 continue;
9760
Richard Smithf50e88a2011-06-05 22:42:48 +00009761 SemaRef.LookupQualifiedName(R, DC);
9762
9763 if (!R.empty()) {
9764 R.suppressDiagnostics();
9765
9766 if (isa<CXXRecordDecl>(DC)) {
9767 // Don't diagnose names we find in classes; we get much better
9768 // diagnostics for these from DiagnoseEmptyLookup.
9769 R.clear();
9770 return false;
9771 }
9772
9773 OverloadCandidateSet Candidates(FnLoc);
9774 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9775 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009776 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009777 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009778
9779 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009780 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009781 // No viable functions. Don't bother the user with notes for functions
9782 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009783 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009784 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009785 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009786
9787 // Find the namespaces where ADL would have looked, and suggest
9788 // declaring the function there instead.
9789 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9790 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009791 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009792 AssociatedNamespaces,
9793 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009794 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009795 if (canBeDeclaredInNamespace(R.getLookupName())) {
9796 DeclContext *Std = SemaRef.getStdNamespace();
9797 for (Sema::AssociatedNamespaceSet::iterator
9798 it = AssociatedNamespaces.begin(),
9799 end = AssociatedNamespaces.end(); it != end; ++it) {
9800 // Never suggest declaring a function within namespace 'std'.
9801 if (Std && Std->Encloses(*it))
9802 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009803
Richard Smithd3ff3252013-06-12 22:56:54 +00009804 // Never suggest declaring a function within a namespace with a
9805 // reserved name, like __gnu_cxx.
9806 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9807 if (NS &&
9808 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9809 continue;
9810
9811 SuggestedNamespaces.insert(*it);
9812 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009813 }
9814
9815 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9816 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009817 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009818 SemaRef.Diag(Best->Function->getLocation(),
9819 diag::note_not_found_by_two_phase_lookup)
9820 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009821 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009822 SemaRef.Diag(Best->Function->getLocation(),
9823 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009824 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009825 } else {
9826 // FIXME: It would be useful to list the associated namespaces here,
9827 // but the diagnostics infrastructure doesn't provide a way to produce
9828 // a localized representation of a list of items.
9829 SemaRef.Diag(Best->Function->getLocation(),
9830 diag::note_not_found_by_two_phase_lookup)
9831 << R.getLookupName() << 2;
9832 }
9833
9834 // Try to recover by calling this function.
9835 return true;
9836 }
9837
9838 R.clear();
9839 }
9840
9841 return false;
9842}
9843
9844/// Attempt to recover from ill-formed use of a non-dependent operator in a
9845/// template, where the non-dependent operator was declared after the template
9846/// was defined.
9847///
9848/// Returns true if a viable candidate was found and a diagnostic was issued.
9849static bool
9850DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9851 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009852 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009853 DeclarationName OpName =
9854 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9855 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9856 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009857 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009858}
9859
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009860namespace {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009861class BuildRecoveryCallExprRAII {
9862 Sema &SemaRef;
9863public:
9864 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9865 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9866 SemaRef.IsBuildingRecoveryCallExpr = true;
9867 }
9868
9869 ~BuildRecoveryCallExprRAII() {
9870 SemaRef.IsBuildingRecoveryCallExpr = false;
9871 }
9872};
9873
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009874}
9875
John McCall578b69b2009-12-16 08:11:27 +00009876/// Attempts to recover from a call where no functions were found.
9877///
9878/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009879static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009880BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009881 UnresolvedLookupExpr *ULE,
9882 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009883 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009884 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009885 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009886 // Do not try to recover if it is already building a recovery call.
9887 // This stops infinite loops for template instantiations like
9888 //
9889 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9890 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9891 //
9892 if (SemaRef.IsBuildingRecoveryCallExpr)
9893 return ExprError();
9894 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009895
9896 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009897 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009898 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009899
John McCall3b4294e2009-12-16 12:17:52 +00009900 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009901 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009902 if (ULE->hasExplicitTemplateArgs()) {
9903 ULE->copyTemplateArgumentsInto(TABuffer);
9904 ExplicitTemplateArgs = &TABuffer;
9905 }
9906
John McCall578b69b2009-12-16 08:11:27 +00009907 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9908 Sema::LookupOrdinaryName);
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00009909 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
9910 ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009911 NoTypoCorrectionCCC RejectAll;
9912 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9913 (CorrectionCandidateCallback*)&Validator :
9914 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009915 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009916 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009917 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009918 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009919 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009920 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009921
John McCall3b4294e2009-12-16 12:17:52 +00009922 assert(!R.empty() && "lookup results empty despite recovery");
9923
9924 // Build an implicit member call if appropriate. Just drop the
9925 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009926 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009927 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009928 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9929 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009930 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009931 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009932 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009933 else
9934 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9935
9936 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009937 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009938
9939 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009940 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009941 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009942 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009943 MultiExprArg(Args.data(), Args.size()),
9944 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009945}
Douglas Gregord7a95972010-06-08 17:35:15 +00009946
Sam Panzere1715b62012-08-21 00:52:01 +00009947/// \brief Constructs and populates an OverloadedCandidateSet from
9948/// the given function.
9949/// \returns true when an the ExprResult output parameter has been set.
9950bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9951 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009952 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +00009953 SourceLocation RParenLoc,
9954 OverloadCandidateSet *CandidateSet,
9955 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009956#ifndef NDEBUG
9957 if (ULE->requiresADL()) {
9958 // To do ADL, we must have found an unqualified name.
9959 assert(!ULE->getQualifier() && "qualified name with ADL");
9960
9961 // We don't perform ADL for implicit declarations of builtins.
9962 // Verify that this was correctly set up.
9963 FunctionDecl *F;
9964 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9965 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9966 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009967 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009968
John McCall3b4294e2009-12-16 12:17:52 +00009969 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009970 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009971 }
John McCall3b4294e2009-12-16 12:17:52 +00009972#endif
9973
John McCall5acb0c92011-10-17 18:40:02 +00009974 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009975 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +00009976 *Result = ExprError();
9977 return true;
9978 }
Douglas Gregor17330012009-02-04 15:01:18 +00009979
John McCall3b4294e2009-12-16 12:17:52 +00009980 // Add the functions denoted by the callee to the set of candidate
9981 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009982 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009983
9984 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009985 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9986 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009987 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009988 // In Microsoft mode, if we are inside a template class member function then
9989 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009990 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009991 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009992 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009993 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00009994 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009995 Context.DependentTy, VK_RValue,
9996 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009997 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009998 *Result = Owned(CE);
9999 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010000 }
Sam Panzere1715b62012-08-21 00:52:01 +000010001 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010002 }
John McCall578b69b2009-12-16 08:11:27 +000010003
John McCall5acb0c92011-10-17 18:40:02 +000010004 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010005 return false;
10006}
John McCall5acb0c92011-10-17 18:40:02 +000010007
Sam Panzere1715b62012-08-21 00:52:01 +000010008/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10009/// the completed call expression. If overload resolution fails, emits
10010/// diagnostics and returns ExprError()
10011static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10012 UnresolvedLookupExpr *ULE,
10013 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010014 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010015 SourceLocation RParenLoc,
10016 Expr *ExecConfig,
10017 OverloadCandidateSet *CandidateSet,
10018 OverloadCandidateSet::iterator *Best,
10019 OverloadingResult OverloadResult,
10020 bool AllowTypoCorrection) {
10021 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010022 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010023 RParenLoc, /*EmptyLookup=*/true,
10024 AllowTypoCorrection);
10025
10026 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010027 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010028 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010029 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010030 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10031 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010032 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010033 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10034 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010035 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010036
Richard Smithf50e88a2011-06-05 22:42:48 +000010037 case OR_No_Viable_Function: {
10038 // Try to recover by looking for viable functions which the user might
10039 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010040 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010041 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010042 /*EmptyLookup=*/false,
10043 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010044 if (!Recovery.isInvalid())
10045 return Recovery;
10046
Sam Panzere1715b62012-08-21 00:52:01 +000010047 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010048 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010049 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010050 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010051 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010052 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010053
10054 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010055 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010056 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010057 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010058 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010059
Sam Panzere1715b62012-08-21 00:52:01 +000010060 case OR_Deleted: {
10061 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10062 << (*Best)->Function->isDeleted()
10063 << ULE->getName()
10064 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10065 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010066 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010067
Sam Panzere1715b62012-08-21 00:52:01 +000010068 // We emitted an error for the unvailable/deleted function call but keep
10069 // the call in the AST.
10070 FunctionDecl *FDecl = (*Best)->Function;
10071 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010072 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10073 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010074 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010075 }
10076
Douglas Gregorff331c12010-07-25 18:17:45 +000010077 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010078 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010079}
10080
Sam Panzere1715b62012-08-21 00:52:01 +000010081/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10082/// (which eventually refers to the declaration Func) and the call
10083/// arguments Args/NumArgs, attempt to resolve the function call down
10084/// to a specific function. If overload resolution succeeds, returns
10085/// the call expression produced by overload resolution.
10086/// Otherwise, emits diagnostics and returns ExprError.
10087ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10088 UnresolvedLookupExpr *ULE,
10089 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010090 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010091 SourceLocation RParenLoc,
10092 Expr *ExecConfig,
10093 bool AllowTypoCorrection) {
10094 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10095 ExprResult result;
10096
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010097 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10098 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010099 return result;
10100
10101 OverloadCandidateSet::iterator Best;
10102 OverloadingResult OverloadResult =
10103 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10104
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010105 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010106 RParenLoc, ExecConfig, &CandidateSet,
10107 &Best, OverloadResult,
10108 AllowTypoCorrection);
10109}
10110
John McCall6e266892010-01-26 03:27:55 +000010111static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010112 return Functions.size() > 1 ||
10113 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10114}
10115
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010116/// \brief Create a unary operation that may resolve to an overloaded
10117/// operator.
10118///
10119/// \param OpLoc The location of the operator itself (e.g., '*').
10120///
10121/// \param OpcIn The UnaryOperator::Opcode that describes this
10122/// operator.
10123///
James Dennett40ae6662012-06-22 08:52:37 +000010124/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010125/// considered by overload resolution. The caller needs to build this
10126/// set based on the context using, e.g.,
10127/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10128/// set should not contain any member functions; those will be added
10129/// by CreateOverloadedUnaryOp().
10130///
James Dennett8da16872012-06-22 10:32:46 +000010131/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010132ExprResult
John McCall6e266892010-01-26 03:27:55 +000010133Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10134 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010135 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010136 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010137
10138 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10139 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10140 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010141 // TODO: provide better source location info.
10142 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010143
John McCall5acb0c92011-10-17 18:40:02 +000010144 if (checkPlaceholderForOverload(*this, Input))
10145 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010146
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010147 Expr *Args[2] = { Input, 0 };
10148 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010149
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010150 // For post-increment and post-decrement, add the implicit '0' as
10151 // the second argument, so that we know this is a post-increment or
10152 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010153 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010154 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010155 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10156 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010157 NumArgs = 2;
10158 }
10159
Richard Smith958ba642013-05-05 15:51:06 +000010160 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10161
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010162 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010163 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010164 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010165 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010166 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010167 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010168 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010169
John McCallc373d482010-01-27 01:50:18 +000010170 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010171 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010172 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010173 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010174 /*ADL*/ true, IsOverloaded(Fns),
10175 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010176 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010177 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010178 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010179 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010180 }
10181
10182 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010183 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010184
10185 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010186 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010187
10188 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010189 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010190
John McCall6e266892010-01-26 03:27:55 +000010191 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010192 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10193 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010194 CandidateSet);
10195
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010196 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010197 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010198
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010199 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10200
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010201 // Perform overload resolution.
10202 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010203 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010204 case OR_Success: {
10205 // We found a built-in operator or an overloaded operator.
10206 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010207
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010208 if (FnDecl) {
10209 // We matched an overloaded operator. Build a call to that
10210 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010211
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010212 // Convert the arguments.
10213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010214 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010215
John Wiegley429bb272011-04-08 18:41:53 +000010216 ExprResult InputRes =
10217 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10218 Best->FoundDecl, Method);
10219 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010220 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010221 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010222 } else {
10223 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010224 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010225 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010226 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010227 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010228 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010229 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010230 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010231 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010232 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010233 }
10234
John McCallf89e55a2010-11-18 06:31:45 +000010235 // Determine the result type.
10236 QualType ResultTy = FnDecl->getResultType();
10237 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10238 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010239
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010240 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010242 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010243 if (FnExpr.isInvalid())
10244 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010245
Eli Friedman4c3b8962009-11-18 03:58:17 +000010246 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010247 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010248 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010249 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010250
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010251 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010252 FnDecl))
10253 return ExprError();
10254
John McCall9ae2f072010-08-23 23:25:46 +000010255 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010256 } else {
10257 // We matched a built-in operator. Convert the arguments, then
10258 // break out so that we will build the appropriate built-in
10259 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010260 ExprResult InputRes =
10261 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10262 Best->Conversions[0], AA_Passing);
10263 if (InputRes.isInvalid())
10264 return ExprError();
10265 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010266 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010267 }
John Wiegley429bb272011-04-08 18:41:53 +000010268 }
10269
10270 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010271 // This is an erroneous use of an operator which can be overloaded by
10272 // a non-member function. Check for non-member operators which were
10273 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010274 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010275 // FIXME: Recover by calling the found function.
10276 return ExprError();
10277
John Wiegley429bb272011-04-08 18:41:53 +000010278 // No viable function; fall through to handling this as a
10279 // built-in operator, which will produce an error message for us.
10280 break;
10281
10282 case OR_Ambiguous:
10283 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10284 << UnaryOperator::getOpcodeStr(Opc)
10285 << Input->getType()
10286 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010287 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010288 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10289 return ExprError();
10290
10291 case OR_Deleted:
10292 Diag(OpLoc, diag::err_ovl_deleted_oper)
10293 << Best->Function->isDeleted()
10294 << UnaryOperator::getOpcodeStr(Opc)
10295 << getDeletedOrUnavailableSuffix(Best->Function)
10296 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010297 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010298 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010299 return ExprError();
10300 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010301
10302 // Either we found no viable overloaded operator or we matched a
10303 // built-in operator. In either case, fall through to trying to
10304 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010305 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010306}
10307
Douglas Gregor063daf62009-03-13 18:40:31 +000010308/// \brief Create a binary operation that may resolve to an overloaded
10309/// operator.
10310///
10311/// \param OpLoc The location of the operator itself (e.g., '+').
10312///
10313/// \param OpcIn The BinaryOperator::Opcode that describes this
10314/// operator.
10315///
James Dennett40ae6662012-06-22 08:52:37 +000010316/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010317/// considered by overload resolution. The caller needs to build this
10318/// set based on the context using, e.g.,
10319/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10320/// set should not contain any member functions; those will be added
10321/// by CreateOverloadedBinOp().
10322///
10323/// \param LHS Left-hand argument.
10324/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010325ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010326Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010327 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010328 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010329 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010330 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010331 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010332
10333 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10334 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10335 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10336
10337 // If either side is type-dependent, create an appropriate dependent
10338 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010339 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010340 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010341 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010342 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010343 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010344 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010345 Context.DependentTy,
10346 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010347 OpLoc,
10348 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010349
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010350 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10351 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010352 VK_LValue,
10353 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010354 Context.DependentTy,
10355 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010356 OpLoc,
10357 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010358 }
John McCall6e266892010-01-26 03:27:55 +000010359
10360 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010361 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010362 // TODO: provide better source location info in DNLoc component.
10363 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010364 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010365 = UnresolvedLookupExpr::Create(Context, NamingClass,
10366 NestedNameSpecifierLoc(), OpNameInfo,
10367 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010368 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010369 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10370 Context.DependentTy, VK_RValue,
10371 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010372 }
10373
John McCall5acb0c92011-10-17 18:40:02 +000010374 // Always do placeholder-like conversions on the RHS.
10375 if (checkPlaceholderForOverload(*this, Args[1]))
10376 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010377
John McCall3c3b7f92011-10-25 17:37:35 +000010378 // Do placeholder-like conversion on the LHS; note that we should
10379 // not get here with a PseudoObject LHS.
10380 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010381 if (checkPlaceholderForOverload(*this, Args[0]))
10382 return ExprError();
10383
Sebastian Redl275c2b42009-11-18 23:10:33 +000010384 // If this is the assignment operator, we only perform overload resolution
10385 // if the left-hand side is a class or enumeration type. This is actually
10386 // a hack. The standard requires that we do overload resolution between the
10387 // various built-in candidates, but as DR507 points out, this can lead to
10388 // problems. So we do it this way, which pretty much follows what GCC does.
10389 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010390 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010391 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010392
John McCall0e800c92010-12-04 08:14:53 +000010393 // If this is the .* operator, which is not overloadable, just
10394 // create a built-in binary operator.
10395 if (Opc == BO_PtrMemD)
10396 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10397
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010398 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010399 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010400
10401 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010402 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010403
10404 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010405 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010406
John McCall6e266892010-01-26 03:27:55 +000010407 // Add candidates from ADL.
10408 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010409 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010410 /*ExplicitTemplateArgs*/ 0,
10411 CandidateSet);
10412
Douglas Gregor063daf62009-03-13 18:40:31 +000010413 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010414 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010415
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010416 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10417
Douglas Gregor063daf62009-03-13 18:40:31 +000010418 // Perform overload resolution.
10419 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010420 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010421 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010422 // We found a built-in operator or an overloaded operator.
10423 FunctionDecl *FnDecl = Best->Function;
10424
10425 if (FnDecl) {
10426 // We matched an overloaded operator. Build a call to that
10427 // operator.
10428
10429 // Convert the arguments.
10430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010431 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010432 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010433
Chandler Carruth6df868e2010-12-12 08:17:55 +000010434 ExprResult Arg1 =
10435 PerformCopyInitialization(
10436 InitializedEntity::InitializeParameter(Context,
10437 FnDecl->getParamDecl(0)),
10438 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010439 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010440 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010441
John Wiegley429bb272011-04-08 18:41:53 +000010442 ExprResult Arg0 =
10443 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10444 Best->FoundDecl, Method);
10445 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010446 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010447 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010448 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010449 } else {
10450 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010451 ExprResult Arg0 = PerformCopyInitialization(
10452 InitializedEntity::InitializeParameter(Context,
10453 FnDecl->getParamDecl(0)),
10454 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010455 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010456 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010457
Chandler Carruth6df868e2010-12-12 08:17:55 +000010458 ExprResult Arg1 =
10459 PerformCopyInitialization(
10460 InitializedEntity::InitializeParameter(Context,
10461 FnDecl->getParamDecl(1)),
10462 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010463 if (Arg1.isInvalid())
10464 return ExprError();
10465 Args[0] = LHS = Arg0.takeAs<Expr>();
10466 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010467 }
10468
John McCallf89e55a2010-11-18 06:31:45 +000010469 // Determine the result type.
10470 QualType ResultTy = FnDecl->getResultType();
10471 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10472 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010473
10474 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010475 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010476 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010477 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010478 if (FnExpr.isInvalid())
10479 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010480
John McCall9ae2f072010-08-23 23:25:46 +000010481 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010482 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010483 Args, ResultTy, VK, OpLoc,
10484 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010485
10486 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010487 FnDecl))
10488 return ExprError();
10489
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010490 ArrayRef<const Expr *> ArgsArray(Args, 2);
10491 // Cut off the implicit 'this'.
10492 if (isa<CXXMethodDecl>(FnDecl))
10493 ArgsArray = ArgsArray.slice(1);
10494 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10495 TheCall->getSourceRange(), VariadicDoesNotApply);
10496
John McCall9ae2f072010-08-23 23:25:46 +000010497 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010498 } else {
10499 // We matched a built-in operator. Convert the arguments, then
10500 // break out so that we will build the appropriate built-in
10501 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010502 ExprResult ArgsRes0 =
10503 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10504 Best->Conversions[0], AA_Passing);
10505 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010506 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010507 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010508
John Wiegley429bb272011-04-08 18:41:53 +000010509 ExprResult ArgsRes1 =
10510 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10511 Best->Conversions[1], AA_Passing);
10512 if (ArgsRes1.isInvalid())
10513 return ExprError();
10514 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010515 break;
10516 }
10517 }
10518
Douglas Gregor33074752009-09-30 21:46:01 +000010519 case OR_No_Viable_Function: {
10520 // C++ [over.match.oper]p9:
10521 // If the operator is the operator , [...] and there are no
10522 // viable functions, then the operator is assumed to be the
10523 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010524 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010525 break;
10526
Chandler Carruth6df868e2010-12-12 08:17:55 +000010527 // For class as left operand for assignment or compound assigment
10528 // operator do not fall through to handling in built-in, but report that
10529 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010530 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010531 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010532 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010533 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10534 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010535 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010536 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010537 // This is an erroneous use of an operator which can be overloaded by
10538 // a non-member function. Check for non-member operators which were
10539 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010540 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010541 // FIXME: Recover by calling the found function.
10542 return ExprError();
10543
Douglas Gregor33074752009-09-30 21:46:01 +000010544 // No viable function; try to create a built-in operation, which will
10545 // produce an error. Then, show the non-viable candidates.
10546 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010547 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010548 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010549 "C++ binary operator overloading is missing candidates!");
10550 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010551 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010552 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010553 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010554 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010555
10556 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010557 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010558 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010559 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010560 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010561 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010562 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010563 return ExprError();
10564
10565 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010566 if (isImplicitlyDeleted(Best->Function)) {
10567 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10568 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010569 << Context.getRecordType(Method->getParent())
10570 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010571
Richard Smith0f46e642012-12-28 12:23:24 +000010572 // The user probably meant to call this special member. Just
10573 // explain why it's deleted.
10574 NoteDeletedFunction(Method);
10575 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010576 } else {
10577 Diag(OpLoc, diag::err_ovl_deleted_oper)
10578 << Best->Function->isDeleted()
10579 << BinaryOperator::getOpcodeStr(Opc)
10580 << getDeletedOrUnavailableSuffix(Best->Function)
10581 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10582 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010583 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010584 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010585 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010586 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010587
Douglas Gregor33074752009-09-30 21:46:01 +000010588 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010589 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010590}
10591
John McCall60d7b3a2010-08-24 06:29:42 +000010592ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010593Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10594 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010595 Expr *Base, Expr *Idx) {
10596 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010597 DeclarationName OpName =
10598 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10599
10600 // If either side is type-dependent, create an appropriate dependent
10601 // expression.
10602 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10603
John McCallc373d482010-01-27 01:50:18 +000010604 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010605 // CHECKME: no 'operator' keyword?
10606 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10607 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010608 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010609 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010610 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010611 /*ADL*/ true, /*Overloaded*/ false,
10612 UnresolvedSetIterator(),
10613 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010614 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010615
Sebastian Redlf322ed62009-10-29 20:17:01 +000010616 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010617 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010618 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010619 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010620 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010621 }
10622
John McCall5acb0c92011-10-17 18:40:02 +000010623 // Handle placeholders on both operands.
10624 if (checkPlaceholderForOverload(*this, Args[0]))
10625 return ExprError();
10626 if (checkPlaceholderForOverload(*this, Args[1]))
10627 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010628
Sebastian Redlf322ed62009-10-29 20:17:01 +000010629 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010630 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010631
10632 // Subscript can only be overloaded as a member function.
10633
10634 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010635 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010636
10637 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010638 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010639
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010640 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10641
Sebastian Redlf322ed62009-10-29 20:17:01 +000010642 // Perform overload resolution.
10643 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010644 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010645 case OR_Success: {
10646 // We found a built-in operator or an overloaded operator.
10647 FunctionDecl *FnDecl = Best->Function;
10648
10649 if (FnDecl) {
10650 // We matched an overloaded operator. Build a call to that
10651 // operator.
10652
John McCall9aa472c2010-03-19 07:35:19 +000010653 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010654
Sebastian Redlf322ed62009-10-29 20:17:01 +000010655 // Convert the arguments.
10656 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010657 ExprResult Arg0 =
10658 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10659 Best->FoundDecl, Method);
10660 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010661 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010662 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010663
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010664 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010665 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010666 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010667 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010668 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010669 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010670 Owned(Args[1]));
10671 if (InputInit.isInvalid())
10672 return ExprError();
10673
10674 Args[1] = InputInit.takeAs<Expr>();
10675
Sebastian Redlf322ed62009-10-29 20:17:01 +000010676 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010677 QualType ResultTy = FnDecl->getResultType();
10678 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10679 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010680
10681 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010682 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10683 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010684 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010685 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010686 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010687 OpLocInfo.getLoc(),
10688 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010689 if (FnExpr.isInvalid())
10690 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010691
John McCall9ae2f072010-08-23 23:25:46 +000010692 CXXOperatorCallExpr *TheCall =
10693 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010694 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010695 ResultTy, VK, RLoc,
10696 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010697
John McCall9ae2f072010-08-23 23:25:46 +000010698 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010699 FnDecl))
10700 return ExprError();
10701
John McCall9ae2f072010-08-23 23:25:46 +000010702 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010703 } else {
10704 // We matched a built-in operator. Convert the arguments, then
10705 // break out so that we will build the appropriate built-in
10706 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010707 ExprResult ArgsRes0 =
10708 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10709 Best->Conversions[0], AA_Passing);
10710 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010711 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010712 Args[0] = ArgsRes0.take();
10713
10714 ExprResult ArgsRes1 =
10715 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10716 Best->Conversions[1], AA_Passing);
10717 if (ArgsRes1.isInvalid())
10718 return ExprError();
10719 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010720
10721 break;
10722 }
10723 }
10724
10725 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010726 if (CandidateSet.empty())
10727 Diag(LLoc, diag::err_ovl_no_oper)
10728 << Args[0]->getType() << /*subscript*/ 0
10729 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10730 else
10731 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10732 << Args[0]->getType()
10733 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010734 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010735 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010736 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010737 }
10738
10739 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010740 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010741 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010742 << Args[0]->getType() << Args[1]->getType()
10743 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010744 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010745 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010746 return ExprError();
10747
10748 case OR_Deleted:
10749 Diag(LLoc, diag::err_ovl_deleted_oper)
10750 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010751 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010752 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010753 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010754 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010755 return ExprError();
10756 }
10757
10758 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010759 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010760}
10761
Douglas Gregor88a35142008-12-22 05:46:06 +000010762/// BuildCallToMemberFunction - Build a call to a member
10763/// function. MemExpr is the expression that refers to the member
10764/// function (and includes the object parameter), Args/NumArgs are the
10765/// arguments to the function call (not including the object
10766/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010767/// expression refers to a non-static member function or an overloaded
10768/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010769ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010770Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010771 SourceLocation LParenLoc,
10772 MultiExprArg Args,
10773 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010774 assert(MemExprE->getType() == Context.BoundMemberTy ||
10775 MemExprE->getType() == Context.OverloadTy);
10776
Douglas Gregor88a35142008-12-22 05:46:06 +000010777 // Dig out the member expression. This holds both the object
10778 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010779 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010780
John McCall864c0412011-04-26 20:42:42 +000010781 // Determine whether this is a call to a pointer-to-member function.
10782 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10783 assert(op->getType() == Context.BoundMemberTy);
10784 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10785
10786 QualType fnType =
10787 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10788
10789 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10790 QualType resultType = proto->getCallResultType(Context);
10791 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10792
10793 // Check that the object type isn't more qualified than the
10794 // member function we're calling.
10795 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10796
10797 QualType objectType = op->getLHS()->getType();
10798 if (op->getOpcode() == BO_PtrMemI)
10799 objectType = objectType->castAs<PointerType>()->getPointeeType();
10800 Qualifiers objectQuals = objectType.getQualifiers();
10801
10802 Qualifiers difference = objectQuals - funcQuals;
10803 difference.removeObjCGCAttr();
10804 difference.removeAddressSpace();
10805 if (difference) {
10806 std::string qualsString = difference.getAsString();
10807 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10808 << fnType.getUnqualifiedType()
10809 << qualsString
10810 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10811 }
10812
10813 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010814 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000010815 resultType, valueKind, RParenLoc);
10816
10817 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010818 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010819 call, 0))
10820 return ExprError();
10821
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010822 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000010823 return ExprError();
10824
Richard Trieue2a90b82013-06-22 02:30:38 +000010825 if (CheckOtherCall(call, proto))
10826 return ExprError();
10827
John McCall864c0412011-04-26 20:42:42 +000010828 return MaybeBindToTemporary(call);
10829 }
10830
John McCall5acb0c92011-10-17 18:40:02 +000010831 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010832 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000010833 return ExprError();
10834
John McCall129e2df2009-11-30 22:42:35 +000010835 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010836 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010837 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010838 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010839 if (isa<MemberExpr>(NakedMemExpr)) {
10840 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010841 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010842 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010843 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010844 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010845 } else {
10846 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010847 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010848
John McCall701c89e2009-12-03 04:06:58 +000010849 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010850 Expr::Classification ObjectClassification
10851 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10852 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010853
Douglas Gregor88a35142008-12-22 05:46:06 +000010854 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010855 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010856
John McCallaa81e162009-12-01 22:10:20 +000010857 // FIXME: avoid copy.
10858 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10859 if (UnresExpr->hasExplicitTemplateArgs()) {
10860 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10861 TemplateArgs = &TemplateArgsBuffer;
10862 }
10863
John McCall129e2df2009-11-30 22:42:35 +000010864 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10865 E = UnresExpr->decls_end(); I != E; ++I) {
10866
John McCall701c89e2009-12-03 04:06:58 +000010867 NamedDecl *Func = *I;
10868 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10869 if (isa<UsingShadowDecl>(Func))
10870 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10871
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010872
Francois Pichetdbee3412011-01-18 05:04:39 +000010873 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010874 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010875 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010876 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010877 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010878 // If explicit template arguments were provided, we can't call a
10879 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010880 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010881 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010882
John McCall9aa472c2010-03-19 07:35:19 +000010883 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010884 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010885 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010886 } else {
John McCall129e2df2009-11-30 22:42:35 +000010887 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010888 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010889 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010890 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010891 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010892 }
Douglas Gregordec06662009-08-21 18:42:58 +000010893 }
Mike Stump1eb44332009-09-09 15:08:12 +000010894
John McCall129e2df2009-11-30 22:42:35 +000010895 DeclarationName DeclName = UnresExpr->getMemberName();
10896
John McCall5acb0c92011-10-17 18:40:02 +000010897 UnbridgedCasts.restore();
10898
Douglas Gregor88a35142008-12-22 05:46:06 +000010899 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010900 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010901 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010902 case OR_Success:
10903 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010904 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010905 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010906 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
10907 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000010908 // If FoundDecl is different from Method (such as if one is a template
10909 // and the other a specialization), make sure DiagnoseUseOfDecl is
10910 // called on both.
10911 // FIXME: This would be more comprehensively addressed by modifying
10912 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
10913 // being used.
10914 if (Method != FoundDecl.getDecl() &&
10915 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
10916 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010917 break;
10918
10919 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010920 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010921 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010922 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010923 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000010924 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010925 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010926
10927 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010928 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010929 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010930 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000010931 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010932 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010933
10934 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010935 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010936 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010937 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010938 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010939 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010940 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010941 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010942 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010943 }
10944
John McCall6bb80172010-03-30 21:47:33 +000010945 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010946
John McCallaa81e162009-12-01 22:10:20 +000010947 // If overload resolution picked a static member, build a
10948 // non-member call based on that function.
10949 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010950 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
10951 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000010952 }
10953
John McCall129e2df2009-11-30 22:42:35 +000010954 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010955 }
10956
John McCallf89e55a2010-11-18 06:31:45 +000010957 QualType ResultType = Method->getResultType();
10958 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10959 ResultType = ResultType.getNonLValueExprType(Context);
10960
Douglas Gregor88a35142008-12-22 05:46:06 +000010961 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010962 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010963 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000010964 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010965
Anders Carlssoneed3e692009-10-10 00:06:20 +000010966 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010967 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010968 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010969 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010970
Douglas Gregor88a35142008-12-22 05:46:06 +000010971 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010972 // We only need to do this if there was actually an overload; otherwise
10973 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010974 if (!Method->isStatic()) {
10975 ExprResult ObjectArg =
10976 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10977 FoundDecl, Method);
10978 if (ObjectArg.isInvalid())
10979 return ExprError();
10980 MemExpr->setBase(ObjectArg.take());
10981 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010982
10983 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010984 const FunctionProtoType *Proto =
10985 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010986 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000010987 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010988 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010989
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010990 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000010991
Richard Smith831421f2012-06-25 20:30:08 +000010992 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010993 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010994
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010995 if ((isa<CXXConstructorDecl>(CurContext) ||
10996 isa<CXXDestructorDecl>(CurContext)) &&
10997 TheCall->getMethodDecl()->isPure()) {
10998 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10999
Chandler Carruthae198062011-06-27 08:31:58 +000011000 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011001 Diag(MemExpr->getLocStart(),
11002 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11003 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11004 << MD->getParent()->getDeclName();
11005
11006 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011007 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011008 }
John McCall9ae2f072010-08-23 23:25:46 +000011009 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011010}
11011
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011012/// BuildCallToObjectOfClassType - Build a call to an object of class
11013/// type (C++ [over.call.object]), which can end up invoking an
11014/// overloaded function call operator (@c operator()) or performing a
11015/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011016ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011017Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011018 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011019 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011020 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011021 if (checkPlaceholderForOverload(*this, Obj))
11022 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011023 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011024
11025 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011026 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011027 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011028
John Wiegley429bb272011-04-08 18:41:53 +000011029 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11030 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011031
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011032 // C++ [over.call.object]p1:
11033 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011034 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011035 // candidate functions includes at least the function call
11036 // operators of T. The function call operators of T are obtained by
11037 // ordinary lookup of the name operator() in the context of
11038 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011039 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011040 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011041
John Wiegley429bb272011-04-08 18:41:53 +000011042 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011043 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011044 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011045
John McCalla24dc2e2009-11-17 02:14:36 +000011046 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11047 LookupQualifiedName(R, Record->getDecl());
11048 R.suppressDiagnostics();
11049
Douglas Gregor593564b2009-11-15 07:48:03 +000011050 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011051 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011052 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011053 Object.get()->Classify(Context),
11054 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011055 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011056 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011057
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011058 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011059 // In addition, for each (non-explicit in C++0x) conversion function
11060 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011061 //
11062 // operator conversion-type-id () cv-qualifier;
11063 //
11064 // where cv-qualifier is the same cv-qualification as, or a
11065 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011066 // denotes the type "pointer to function of (P1,...,Pn) returning
11067 // R", or the type "reference to pointer to function of
11068 // (P1,...,Pn) returning R", or the type "reference to function
11069 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011070 // is also considered as a candidate function. Similarly,
11071 // surrogate call functions are added to the set of candidate
11072 // functions for each conversion function declared in an
11073 // accessible base class provided the function is not hidden
11074 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011075 std::pair<CXXRecordDecl::conversion_iterator,
11076 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011077 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011078 for (CXXRecordDecl::conversion_iterator
11079 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011080 NamedDecl *D = *I;
11081 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11082 if (isa<UsingShadowDecl>(D))
11083 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011084
Douglas Gregor4a27d702009-10-21 06:18:39 +000011085 // Skip over templated conversion functions; they aren't
11086 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011087 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011088 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011089
John McCall701c89e2009-12-03 04:06:58 +000011090 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011091 if (!Conv->isExplicit()) {
11092 // Strip the reference type (if any) and then the pointer type (if
11093 // any) to get down to what might be a function type.
11094 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11095 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11096 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011097
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011098 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11099 {
11100 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011101 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011102 }
11103 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011104 }
Mike Stump1eb44332009-09-09 15:08:12 +000011105
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011106 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11107
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011108 // Perform overload resolution.
11109 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011110 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011111 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011112 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011113 // Overload resolution succeeded; we'll build the appropriate call
11114 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011115 break;
11116
11117 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011118 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011119 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011120 << Object.get()->getType() << /*call*/ 1
11121 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011122 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011123 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011124 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011125 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011126 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011127 break;
11128
11129 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011130 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011131 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011132 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011133 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011134 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011135
11136 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011137 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011138 diag::err_ovl_deleted_object_call)
11139 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011140 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011141 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011142 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011143 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011144 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011145 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011146
Douglas Gregorff331c12010-07-25 18:17:45 +000011147 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011148 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011149
John McCall5acb0c92011-10-17 18:40:02 +000011150 UnbridgedCasts.restore();
11151
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011152 if (Best->Function == 0) {
11153 // Since there is no function declaration, this is one of the
11154 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011155 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011156 = cast<CXXConversionDecl>(
11157 Best->Conversions[0].UserDefined.ConversionFunction);
11158
John Wiegley429bb272011-04-08 18:41:53 +000011159 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011160 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11161 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011162 assert(Conv == Best->FoundDecl.getDecl() &&
11163 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011164 // We selected one of the surrogate functions that converts the
11165 // object parameter to a function pointer. Perform the conversion
11166 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011167
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011168 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011169 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011170 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11171 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011172 if (Call.isInvalid())
11173 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011174 // Record usage of conversion in an implicit cast.
11175 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11176 CK_UserDefinedConversion,
11177 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011178
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011179 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011180 }
11181
John Wiegley429bb272011-04-08 18:41:53 +000011182 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011183
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011184 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11185 // that calls this method, using Object for the implicit object
11186 // parameter and passing along the remaining arguments.
11187 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011188
11189 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011190 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011191 return ExprError();
11192
Chandler Carruth6df868e2010-12-12 08:17:55 +000011193 const FunctionProtoType *Proto =
11194 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011195
11196 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011197 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011198
11199 // Build the full argument list for the method call (the
11200 // implicit object parameter is placed at the beginning of the
11201 // list).
11202 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011203 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011204 NumArgsToCheck = NumArgsInProto;
11205 MethodArgs = new Expr*[NumArgsInProto + 1];
11206 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011207 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011208 }
John Wiegley429bb272011-04-08 18:41:53 +000011209 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011210 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011211 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011212
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011213 DeclarationNameInfo OpLocInfo(
11214 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11215 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011216 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011217 HadMultipleCandidates,
11218 OpLocInfo.getLoc(),
11219 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011220 if (NewFn.isInvalid())
11221 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011222
11223 // Once we've built TheCall, all of the expressions are properly
11224 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011225 QualType ResultTy = Method->getResultType();
11226 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11227 ResultTy = ResultTy.getNonLValueExprType(Context);
11228
John McCall9ae2f072010-08-23 23:25:46 +000011229 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011230 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011231 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011232 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011233 delete [] MethodArgs;
11234
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011235 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011236 Method))
11237 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011238
Douglas Gregor518fda12009-01-13 05:10:00 +000011239 // We may have default arguments. If so, we need to allocate more
11240 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011241 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011242 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011243 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011244 NumArgsToCheck = NumArgsInProto;
11245
Chris Lattner312531a2009-04-12 08:11:20 +000011246 bool IsError = false;
11247
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011248 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011249 ExprResult ObjRes =
11250 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11251 Best->FoundDecl, Method);
11252 if (ObjRes.isInvalid())
11253 IsError = true;
11254 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011255 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011256 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011257
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011258 // Check the argument types.
11259 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011260 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011261 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011262 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011263
Douglas Gregor518fda12009-01-13 05:10:00 +000011264 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011265
John McCall60d7b3a2010-08-24 06:29:42 +000011266 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011267 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011268 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011269 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011270 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011271
Anders Carlsson3faa4862010-01-29 18:43:53 +000011272 IsError |= InputInit.isInvalid();
11273 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011274 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011275 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011276 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11277 if (DefArg.isInvalid()) {
11278 IsError = true;
11279 break;
11280 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011281
Douglas Gregord47c47d2009-11-09 19:27:57 +000011282 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011283 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011284
11285 TheCall->setArg(i + 1, Arg);
11286 }
11287
11288 // If this is a variadic call, handle args passed through "...".
11289 if (Proto->isVariadic()) {
11290 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011291 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011292 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11293 IsError |= Arg.isInvalid();
11294 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011295 }
11296 }
11297
Chris Lattner312531a2009-04-12 08:11:20 +000011298 if (IsError) return true;
11299
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011300 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011301
Richard Smith831421f2012-06-25 20:30:08 +000011302 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011303 return true;
11304
John McCall182f7092010-08-24 06:09:16 +000011305 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011306}
11307
Douglas Gregor8ba10742008-11-20 16:27:02 +000011308/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011309/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011310/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011311ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011312Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011313 assert(Base->getType()->isRecordType() &&
11314 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011315
John McCall5acb0c92011-10-17 18:40:02 +000011316 if (checkPlaceholderForOverload(*this, Base))
11317 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011318
John McCall5769d612010-02-08 23:07:23 +000011319 SourceLocation Loc = Base->getExprLoc();
11320
Douglas Gregor8ba10742008-11-20 16:27:02 +000011321 // C++ [over.ref]p1:
11322 //
11323 // [...] An expression x->m is interpreted as (x.operator->())->m
11324 // for a class object x of type T if T::operator->() exists and if
11325 // the operator is selected as the best match function by the
11326 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011327 DeclarationName OpName =
11328 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011329 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011330 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011331
John McCall5769d612010-02-08 23:07:23 +000011332 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011333 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011334 return ExprError();
11335
John McCalla24dc2e2009-11-17 02:14:36 +000011336 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11337 LookupQualifiedName(R, BaseRecord->getDecl());
11338 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011339
11340 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011341 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011342 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011343 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011344 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011345
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011346 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11347
Douglas Gregor8ba10742008-11-20 16:27:02 +000011348 // Perform overload resolution.
11349 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011350 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011351 case OR_Success:
11352 // Overload resolution succeeded; we'll build the call below.
11353 break;
11354
11355 case OR_No_Viable_Function:
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011356 if (CandidateSet.empty()) {
11357 QualType BaseType = Base->getType();
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011358 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11359 << BaseType << Base->getSourceRange();
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011360 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011361 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011362 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011363 }
11364 } else
Douglas Gregor8ba10742008-11-20 16:27:02 +000011365 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011366 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011367 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011368 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011369
11370 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011371 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11372 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011373 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011374 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011375
11376 case OR_Deleted:
11377 Diag(OpLoc, diag::err_ovl_deleted_oper)
11378 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011379 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011380 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011381 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011382 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011383 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011384 }
11385
John McCall9aa472c2010-03-19 07:35:19 +000011386 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11387
Douglas Gregor8ba10742008-11-20 16:27:02 +000011388 // Convert the object parameter.
11389 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011390 ExprResult BaseResult =
11391 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11392 Best->FoundDecl, Method);
11393 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011394 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011395 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011396
Douglas Gregor8ba10742008-11-20 16:27:02 +000011397 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011398 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011399 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011400 if (FnExpr.isInvalid())
11401 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011402
John McCallf89e55a2010-11-18 06:31:45 +000011403 QualType ResultTy = Method->getResultType();
11404 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11405 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011406 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011407 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011408 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011409
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011410 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011411 Method))
11412 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011413
11414 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011415}
11416
Richard Smith36f5cfe2012-03-09 08:00:36 +000011417/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11418/// a literal operator described by the provided lookup results.
11419ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11420 DeclarationNameInfo &SuffixInfo,
11421 ArrayRef<Expr*> Args,
11422 SourceLocation LitEndLoc,
11423 TemplateArgumentListInfo *TemplateArgs) {
11424 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011425
Richard Smith36f5cfe2012-03-09 08:00:36 +000011426 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11427 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11428 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011429
Richard Smith36f5cfe2012-03-09 08:00:36 +000011430 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11431
Richard Smith36f5cfe2012-03-09 08:00:36 +000011432 // Perform overload resolution. This will usually be trivial, but might need
11433 // to perform substitutions for a literal operator template.
11434 OverloadCandidateSet::iterator Best;
11435 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11436 case OR_Success:
11437 case OR_Deleted:
11438 break;
11439
11440 case OR_No_Viable_Function:
11441 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11442 << R.getLookupName();
11443 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11444 return ExprError();
11445
11446 case OR_Ambiguous:
11447 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11448 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11449 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011450 }
11451
Richard Smith36f5cfe2012-03-09 08:00:36 +000011452 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011453 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11454 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011455 SuffixInfo.getLoc(),
11456 SuffixInfo.getInfo());
11457 if (Fn.isInvalid())
11458 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011459
11460 // Check the argument types. This should almost always be a no-op, except
11461 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011462 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011463 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011464 ExprResult InputInit = PerformCopyInitialization(
11465 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11466 SourceLocation(), Args[ArgIdx]);
11467 if (InputInit.isInvalid())
11468 return true;
11469 ConvArgs[ArgIdx] = InputInit.take();
11470 }
11471
Richard Smith9fcce652012-03-07 08:35:16 +000011472 QualType ResultTy = FD->getResultType();
11473 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11474 ResultTy = ResultTy.getNonLValueExprType(Context);
11475
Richard Smith9fcce652012-03-07 08:35:16 +000011476 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011477 new (Context) UserDefinedLiteral(Context, Fn.take(),
11478 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011479 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11480
11481 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11482 return ExprError();
11483
Richard Smith831421f2012-06-25 20:30:08 +000011484 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011485 return ExprError();
11486
11487 return MaybeBindToTemporary(UDL);
11488}
11489
Sam Panzere1715b62012-08-21 00:52:01 +000011490/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11491/// given LookupResult is non-empty, it is assumed to describe a member which
11492/// will be invoked. Otherwise, the function will be found via argument
11493/// dependent lookup.
11494/// CallExpr is set to a valid expression and FRS_Success returned on success,
11495/// otherwise CallExpr is set to ExprError() and some non-success value
11496/// is returned.
11497Sema::ForRangeStatus
11498Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11499 SourceLocation RangeLoc, VarDecl *Decl,
11500 BeginEndFunction BEF,
11501 const DeclarationNameInfo &NameInfo,
11502 LookupResult &MemberLookup,
11503 OverloadCandidateSet *CandidateSet,
11504 Expr *Range, ExprResult *CallExpr) {
11505 CandidateSet->clear();
11506 if (!MemberLookup.empty()) {
11507 ExprResult MemberRef =
11508 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11509 /*IsPtr=*/false, CXXScopeSpec(),
11510 /*TemplateKWLoc=*/SourceLocation(),
11511 /*FirstQualifierInScope=*/0,
11512 MemberLookup,
11513 /*TemplateArgs=*/0);
11514 if (MemberRef.isInvalid()) {
11515 *CallExpr = ExprError();
11516 Diag(Range->getLocStart(), diag::note_in_for_range)
11517 << RangeLoc << BEF << Range->getType();
11518 return FRS_DiagnosticIssued;
11519 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011520 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011521 if (CallExpr->isInvalid()) {
11522 *CallExpr = ExprError();
11523 Diag(Range->getLocStart(), diag::note_in_for_range)
11524 << RangeLoc << BEF << Range->getType();
11525 return FRS_DiagnosticIssued;
11526 }
11527 } else {
11528 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011529 UnresolvedLookupExpr *Fn =
11530 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11531 NestedNameSpecifierLoc(), NameInfo,
11532 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011533 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011534
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011535 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011536 CandidateSet, CallExpr);
11537 if (CandidateSet->empty() || CandidateSetError) {
11538 *CallExpr = ExprError();
11539 return FRS_NoViableFunction;
11540 }
11541 OverloadCandidateSet::iterator Best;
11542 OverloadingResult OverloadResult =
11543 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11544
11545 if (OverloadResult == OR_No_Viable_Function) {
11546 *CallExpr = ExprError();
11547 return FRS_NoViableFunction;
11548 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011549 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011550 Loc, 0, CandidateSet, &Best,
11551 OverloadResult,
11552 /*AllowTypoCorrection=*/false);
11553 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11554 *CallExpr = ExprError();
11555 Diag(Range->getLocStart(), diag::note_in_for_range)
11556 << RangeLoc << BEF << Range->getType();
11557 return FRS_DiagnosticIssued;
11558 }
11559 }
11560 return FRS_Success;
11561}
11562
11563
Douglas Gregor904eed32008-11-10 20:40:00 +000011564/// FixOverloadedFunctionReference - E is an expression that refers to
11565/// a C++ overloaded function (possibly with some parentheses and
11566/// perhaps a '&' around it). We have resolved the overloaded function
11567/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011568/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011569Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011570 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011571 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011572 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11573 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011574 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011575 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011576
Douglas Gregor699ee522009-11-20 19:42:02 +000011577 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011578 }
11579
Douglas Gregor699ee522009-11-20 19:42:02 +000011580 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011581 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11582 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011583 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011584 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011585 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011586 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011587 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011588 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011589
11590 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011591 ICE->getCastKind(),
11592 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011593 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011594 }
11595
Douglas Gregor699ee522009-11-20 19:42:02 +000011596 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011597 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011598 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11600 if (Method->isStatic()) {
11601 // Do nothing: static member functions aren't any different
11602 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011603 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011604 // Fix the sub expression, which really has to be an
11605 // UnresolvedLookupExpr holding an overloaded member function
11606 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011607 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11608 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011609 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011610 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011611
John McCallba135432009-11-21 08:51:07 +000011612 assert(isa<DeclRefExpr>(SubExpr)
11613 && "fixed to something other than a decl ref");
11614 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11615 && "fixed to a member ref with no nested name qualifier");
11616
11617 // We have taken the address of a pointer to member
11618 // function. Perform the computation here so that we get the
11619 // appropriate pointer to member type.
11620 QualType ClassType
11621 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11622 QualType MemPtrType
11623 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11624
John McCallf89e55a2010-11-18 06:31:45 +000011625 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11626 VK_RValue, OK_Ordinary,
11627 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011628 }
11629 }
John McCall6bb80172010-03-30 21:47:33 +000011630 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11631 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011632 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011633 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011634
John McCall2de56d12010-08-25 11:45:40 +000011635 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011636 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011637 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011638 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011639 }
John McCallba135432009-11-21 08:51:07 +000011640
11641 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011642 // FIXME: avoid copy.
11643 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011644 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011645 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11646 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011647 }
11648
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011649 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11650 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011651 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011652 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011653 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011654 ULE->getNameLoc(),
11655 Fn->getType(),
11656 VK_LValue,
11657 Found.getDecl(),
11658 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011659 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011660 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11661 return DRE;
John McCallba135432009-11-21 08:51:07 +000011662 }
11663
John McCall129e2df2009-11-30 22:42:35 +000011664 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011665 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011666 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11667 if (MemExpr->hasExplicitTemplateArgs()) {
11668 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11669 TemplateArgs = &TemplateArgsBuffer;
11670 }
John McCalld5532b62009-11-23 01:53:49 +000011671
John McCallaa81e162009-12-01 22:10:20 +000011672 Expr *Base;
11673
John McCallf89e55a2010-11-18 06:31:45 +000011674 // If we're filling in a static method where we used to have an
11675 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011676 if (MemExpr->isImplicitAccess()) {
11677 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011678 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11679 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011680 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011681 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011682 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011683 MemExpr->getMemberLoc(),
11684 Fn->getType(),
11685 VK_LValue,
11686 Found.getDecl(),
11687 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011688 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011689 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11690 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011691 } else {
11692 SourceLocation Loc = MemExpr->getMemberLoc();
11693 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011694 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011695 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011696 Base = new (Context) CXXThisExpr(Loc,
11697 MemExpr->getBaseType(),
11698 /*isImplicit=*/true);
11699 }
John McCallaa81e162009-12-01 22:10:20 +000011700 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011701 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011702
John McCallf5307512011-04-27 00:36:17 +000011703 ExprValueKind valueKind;
11704 QualType type;
11705 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11706 valueKind = VK_LValue;
11707 type = Fn->getType();
11708 } else {
11709 valueKind = VK_RValue;
11710 type = Context.BoundMemberTy;
11711 }
11712
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011713 MemberExpr *ME = MemberExpr::Create(Context, Base,
11714 MemExpr->isArrow(),
11715 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011716 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011717 Fn,
11718 Found,
11719 MemExpr->getMemberNameInfo(),
11720 TemplateArgs,
11721 type, valueKind, OK_Ordinary);
11722 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011723 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011724 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011725 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011726
John McCall3fa5cae2010-10-26 07:05:15 +000011727 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011728}
11729
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011730ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011731 DeclAccessPair Found,
11732 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011733 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011734}
11735
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011736} // end namespace clang