blob: 3f7ab1c90f11bbbae7994e1cb6537fa29086c20d [file] [log] [blame]
Nick Lewycky5d9484d2013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000038
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000039/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42 bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith82f145d2013-05-04 06:44:46 +000045 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid570a922013-06-15 11:54:37 +000046 return ExprError();
47 // If FoundDecl is different from Fn (such as if one is a template
48 // and the other a specialization), make sure DiagnoseUseOfDecl is
49 // called on both.
50 // FIXME: This would be more comprehensively addressed by modifying
51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
52 // being used.
53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith82f145d2013-05-04 06:44:46 +000054 return ExprError();
John McCallf4b88a42012-03-10 09:33:50 +000055 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000056 VK_LValue, Loc, LocInfo);
57 if (HadMultipleCandidates)
58 DRE->setHadMultipleCandidates(true);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000059
60 S.MarkDeclRefReferenced(DRE);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000061
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000062 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000063 E = S.DefaultFunctionArrayConversion(E.take());
64 if (E.isInvalid())
65 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000066 return E;
John McCallf89e55a2010-11-18 06:31:45 +000067}
68
John McCall120d63c2010-08-24 20:38:10 +000069static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
70 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000071 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000072 bool CStyle,
73 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000074
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000075static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
76 QualType &ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000080static OverloadingResult
81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
82 UserDefinedConversionSequence& User,
83 OverloadCandidateSet& Conversions,
84 bool AllowExplicit);
85
86
87static ImplicitConversionSequence::CompareKind
88CompareStandardConversionSequences(Sema &S,
89 const StandardConversionSequence& SCS1,
90 const StandardConversionSequence& SCS2);
91
92static ImplicitConversionSequence::CompareKind
93CompareQualificationConversions(Sema &S,
94 const StandardConversionSequence& SCS1,
95 const StandardConversionSequence& SCS2);
96
97static ImplicitConversionSequence::CompareKind
98CompareDerivedToBaseConversions(Sema &S,
99 const StandardConversionSequence& SCS1,
100 const StandardConversionSequence& SCS2);
101
102
103
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104/// GetConversionCategory - Retrieve the implicit conversion
105/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +0000106ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107GetConversionCategory(ImplicitConversionKind Kind) {
108 static const ImplicitConversionCategory
109 Category[(int)ICK_Num_Conversion_Kinds] = {
110 ICC_Identity,
111 ICC_Lvalue_Transformation,
112 ICC_Lvalue_Transformation,
113 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000114 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000115 ICC_Qualification_Adjustment,
116 ICC_Promotion,
117 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000118 ICC_Promotion,
119 ICC_Conversion,
120 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000121 ICC_Conversion,
122 ICC_Conversion,
123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000126 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000127 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000128 ICC_Conversion,
129 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000130 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000131 ICC_Conversion
132 };
133 return Category[(int)Kind];
134}
135
136/// GetConversionRank - Retrieve the implicit conversion rank
137/// corresponding to the given implicit conversion kind.
138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
139 static const ImplicitConversionRank
140 Rank[(int)ICK_Num_Conversion_Kinds] = {
141 ICR_Exact_Match,
142 ICR_Exact_Match,
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000146 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 ICR_Promotion,
148 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000149 ICR_Promotion,
150 ICR_Conversion,
151 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000157 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000158 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000159 ICR_Conversion,
160 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000161 ICR_Complex_Real_Conversion,
162 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000163 ICR_Conversion,
164 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165 };
166 return Rank[(int)Kind];
167}
168
169/// GetImplicitConversionName - Return the name of this kind of
170/// implicit conversion.
171const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 "No conversion",
174 "Lvalue-to-rvalue",
175 "Array-to-pointer",
176 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000177 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000178 "Qualification",
179 "Integral promotion",
180 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000181 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 "Integral conversion",
183 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000184 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 "Floating-integral conversion",
186 "Pointer conversion",
187 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000188 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000189 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000190 "Derived-to-base conversion",
191 "Vector conversion",
192 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000193 "Complex-real conversion",
194 "Block Pointer conversion",
195 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000196 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 };
198 return Name[Kind];
199}
200
Douglas Gregor60d62c22008-10-31 16:23:19 +0000201/// StandardConversionSequence - Set the standard conversion
202/// sequence to the identity conversion.
203void StandardConversionSequence::setAsIdentityConversion() {
204 First = ICK_Identity;
205 Second = ICK_Identity;
206 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000207 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000208 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000209 ReferenceBinding = false;
210 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000211 IsLvalueReference = true;
212 BindsToFunctionLvalue = false;
213 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000214 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000215 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000216 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000217}
218
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219/// getRank - Retrieve the rank of this standard conversion sequence
220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
221/// implicit conversions.
222ImplicitConversionRank StandardConversionSequence::getRank() const {
223 ImplicitConversionRank Rank = ICR_Exact_Match;
224 if (GetConversionRank(First) > Rank)
225 Rank = GetConversionRank(First);
226 if (GetConversionRank(Second) > Rank)
227 Rank = GetConversionRank(Second);
228 if (GetConversionRank(Third) > Rank)
229 Rank = GetConversionRank(Third);
230 return Rank;
231}
232
233/// isPointerConversionToBool - Determines whether this conversion is
234/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000235/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000237bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 // Note that FromType has not necessarily been transformed by the
239 // array-to-pointer or function-to-pointer implicit conversions, so
240 // check for their presence as well as checking whether FromType is
241 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000242 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000243 (getFromType()->isPointerType() ||
244 getFromType()->isObjCObjectPointerType() ||
245 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000246 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
248 return true;
249
250 return false;
251}
252
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000253/// isPointerConversionToVoidPointer - Determines whether this
254/// conversion is a conversion of a pointer to a void pointer. This is
255/// used as part of the ranking of standard conversion sequences (C++
256/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000257bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000258StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000259isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000260 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000261 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000262
263 // Note that FromType has not necessarily been transformed by the
264 // array-to-pointer implicit conversion, so check for its presence
265 // and redo the conversion to get a pointer.
266 if (First == ICK_Array_To_Pointer)
267 FromType = Context.getArrayDecayedType(FromType);
268
Douglas Gregorf9af5242011-04-15 20:45:44 +0000269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000271 return ToPtrType->getPointeeType()->isVoidType();
272
273 return false;
274}
275
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000276/// Skip any implicit casts which could be either part of a narrowing conversion
277/// or after one in an implicit conversion.
278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280 switch (ICE->getCastKind()) {
281 case CK_NoOp:
282 case CK_IntegralCast:
283 case CK_IntegralToBoolean:
284 case CK_IntegralToFloating:
285 case CK_FloatingToIntegral:
286 case CK_FloatingToBoolean:
287 case CK_FloatingCast:
288 Converted = ICE->getSubExpr();
289 continue;
290
291 default:
292 return Converted;
293 }
294 }
295
296 return Converted;
297}
298
299/// Check if this standard conversion sequence represents a narrowing
300/// conversion, according to C++11 [dcl.init.list]p7.
301///
302/// \param Ctx The AST context.
303/// \param Converted The result of applying this standard conversion sequence.
304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000308NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
310 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000311 APValue &ConstantValue,
312 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000314
315 // C++11 [dcl.init.list]p7:
316 // A narrowing conversion is an implicit conversion ...
317 QualType FromType = getToType(0);
318 QualType ToType = getToType(1);
319 switch (Second) {
320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332 if (Initializer &&
333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334 // Convert the integer to the floating type.
335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337 llvm::APFloat::rmNearestTiesToEven);
338 // And back.
339 llvm::APSInt ConvertedValue = IntConstantValue;
340 bool ignored;
341 Result.convertToInteger(ConvertedValue,
342 llvm::APFloat::rmTowardZero, &ignored);
343 // If the resulting value is different, this was a narrowing conversion.
344 if (IntConstantValue != ConvertedValue) {
345 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000346 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
348 }
349 } else {
350 // Variables are always narrowings.
351 return NK_Variable_Narrowing;
352 }
353 }
354 return NK_Not_Narrowing;
355
356 // -- from long double to double or float, or from double to float, except
357 // where the source is a constant expression and the actual value after
358 // conversion is within the range of values that can be represented (even
359 // if it cannot be represented exactly), or
360 case ICK_Floating_Conversion:
361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363 // FromType is larger than ToType.
364 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366 // Constant!
367 assert(ConstantValue.isFloat());
368 llvm::APFloat FloatVal = ConstantValue.getFloat();
369 // Convert the source value into the target type.
370 bool ignored;
371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372 Ctx.getFloatTypeSemantics(ToType),
373 llvm::APFloat::rmNearestTiesToEven, &ignored);
374 // If there was no overflow, the source value is within the range of
375 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000376 if (ConvertStatus & llvm::APFloat::opOverflow) {
377 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000378 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000379 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000380 } else {
381 return NK_Variable_Narrowing;
382 }
383 }
384 return NK_Not_Narrowing;
385
386 // -- from an integer type or unscoped enumeration type to an integer type
387 // that cannot represent all the values of the original type, except where
388 // the source is a constant expression and the actual value after
389 // conversion will fit into the target type and will produce the original
390 // value when converted back to the original type.
391 case ICK_Boolean_Conversion: // Bools are integers too.
392 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
393 // Boolean conversions can be from pointers and pointers to members
394 // [conv.bool], and those aren't considered narrowing conversions.
395 return NK_Not_Narrowing;
396 } // Otherwise, fall through to the integral case.
397 case ICK_Integral_Conversion: {
398 assert(FromType->isIntegralOrUnscopedEnumerationType());
399 assert(ToType->isIntegralOrUnscopedEnumerationType());
400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
401 const unsigned FromWidth = Ctx.getIntWidth(FromType);
402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
403 const unsigned ToWidth = Ctx.getIntWidth(ToType);
404
405 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000406 (FromWidth == ToWidth && FromSigned != ToSigned) ||
407 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000408 // Not all values of FromType can be represented in ToType.
409 llvm::APSInt InitializerValue;
410 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
412 // Such conversions on variables are always narrowing.
413 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000414 }
415 bool Narrowing = false;
416 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000417 // Negative -> unsigned is narrowing. Otherwise, more bits is never
418 // narrowing.
419 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000420 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000421 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000422 // Add a bit to the InitializerValue so we don't have to worry about
423 // signed vs. unsigned comparisons.
424 InitializerValue = InitializerValue.extend(
425 InitializerValue.getBitWidth() + 1);
426 // Convert the initializer to and from the target width and signed-ness.
427 llvm::APSInt ConvertedValue = InitializerValue;
428 ConvertedValue = ConvertedValue.trunc(ToWidth);
429 ConvertedValue.setIsSigned(ToSigned);
430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
431 ConvertedValue.setIsSigned(InitializerValue.isSigned());
432 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000433 if (ConvertedValue != InitializerValue)
434 Narrowing = true;
435 }
436 if (Narrowing) {
437 ConstantType = Initializer->getType();
438 ConstantValue = APValue(InitializerValue);
439 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000440 }
441 }
442 return NK_Not_Narrowing;
443 }
444
445 default:
446 // Other kinds of conversions are not narrowings.
447 return NK_Not_Narrowing;
448 }
449}
450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451/// DebugPrint - Print this standard conversion sequence to standard
452/// error. Useful for debugging overloading issues.
453void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000454 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 bool PrintedSomething = false;
456 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (Second != ICK_Identity) {
462 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000466
467 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000468 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000469 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000470 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000471 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000473 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 PrintedSomething = true;
475 }
476
477 if (Third != ICK_Identity) {
478 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000481 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 PrintedSomething = true;
483 }
484
485 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000486 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 }
488}
489
490/// DebugPrint - Print this user-defined conversion sequence to standard
491/// error. Useful for debugging overloading issues.
492void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000493 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000494 if (Before.First || Before.Second || Before.Third) {
495 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000498 if (ConversionFunction)
499 OS << '\'' << *ConversionFunction << '\'';
500 else
501 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000503 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 After.DebugPrint();
505 }
506}
507
508/// DebugPrint - Print this implicit conversion sequence to standard
509/// error. Useful for debugging overloading issues.
510void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000511 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 switch (ConversionKind) {
513 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000514 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 Standard.DebugPrint();
516 break;
517 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 UserDefined.DebugPrint();
520 break;
521 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000522 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 break;
John McCall1d318332010-01-12 00:44:57 +0000524 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000525 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000526 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000528 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 break;
530 }
531
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000532 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533}
534
John McCall1d318332010-01-12 00:44:57 +0000535void AmbiguousConversionSequence::construct() {
536 new (&conversions()) ConversionSet();
537}
538
539void AmbiguousConversionSequence::destruct() {
540 conversions().~ConversionSet();
541}
542
543void
544AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
545 FromTypePtr = O.FromTypePtr;
546 ToTypePtr = O.ToTypePtr;
547 new (&conversions()) ConversionSet(O.conversions());
548}
549
Douglas Gregora9333192010-05-08 17:41:32 +0000550namespace {
551 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000552 // template argument information.
553 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000554 TemplateArgument FirstArg;
555 TemplateArgument SecondArg;
556 };
Richard Smith29805ca2013-01-31 05:19:49 +0000557 // Structure used by OverloadCandidate::DeductionFailureInfo to store
558 // template parameter and template argument information.
559 struct DFIParamWithArguments : DFIArguments {
560 TemplateParameter Param;
561 };
Douglas Gregora9333192010-05-08 17:41:32 +0000562}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564/// \brief Convert from Sema's representation of template deduction information
565/// to the form used in overload-candidate information.
566OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000567static MakeDeductionFailureInfo(ASTContext &Context,
568 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000569 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000570 OverloadCandidate::DeductionFailureInfo Result;
571 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000572 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000573 Result.Data = 0;
574 switch (TDK) {
575 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000576 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000577 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000578 case Sema::TDK_TooManyArguments:
579 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora9333192010-05-08 17:41:32 +0000582 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000583 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000584 Result.Data = Info.Param.getOpaqueValue();
585 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586
Richard Smith29805ca2013-01-31 05:19:49 +0000587 case Sema::TDK_NonDeducedMismatch: {
588 // FIXME: Should allocate from normal heap so that we can free this later.
589 DFIArguments *Saved = new (Context) DFIArguments;
590 Saved->FirstArg = Info.FirstArg;
591 Saved->SecondArg = Info.SecondArg;
592 Result.Data = Saved;
593 break;
594 }
595
Douglas Gregora9333192010-05-08 17:41:32 +0000596 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000597 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000598 // FIXME: Should allocate from normal heap so that we can free this later.
599 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000600 Saved->Param = Info.Param;
601 Saved->FirstArg = Info.FirstArg;
602 Saved->SecondArg = Info.SecondArg;
603 Result.Data = Saved;
604 break;
605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000606
Douglas Gregora9333192010-05-08 17:41:32 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000608 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000609 if (Info.hasSFINAEDiagnostic()) {
610 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
611 SourceLocation(), PartialDiagnostic::NullDiagnostic());
612 Info.takeSFINAEDiagnostic(*Diag);
613 Result.HasDiagnostic = true;
614 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616
Douglas Gregora9333192010-05-08 17:41:32 +0000617 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000618 Result.Data = Info.Expression;
619 break;
620
Richard Smith29805ca2013-01-31 05:19:49 +0000621 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000622 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000623 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregora9333192010-05-08 17:41:32 +0000625 return Result;
626}
John McCall1d318332010-01-12 00:44:57 +0000627
Douglas Gregora9333192010-05-08 17:41:32 +0000628void OverloadCandidate::DeductionFailureInfo::Destroy() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000631 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000632 case Sema::TDK_InstantiationDepth:
633 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000634 case Sema::TDK_TooManyArguments:
635 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000636 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000637 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000638 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639
Douglas Gregora9333192010-05-08 17:41:32 +0000640 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000641 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000642 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000643 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000644 Data = 0;
645 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000646
647 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000648 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000649 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
651 Diag->~PartialDiagnosticAt();
652 HasDiagnostic = false;
653 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000654 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000656 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000657 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000658 break;
659 }
660}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661
Richard Smithb8590f32012-05-07 09:03:25 +0000662PartialDiagnosticAt *
663OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
666 return 0;
667}
668
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000670OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
672 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000673 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000674 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000675 case Sema::TDK_TooManyArguments:
676 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000677 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000680 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000681
Douglas Gregora9333192010-05-08 17:41:32 +0000682 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000685
686 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000687 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000688 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689
Douglas Gregora9333192010-05-08 17:41:32 +0000690 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000691 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000692 break;
693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694
Douglas Gregora9333192010-05-08 17:41:32 +0000695 return TemplateParameter();
696}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Douglas Gregorec20f462010-05-08 20:07:26 +0000698TemplateArgumentList *
699OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000713
Richard Smith29805ca2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716
Richard Smith29805ca2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Douglas Gregora9333192010-05-08 17:41:32 +0000725const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregora9333192010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000742
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747
Douglas Gregora9333192010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000749}
Douglas Gregora9333192010-05-08 17:41:32 +0000750
751const TemplateArgument *
752OverloadCandidate::DeductionFailureInfo::getSecondArg() {
753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000755 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000756 case Sema::TDK_InstantiationDepth:
757 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000758 case Sema::TDK_TooManyArguments:
759 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000760 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000761 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000762 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000763 return 0;
764
Douglas Gregora9333192010-05-08 17:41:32 +0000765 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000766 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000767 case Sema::TDK_NonDeducedMismatch:
768 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000769
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000770 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000771 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000772 break;
773 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774
Douglas Gregora9333192010-05-08 17:41:32 +0000775 return 0;
776}
777
Richard Smith0efa62f2013-01-31 04:03:12 +0000778Expr *
779OverloadCandidate::DeductionFailureInfo::getExpr() {
780 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
781 Sema::TDK_FailedOverloadResolution)
782 return static_cast<Expr*>(Data);
783
784 return 0;
785}
786
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000787void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000788 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000789 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
790 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000791 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
792 i->DeductionFailure.Destroy();
793 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000794}
795
796void OverloadCandidateSet::clear() {
797 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000798 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000799 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000800 Functions.clear();
801}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802
John McCall5acb0c92011-10-17 18:40:02 +0000803namespace {
804 class UnbridgedCastsSet {
805 struct Entry {
806 Expr **Addr;
807 Expr *Saved;
808 };
809 SmallVector<Entry, 2> Entries;
810
811 public:
812 void save(Sema &S, Expr *&E) {
813 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
814 Entry entry = { &E, E };
815 Entries.push_back(entry);
816 E = S.stripARCUnbridgedCast(E);
817 }
818
819 void restore() {
820 for (SmallVectorImpl<Entry>::iterator
821 i = Entries.begin(), e = Entries.end(); i != e; ++i)
822 *i->Addr = i->Saved;
823 }
824 };
825}
826
827/// checkPlaceholderForOverload - Do any interesting placeholder-like
828/// preprocessing on the given expression.
829///
830/// \param unbridgedCasts a collection to which to add unbridged casts;
831/// without this, they will be immediately diagnosed as errors
832///
833/// Return true on unrecoverable error.
834static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
835 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
837 // We can't handle overloaded expressions here because overload
838 // resolution might reasonably tweak them.
839 if (placeholder->getKind() == BuiltinType::Overload) return false;
840
841 // If the context potentially accepts unbridged ARC casts, strip
842 // the unbridged cast and add it to the collection for later restoration.
843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
844 unbridgedCasts) {
845 unbridgedCasts->save(S, E);
846 return false;
847 }
848
849 // Go ahead and check everything else.
850 ExprResult result = S.CheckPlaceholderExpr(E);
851 if (result.isInvalid())
852 return true;
853
854 E = result.take();
855 return false;
856 }
857
858 // Nothing to do.
859 return false;
860}
861
862/// checkArgPlaceholdersForOverload - Check a set of call operands for
863/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000864static bool checkArgPlaceholdersForOverload(Sema &S,
865 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000866 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000867 for (unsigned i = 0, e = Args.size(); i != e; ++i)
868 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000869 return true;
870
871 return false;
872}
873
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000874// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000875// overload of the declarations in Old. This routine returns false if
876// New and Old cannot be overloaded, e.g., if New has the same
877// signature as some function in Old (C++ 1.3.10) or if the Old
878// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000879// it does return false, MatchedDecl will point to the decl that New
880// cannot be overloaded with. This decl may be a UsingShadowDecl on
881// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000882//
883// Example: Given the following input:
884//
885// void f(int, float); // #1
886// void f(int, int); // #2
887// int f(int, int); // #3
888//
889// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000890// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000891//
John McCall51fa86f2009-12-02 08:47:38 +0000892// When we process #2, Old contains only the FunctionDecl for #1. By
893// comparing the parameter types, we see that #1 and #2 are overloaded
894// (since they have different signatures), so this routine returns
895// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000896//
John McCall51fa86f2009-12-02 08:47:38 +0000897// When we process #3, Old is an overload set containing #1 and #2. We
898// compare the signatures of #3 to #1 (they're overloaded, so we do
899// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000901// signature), IsOverload returns false and MatchedDecl will be set to
902// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000903//
904// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905// into a class by a using declaration. The rules for whether to hide
906// shadow declarations ignore some properties which otherwise figure
907// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000908Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000909Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000911 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000912 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000913 NamedDecl *OldD = *I;
914
915 bool OldIsUsingDecl = false;
916 if (isa<UsingShadowDecl>(OldD)) {
917 OldIsUsingDecl = true;
918
919 // We can always introduce two using declarations into the same
920 // context, even if they have identical signatures.
921 if (NewIsUsingDecl) continue;
922
923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
924 }
925
926 // If either declaration was introduced by a using declaration,
927 // we'll need to use slightly different rules for matching.
928 // Essentially, these rules are the normal rules, except that
929 // function templates hide function templates with different
930 // return types or template parameter lists.
931 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000934
John McCall51fa86f2009-12-02 08:47:38 +0000935 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000936 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939 continue;
940 }
941
John McCall871b2e72009-12-09 03:35:25 +0000942 Match = *I;
943 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000944 }
John McCall51fa86f2009-12-02 08:47:38 +0000945 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000946 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
947 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
948 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
949 continue;
950 }
951
Rafael Espindola90cc3902013-04-15 12:49:13 +0000952 if (!shouldLinkPossiblyHiddenDecl(*I, New))
953 continue;
954
John McCall871b2e72009-12-09 03:35:25 +0000955 Match = *I;
956 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000957 }
John McCalld7945c62010-11-10 03:01:53 +0000958 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000959 // We can overload with these, which can show up when doing
960 // redeclaration checks for UsingDecls.
961 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000962 } else if (isa<TagDecl>(OldD)) {
963 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000964 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
965 // Optimistically assume that an unresolved using decl will
966 // overload; if it doesn't, we'll have to diagnose during
967 // template instantiation.
968 } else {
John McCall68263142009-11-18 22:49:29 +0000969 // (C++ 13p1):
970 // Only function declarations can be overloaded; object and type
971 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000972 Match = *I;
973 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000974 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000975 }
John McCall68263142009-11-18 22:49:29 +0000976
John McCall871b2e72009-12-09 03:35:25 +0000977 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000978}
979
Rafael Espindola78eeba82012-12-28 14:21:58 +0000980static bool canBeOverloaded(const FunctionDecl &D) {
981 if (D.getAttr<OverloadableAttr>())
982 return true;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000983 if (D.isExternC())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000984 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000985
986 // Main cannot be overloaded (basic.start.main).
987 if (D.isMain())
988 return false;
989
Rafael Espindola78eeba82012-12-28 14:21:58 +0000990 return true;
991}
992
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000993static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
994 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000995 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
996 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
997
998 // C++ [temp.fct]p2:
999 // A function template can be overloaded with other function templates
1000 // and with normal (non-template) functions.
1001 if ((OldTemplate == 0) != (NewTemplate == 0))
1002 return true;
1003
1004 // Is the function New an overload of the function Old?
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001005 QualType OldQType = S.Context.getCanonicalType(Old->getType());
1006 QualType NewQType = S.Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +00001007
1008 // Compare the signatures (C++ 1.3.10) of the two functions to
1009 // determine whether they are overloads. If we find any mismatch
1010 // in the signature, they are overloads.
1011
1012 // If either of these functions is a K&R-style function (no
1013 // prototype), then we consider them to have matching signatures.
1014 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1015 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1016 return false;
1017
John McCallf4c73712011-01-19 06:33:43 +00001018 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1019 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001020
1021 // The signature of a function includes the types of its
1022 // parameters (C++ 1.3.10), which includes the presence or absence
1023 // of the ellipsis; see C++ DR 357).
1024 if (OldQType != NewQType &&
1025 (OldType->getNumArgs() != NewType->getNumArgs() ||
1026 OldType->isVariadic() != NewType->isVariadic() ||
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001027 !S.FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001028 return true;
1029
1030 // C++ [temp.over.link]p4:
1031 // The signature of a function template consists of its function
1032 // signature, its return type and its template parameter list. The names
1033 // of the template parameters are significant only for establishing the
1034 // relationship between the template parameters and the rest of the
1035 // signature.
1036 //
1037 // We check the return type and template parameter lists for function
1038 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001039 //
1040 // However, we don't consider either of these when deciding whether
1041 // a member introduced by a shadow declaration is hidden.
1042 if (!UseUsingDeclRules && NewTemplate &&
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001043 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1044 OldTemplate->getTemplateParameters(),
1045 false, S.TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001046 OldType->getResultType() != NewType->getResultType()))
1047 return true;
1048
1049 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001050 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001051 //
1052 // As part of this, also check whether one of the member functions
1053 // is static, in which case they are not overloads (C++
1054 // 13.1p2). While not part of the definition of the signature,
1055 // this check is important to determine whether these functions
1056 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001057 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1058 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001059 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001060 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1061 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1062 if (!UseUsingDeclRules &&
1063 (OldMethod->getRefQualifier() == RQ_None ||
1064 NewMethod->getRefQualifier() == RQ_None)) {
1065 // C++0x [over.load]p2:
1066 // - Member function declarations with the same name and the same
1067 // parameter-type-list as well as member function template
1068 // declarations with the same name, the same parameter-type-list, and
1069 // the same template parameter lists cannot be overloaded if any of
1070 // them, but not all, have a ref-qualifier (8.3.5).
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001071 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001072 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001073 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001074 }
1075 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001077
Richard Smith21c8fa82013-01-14 05:37:29 +00001078 // We may not have applied the implicit const for a constexpr member
1079 // function yet (because we haven't yet resolved whether this is a static
1080 // or non-static member function). Add it now, on the assumption that this
1081 // is a redeclaration of OldMethod.
1082 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithdb2fe732013-06-25 18:46:26 +00001083 if (!S.getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1084 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001085 NewQuals |= Qualifiers::Const;
1086 if (OldMethod->getTypeQualifiers() != NewQuals)
1087 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001088 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001089
John McCall68263142009-11-18 22:49:29 +00001090 // The signatures match; this is not an overload.
1091 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001092}
1093
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001094bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1095 bool UseUsingDeclRules) {
1096 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1097 return false;
1098
1099 // If both of the functions are extern "C", then they are not
1100 // overloads.
1101 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1102 return false;
1103
1104 return true;
1105}
1106
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001107/// \brief Checks availability of the function depending on the current
1108/// function context. Inside an unavailable function, unavailability is ignored.
1109///
1110/// \returns true if \arg FD is unavailable and current context is inside
1111/// an available function, false otherwise.
1112bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1113 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1114}
1115
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001116/// \brief Tries a user-defined conversion from From to ToType.
1117///
1118/// Produces an implicit conversion sequence for when a standard conversion
1119/// is not an option. See TryImplicitConversion for more information.
1120static ImplicitConversionSequence
1121TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1122 bool SuppressUserConversions,
1123 bool AllowExplicit,
1124 bool InOverloadResolution,
1125 bool CStyle,
1126 bool AllowObjCWritebackConversion) {
1127 ImplicitConversionSequence ICS;
1128
1129 if (SuppressUserConversions) {
1130 // We're not in the case above, so there is no conversion that
1131 // we can perform.
1132 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1133 return ICS;
1134 }
1135
1136 // Attempt user-defined conversion.
1137 OverloadCandidateSet Conversions(From->getExprLoc());
1138 OverloadingResult UserDefResult
1139 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1140 AllowExplicit);
1141
1142 if (UserDefResult == OR_Success) {
1143 ICS.setUserDefined();
1144 // C++ [over.ics.user]p4:
1145 // A conversion of an expression of class type to the same class
1146 // type is given Exact Match rank, and a conversion of an
1147 // expression of class type to a base class of that type is
1148 // given Conversion rank, in spite of the fact that a copy
1149 // constructor (i.e., a user-defined conversion function) is
1150 // called for those cases.
1151 if (CXXConstructorDecl *Constructor
1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1153 QualType FromCanon
1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1155 QualType ToCanon
1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1157 if (Constructor->isCopyConstructor() &&
1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1159 // Turn this into a "standard" conversion sequence, so that it
1160 // gets ranked with standard conversion sequences.
1161 ICS.setStandard();
1162 ICS.Standard.setAsIdentityConversion();
1163 ICS.Standard.setFromType(From->getType());
1164 ICS.Standard.setAllToTypes(ToType);
1165 ICS.Standard.CopyConstructor = Constructor;
1166 if (ToCanon != FromCanon)
1167 ICS.Standard.Second = ICK_Derived_To_Base;
1168 }
1169 }
1170
1171 // C++ [over.best.ics]p4:
1172 // However, when considering the argument of a user-defined
1173 // conversion function that is a candidate by 13.3.1.3 when
1174 // invoked for the copying of the temporary in the second step
1175 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1176 // 13.3.1.6 in all cases, only standard conversion sequences and
1177 // ellipsis conversion sequences are allowed.
1178 if (SuppressUserConversions && ICS.isUserDefined()) {
1179 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1180 }
1181 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1182 ICS.setAmbiguous();
1183 ICS.Ambiguous.setFromType(From->getType());
1184 ICS.Ambiguous.setToType(ToType);
1185 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1186 Cand != Conversions.end(); ++Cand)
1187 if (Cand->Viable)
1188 ICS.Ambiguous.addConversion(Cand->Function);
1189 } else {
1190 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1191 }
1192
1193 return ICS;
1194}
1195
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001196/// TryImplicitConversion - Attempt to perform an implicit conversion
1197/// from the given expression (Expr) to the given type (ToType). This
1198/// function returns an implicit conversion sequence that can be used
1199/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200///
1201/// void f(float f);
1202/// void g(int i) { f(i); }
1203///
1204/// this routine would produce an implicit conversion sequence to
1205/// describe the initialization of f from i, which will be a standard
1206/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1207/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1208//
1209/// Note that this routine only determines how the conversion can be
1210/// performed; it does not actually perform the conversion. As such,
1211/// it will not produce any diagnostics if no conversion is available,
1212/// but will instead return an implicit conversion sequence of kind
1213/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001214///
1215/// If @p SuppressUserConversions, then user-defined conversions are
1216/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001217/// If @p AllowExplicit, then explicit user-defined conversions are
1218/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001219///
1220/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1221/// writeback conversion, which allows __autoreleasing id* parameters to
1222/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001223static ImplicitConversionSequence
1224TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1225 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001226 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001227 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001228 bool CStyle,
1229 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001230 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001231 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001232 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001233 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001234 return ICS;
1235 }
1236
David Blaikie4e4d0842012-03-11 07:00:24 +00001237 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001239 return ICS;
1240 }
1241
Douglas Gregor604eb652010-08-11 02:15:33 +00001242 // C++ [over.ics.user]p4:
1243 // A conversion of an expression of class type to the same class
1244 // type is given Exact Match rank, and a conversion of an
1245 // expression of class type to a base class of that type is
1246 // given Conversion rank, in spite of the fact that a copy/move
1247 // constructor (i.e., a user-defined conversion function) is
1248 // called for those cases.
1249 QualType FromType = From->getType();
1250 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001251 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1252 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001253 ICS.setStandard();
1254 ICS.Standard.setAsIdentityConversion();
1255 ICS.Standard.setFromType(FromType);
1256 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001257
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001258 // We don't actually check at this point whether there is a valid
1259 // copy/move constructor, since overloading just assumes that it
1260 // exists. When we actually perform initialization, we'll find the
1261 // appropriate constructor to copy the returned object, if needed.
1262 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001263
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001264 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001265 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001266 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267
Douglas Gregor604eb652010-08-11 02:15:33 +00001268 return ICS;
1269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001270
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001271 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1272 AllowExplicit, InOverloadResolution, CStyle,
1273 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001274}
1275
John McCallf85e1932011-06-15 23:02:42 +00001276ImplicitConversionSequence
1277Sema::TryImplicitConversion(Expr *From, QualType ToType,
1278 bool SuppressUserConversions,
1279 bool AllowExplicit,
1280 bool InOverloadResolution,
1281 bool CStyle,
1282 bool AllowObjCWritebackConversion) {
1283 return clang::TryImplicitConversion(*this, From, ToType,
1284 SuppressUserConversions, AllowExplicit,
1285 InOverloadResolution, CStyle,
1286 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001287}
1288
Douglas Gregor575c63a2010-04-16 22:27:05 +00001289/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001290/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001291/// converted expression. Flavor is the kind of conversion we're
1292/// performing, used in the error message. If @p AllowExplicit,
1293/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001294ExprResult
1295Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001296 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001297 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001298 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001299}
1300
John Wiegley429bb272011-04-08 18:41:53 +00001301ExprResult
1302Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001303 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001304 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001305 if (checkPlaceholderForOverload(*this, From))
1306 return ExprError();
1307
John McCallf85e1932011-06-15 23:02:42 +00001308 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1309 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001310 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001311 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001312
John McCall120d63c2010-08-24 20:38:10 +00001313 ICS = clang::TryImplicitConversion(*this, From, ToType,
1314 /*SuppressUserConversions=*/false,
1315 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001316 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001317 /*CStyle=*/false,
1318 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001319 return PerformImplicitConversion(From, ToType, ICS, Action);
1320}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001321
1322/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001323/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001324bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1325 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001326 if (Context.hasSameUnqualifiedType(FromType, ToType))
1327 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001328
John McCall00ccbef2010-12-21 00:44:39 +00001329 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1330 // where F adds one of the following at most once:
1331 // - a pointer
1332 // - a member pointer
1333 // - a block pointer
1334 CanQualType CanTo = Context.getCanonicalType(ToType);
1335 CanQualType CanFrom = Context.getCanonicalType(FromType);
1336 Type::TypeClass TyClass = CanTo->getTypeClass();
1337 if (TyClass != CanFrom->getTypeClass()) return false;
1338 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1339 if (TyClass == Type::Pointer) {
1340 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1341 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1342 } else if (TyClass == Type::BlockPointer) {
1343 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1344 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1345 } else if (TyClass == Type::MemberPointer) {
1346 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1347 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1348 } else {
1349 return false;
1350 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001351
John McCall00ccbef2010-12-21 00:44:39 +00001352 TyClass = CanTo->getTypeClass();
1353 if (TyClass != CanFrom->getTypeClass()) return false;
1354 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1355 return false;
1356 }
1357
1358 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1359 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1360 if (!EInfo.getNoReturn()) return false;
1361
1362 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1363 assert(QualType(FromFn, 0).isCanonical());
1364 if (QualType(FromFn, 0) != CanTo) return false;
1365
1366 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001367 return true;
1368}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001369
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001370/// \brief Determine whether the conversion from FromType to ToType is a valid
1371/// vector conversion.
1372///
1373/// \param ICK Will be set to the vector conversion kind, if this is a vector
1374/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001375static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1376 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001377 // We need at least one of these types to be a vector type to have a vector
1378 // conversion.
1379 if (!ToType->isVectorType() && !FromType->isVectorType())
1380 return false;
1381
1382 // Identical types require no conversions.
1383 if (Context.hasSameUnqualifiedType(FromType, ToType))
1384 return false;
1385
1386 // There are no conversions between extended vector types, only identity.
1387 if (ToType->isExtVectorType()) {
1388 // There are no conversions between extended vector types other than the
1389 // identity conversion.
1390 if (FromType->isExtVectorType())
1391 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001392
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001393 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001394 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001395 ICK = ICK_Vector_Splat;
1396 return true;
1397 }
1398 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001399
1400 // We can perform the conversion between vector types in the following cases:
1401 // 1)vector types are equivalent AltiVec and GCC vector types
1402 // 2)lax vector conversions are permitted and the vector types are of the
1403 // same size
1404 if (ToType->isVectorType() && FromType->isVectorType()) {
1405 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001406 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001407 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001408 ICK = ICK_Vector_Conversion;
1409 return true;
1410 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001411 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001412
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001413 return false;
1414}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001415
Douglas Gregor7d000652012-04-12 20:48:09 +00001416static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1417 bool InOverloadResolution,
1418 StandardConversionSequence &SCS,
1419 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001420
Douglas Gregor60d62c22008-10-31 16:23:19 +00001421/// IsStandardConversion - Determines whether there is a standard
1422/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1423/// expression From to the type ToType. Standard conversion sequences
1424/// only consider non-class types; for conversions that involve class
1425/// types, use TryImplicitConversion. If a conversion exists, SCS will
1426/// contain the standard conversion sequence required to perform this
1427/// conversion and this routine will return true. Otherwise, this
1428/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001429static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1430 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001431 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001432 bool CStyle,
1433 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001434 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001435
Douglas Gregor60d62c22008-10-31 16:23:19 +00001436 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001437 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001438 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001439 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001440 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001441 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442
Douglas Gregorf9201e02009-02-11 23:02:49 +00001443 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001444 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001445 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001446 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001447 return false;
1448
Mike Stump1eb44332009-09-09 15:08:12 +00001449 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001450 }
1451
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001452 // The first conversion can be an lvalue-to-rvalue conversion,
1453 // array-to-pointer conversion, or function-to-pointer conversion
1454 // (C++ 4p1).
1455
John McCall120d63c2010-08-24 20:38:10 +00001456 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001457 DeclAccessPair AccessPair;
1458 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001459 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001460 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001461 // We were able to resolve the address of the overloaded function,
1462 // so we can convert to the type of that function.
1463 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001464
1465 // we can sometimes resolve &foo<int> regardless of ToType, so check
1466 // if the type matches (identity) or we are converting to bool
1467 if (!S.Context.hasSameUnqualifiedType(
1468 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1469 QualType resultTy;
1470 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001471 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001472 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1473 // otherwise, only a boolean conversion is standard
1474 if (!ToType->isBooleanType())
1475 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001476 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001477
Chandler Carruth90434232011-03-29 08:08:18 +00001478 // Check if the "from" expression is taking the address of an overloaded
1479 // function and recompute the FromType accordingly. Take advantage of the
1480 // fact that non-static member functions *must* have such an address-of
1481 // expression.
1482 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1483 if (Method && !Method->isStatic()) {
1484 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1485 "Non-unary operator on non-static member address");
1486 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1487 == UO_AddrOf &&
1488 "Non-address-of operator on non-static member address");
1489 const Type *ClassType
1490 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1491 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001492 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1494 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001495 "Non-address-of operator for overloaded function expression");
1496 FromType = S.Context.getPointerType(FromType);
1497 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001498
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001499 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001500 assert(S.Context.hasSameType(
1501 FromType,
1502 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001503 } else {
1504 return false;
1505 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001506 }
John McCall21480112011-08-30 00:57:29 +00001507 // Lvalue-to-rvalue conversion (C++11 4.1):
1508 // A glvalue (3.10) of a non-function, non-array type T can
1509 // be converted to a prvalue.
1510 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001511 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001512 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001513 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001514 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001515
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001516 // C11 6.3.2.1p2:
1517 // ... if the lvalue has atomic type, the value has the non-atomic version
1518 // of the type of the lvalue ...
1519 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1520 FromType = Atomic->getValueType();
1521
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001522 // If T is a non-class type, the type of the rvalue is the
1523 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001524 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1525 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001526 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001527 } else if (FromType->isArrayType()) {
1528 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001529 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001530
1531 // An lvalue or rvalue of type "array of N T" or "array of unknown
1532 // bound of T" can be converted to an rvalue of type "pointer to
1533 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001534 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001535
John McCall120d63c2010-08-24 20:38:10 +00001536 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001537 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001538 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539
1540 // For the purpose of ranking in overload resolution
1541 // (13.3.3.1.1), this conversion is considered an
1542 // array-to-pointer conversion followed by a qualification
1543 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001544 SCS.Second = ICK_Identity;
1545 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001546 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001547 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001548 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001549 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001550 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001551 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001552 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553
1554 // An lvalue of function type T can be converted to an rvalue of
1555 // type "pointer to T." The result is a pointer to the
1556 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001557 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001558 } else {
1559 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001561 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001562 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001563
1564 // The second conversion can be an integral promotion, floating
1565 // point promotion, integral conversion, floating point conversion,
1566 // floating-integral conversion, pointer conversion,
1567 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001568 // For overloading in C, this can also be a "compatible-type"
1569 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001570 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001571 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001572 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 // The unqualified versions of the types are the same: there's no
1574 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001575 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001576 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001577 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001578 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001579 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001580 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001581 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001582 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001583 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001584 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001585 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001586 SCS.Second = ICK_Complex_Promotion;
1587 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001588 } else if (ToType->isBooleanType() &&
1589 (FromType->isArithmeticType() ||
1590 FromType->isAnyPointerType() ||
1591 FromType->isBlockPointerType() ||
1592 FromType->isMemberPointerType() ||
1593 FromType->isNullPtrType())) {
1594 // Boolean conversions (C++ 4.12).
1595 SCS.Second = ICK_Boolean_Conversion;
1596 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001597 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001598 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001599 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001600 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001601 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001602 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001603 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001604 SCS.Second = ICK_Complex_Conversion;
1605 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001606 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1607 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001608 // Complex-real conversions (C99 6.3.1.7)
1609 SCS.Second = ICK_Complex_Real;
1610 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001611 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001612 // Floating point conversions (C++ 4.8).
1613 SCS.Second = ICK_Floating_Conversion;
1614 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001616 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001617 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001618 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001619 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001620 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001621 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001622 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001623 SCS.Second = ICK_Block_Pointer_Conversion;
1624 } else if (AllowObjCWritebackConversion &&
1625 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1626 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001627 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1628 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001629 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001630 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001631 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001632 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001634 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001635 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001636 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001637 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001638 SCS.Second = SecondICK;
1639 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001640 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001641 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001642 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001643 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001644 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001645 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001646 // Treat a conversion that strips "noreturn" as an identity conversion.
1647 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001648 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1649 InOverloadResolution,
1650 SCS, CStyle)) {
1651 SCS.Second = ICK_TransparentUnionConversion;
1652 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001653 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1654 CStyle)) {
1655 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001656 // appropriately.
1657 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001658 } else if (ToType->isEventT() &&
1659 From->isIntegerConstantExpr(S.getASTContext()) &&
1660 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1661 SCS.Second = ICK_Zero_Event_Conversion;
1662 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001663 } else {
1664 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001665 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001666 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001667 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001668
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001669 QualType CanonFrom;
1670 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001671 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001672 bool ObjCLifetimeConversion;
1673 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1674 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001675 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001676 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001677 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001678 CanonFrom = S.Context.getCanonicalType(FromType);
1679 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001680 } else {
1681 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001682 SCS.Third = ICK_Identity;
1683
Mike Stump1eb44332009-09-09 15:08:12 +00001684 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001685 // [...] Any difference in top-level cv-qualification is
1686 // subsumed by the initialization itself and does not constitute
1687 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001688 CanonFrom = S.Context.getCanonicalType(FromType);
1689 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001691 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001692 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001693 FromType = ToType;
1694 CanonFrom = CanonTo;
1695 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001696 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001697 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001698
1699 // If we have not converted the argument type to the parameter type,
1700 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001701 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001702 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001703
Douglas Gregor60d62c22008-10-31 16:23:19 +00001704 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001705}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001706
1707static bool
1708IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1709 QualType &ToType,
1710 bool InOverloadResolution,
1711 StandardConversionSequence &SCS,
1712 bool CStyle) {
1713
1714 const RecordType *UT = ToType->getAsUnionType();
1715 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1716 return false;
1717 // The field to initialize within the transparent union.
1718 RecordDecl *UD = UT->getDecl();
1719 // It's compatible if the expression matches any of the fields.
1720 for (RecordDecl::field_iterator it = UD->field_begin(),
1721 itend = UD->field_end();
1722 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001723 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1724 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001725 ToType = it->getType();
1726 return true;
1727 }
1728 }
1729 return false;
1730}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001731
1732/// IsIntegralPromotion - Determines whether the conversion from the
1733/// expression From (whose potentially-adjusted type is FromType) to
1734/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1735/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001737 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001738 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001739 if (!To) {
1740 return false;
1741 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001742
1743 // An rvalue of type char, signed char, unsigned char, short int, or
1744 // unsigned short int can be converted to an rvalue of type int if
1745 // int can represent all the values of the source type; otherwise,
1746 // the source rvalue can be converted to an rvalue of type unsigned
1747 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001748 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1749 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001750 if (// We can promote any signed, promotable integer type to an int
1751 (FromType->isSignedIntegerType() ||
1752 // We can promote any unsigned integer type whose size is
1753 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001754 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001755 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001756 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001757 }
1758
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001759 return To->getKind() == BuiltinType::UInt;
1760 }
1761
Richard Smithe7ff9192012-09-13 21:18:54 +00001762 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001763 // A prvalue of an unscoped enumeration type whose underlying type is not
1764 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1765 // following types that can represent all the values of the enumeration
1766 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1767 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001768 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001769 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001770 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001771 // with lowest integer conversion rank (4.13) greater than the rank of long
1772 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001773 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001774 // C++11 [conv.prom]p4:
1775 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1776 // can be converted to a prvalue of its underlying type. Moreover, if
1777 // integral promotion can be applied to its underlying type, a prvalue of an
1778 // unscoped enumeration type whose underlying type is fixed can also be
1779 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001780 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1781 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1782 // provided for a scoped enumeration.
1783 if (FromEnumType->getDecl()->isScoped())
1784 return false;
1785
Richard Smithe7ff9192012-09-13 21:18:54 +00001786 // We can perform an integral promotion to the underlying type of the enum,
1787 // even if that's not the promoted type.
1788 if (FromEnumType->getDecl()->isFixed()) {
1789 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1790 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1791 IsIntegralPromotion(From, Underlying, ToType);
1792 }
1793
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001794 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001796 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001797 return Context.hasSameUnqualifiedType(ToType,
1798 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001799 }
John McCall842aef82009-12-09 09:09:27 +00001800
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001801 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1803 // to an rvalue a prvalue of the first of the following types that can
1804 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001805 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001807 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001808 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001809 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001811 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001812 // Determine whether the type we're converting from is signed or
1813 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001814 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001816
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001817 // The types we'll try to promote to, in the appropriate
1818 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001819 QualType PromoteTypes[6] = {
1820 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001821 Context.LongTy, Context.UnsignedLongTy ,
1822 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001823 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001824 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001825 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1826 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001827 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001828 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1829 // We found the type that we can promote to. If this is the
1830 // type we wanted, we have a promotion. Otherwise, no
1831 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001832 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001833 }
1834 }
1835 }
1836
1837 // An rvalue for an integral bit-field (9.6) can be converted to an
1838 // rvalue of type int if int can represent all the values of the
1839 // bit-field; otherwise, it can be converted to unsigned int if
1840 // unsigned int can represent all the values of the bit-field. If
1841 // the bit-field is larger yet, no integral promotion applies to
1842 // it. If the bit-field has an enumerated type, it is treated as any
1843 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001844 // FIXME: We should delay checking of bit-fields until we actually perform the
1845 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001846 using llvm::APSInt;
1847 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001848 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001849 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001850 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001851 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1852 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1853 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Douglas Gregor86f19402008-12-20 23:49:58 +00001855 // Are we promoting to an int from a bitfield that fits in an int?
1856 if (BitWidth < ToSize ||
1857 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1858 return To->getKind() == BuiltinType::Int;
1859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregor86f19402008-12-20 23:49:58 +00001861 // Are we promoting to an unsigned int from an unsigned bitfield
1862 // that fits into an unsigned int?
1863 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1864 return To->getKind() == BuiltinType::UInt;
1865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor86f19402008-12-20 23:49:58 +00001867 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001868 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001869 }
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001871 // An rvalue of type bool can be converted to an rvalue of type int,
1872 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001873 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001874 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001875 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001876
1877 return false;
1878}
1879
1880/// IsFloatingPointPromotion - Determines whether the conversion from
1881/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1882/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001883bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001884 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1885 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001886 /// An rvalue of type float can be converted to an rvalue of type
1887 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001888 if (FromBuiltin->getKind() == BuiltinType::Float &&
1889 ToBuiltin->getKind() == BuiltinType::Double)
1890 return true;
1891
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001892 // C99 6.3.1.5p1:
1893 // When a float is promoted to double or long double, or a
1894 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001895 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001896 (FromBuiltin->getKind() == BuiltinType::Float ||
1897 FromBuiltin->getKind() == BuiltinType::Double) &&
1898 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1899 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001900
1901 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001902 if (!getLangOpts().NativeHalfType &&
1903 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001904 ToBuiltin->getKind() == BuiltinType::Float)
1905 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001906 }
1907
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001908 return false;
1909}
1910
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001911/// \brief Determine if a conversion is a complex promotion.
1912///
1913/// A complex promotion is defined as a complex -> complex conversion
1914/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001915/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001916bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001917 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001918 if (!FromComplex)
1919 return false;
1920
John McCall183700f2009-09-21 23:43:11 +00001921 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001922 if (!ToComplex)
1923 return false;
1924
1925 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001926 ToComplex->getElementType()) ||
1927 IsIntegralPromotion(0, FromComplex->getElementType(),
1928 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001929}
1930
Douglas Gregorcb7de522008-11-26 23:31:11 +00001931/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1932/// the pointer type FromPtr to a pointer to type ToPointee, with the
1933/// same type qualifiers as FromPtr has on its pointee type. ToType,
1934/// if non-empty, will be a pointer to ToType that may or may not have
1935/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001936///
Mike Stump1eb44332009-09-09 15:08:12 +00001937static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001938BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001939 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001940 ASTContext &Context,
1941 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001942 assert((FromPtr->getTypeClass() == Type::Pointer ||
1943 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1944 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001945
John McCallf85e1932011-06-15 23:02:42 +00001946 /// Conversions to 'id' subsume cv-qualifier conversions.
1947 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001948 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001949
1950 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001951 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001952 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001953 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001954
John McCallf85e1932011-06-15 23:02:42 +00001955 if (StripObjCLifetime)
1956 Quals.removeObjCLifetime();
1957
Mike Stump1eb44332009-09-09 15:08:12 +00001958 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001959 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001960 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001961 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001962 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001963
1964 // Build a pointer to ToPointee. It has the right qualifiers
1965 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001966 if (isa<ObjCObjectPointerType>(ToType))
1967 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001968 return Context.getPointerType(ToPointee);
1969 }
1970
1971 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001972 QualType QualifiedCanonToPointee
1973 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001974
Douglas Gregorda80f742010-12-01 21:43:58 +00001975 if (isa<ObjCObjectPointerType>(ToType))
1976 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1977 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001978}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001979
Mike Stump1eb44332009-09-09 15:08:12 +00001980static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001981 bool InOverloadResolution,
1982 ASTContext &Context) {
1983 // Handle value-dependent integral null pointer constants correctly.
1984 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1985 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001986 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001987 return !InOverloadResolution;
1988
Douglas Gregorce940492009-09-25 04:25:58 +00001989 return Expr->isNullPointerConstant(Context,
1990 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1991 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001992}
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001994/// IsPointerConversion - Determines whether the conversion of the
1995/// expression From, which has the (possibly adjusted) type FromType,
1996/// can be converted to the type ToType via a pointer conversion (C++
1997/// 4.10). If so, returns true and places the converted type (that
1998/// might differ from ToType in its cv-qualifiers at some level) into
1999/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002000///
Douglas Gregor7ca09762008-11-27 01:19:21 +00002001/// This routine also supports conversions to and from block pointers
2002/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2003/// pointers to interfaces. FIXME: Once we've determined the
2004/// appropriate overloading rules for Objective-C, we may want to
2005/// split the Objective-C checks into a different routine; however,
2006/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00002007/// conversions, so for now they live here. IncompatibleObjC will be
2008/// set if the conversion is an allowed Objective-C conversion that
2009/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002010bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00002011 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00002012 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00002013 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002014 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002015 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2016 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002017 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002018
Mike Stump1eb44332009-09-09 15:08:12 +00002019 // Conversion from a null pointer constant to any Objective-C pointer type.
2020 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002022 ConvertedType = ToType;
2023 return true;
2024 }
2025
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002026 // Blocks: Block pointers can be converted to void*.
2027 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002028 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002029 ConvertedType = ToType;
2030 return true;
2031 }
2032 // Blocks: A null pointer constant can be converted to a block
2033 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002034 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002036 ConvertedType = ToType;
2037 return true;
2038 }
2039
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002040 // If the left-hand-side is nullptr_t, the right side can be a null
2041 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002042 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002043 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002044 ConvertedType = ToType;
2045 return true;
2046 }
2047
Ted Kremenek6217b802009-07-29 21:53:49 +00002048 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002049 if (!ToTypePtr)
2050 return false;
2051
2052 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002053 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002054 ConvertedType = ToType;
2055 return true;
2056 }
Sebastian Redl07779722008-10-31 14:43:28 +00002057
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002058 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002059 // , including objective-c pointers.
2060 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002061 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002062 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002063 ConvertedType = BuildSimilarlyQualifiedPointerType(
2064 FromType->getAs<ObjCObjectPointerType>(),
2065 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002066 ToType, Context);
2067 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002068 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002069 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002070 if (!FromTypePtr)
2071 return false;
2072
2073 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002074
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002075 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002076 // pointer conversion, so don't do all of the work below.
2077 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2078 return false;
2079
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002080 // An rvalue of type "pointer to cv T," where T is an object type,
2081 // can be converted to an rvalue of type "pointer to cv void" (C++
2082 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002083 if (FromPointeeType->isIncompleteOrObjectType() &&
2084 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002086 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002087 ToType, Context,
2088 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002089 return true;
2090 }
2091
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002092 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002093 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002094 ToPointeeType->isVoidType()) {
2095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2096 ToPointeeType,
2097 ToType, Context);
2098 return true;
2099 }
2100
Douglas Gregorf9201e02009-02-11 23:02:49 +00002101 // When we're overloading in C, we allow a special kind of pointer
2102 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002103 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002104 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002105 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002106 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002107 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002108 return true;
2109 }
2110
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002111 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002112 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002113 // An rvalue of type "pointer to cv D," where D is a class type,
2114 // can be converted to an rvalue of type "pointer to cv B," where
2115 // B is a base class (clause 10) of D. If B is an inaccessible
2116 // (clause 11) or ambiguous (10.2) base class of D, a program that
2117 // necessitates this conversion is ill-formed. The result of the
2118 // conversion is a pointer to the base class sub-object of the
2119 // derived class object. The null pointer value is converted to
2120 // the null pointer value of the destination type.
2121 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002122 // Note that we do not check for ambiguity or inaccessibility
2123 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002124 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002125 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002126 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002127 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002128 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002129 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002130 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002131 ToType, Context);
2132 return true;
2133 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002134
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002135 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2136 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2137 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2138 ToPointeeType,
2139 ToType, Context);
2140 return true;
2141 }
2142
Douglas Gregorc7887512008-12-19 19:13:09 +00002143 return false;
2144}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002145
2146/// \brief Adopt the given qualifiers for the given type.
2147static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2148 Qualifiers TQs = T.getQualifiers();
2149
2150 // Check whether qualifiers already match.
2151 if (TQs == Qs)
2152 return T;
2153
2154 if (Qs.compatiblyIncludes(TQs))
2155 return Context.getQualifiedType(T, Qs);
2156
2157 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2158}
Douglas Gregorc7887512008-12-19 19:13:09 +00002159
2160/// isObjCPointerConversion - Determines whether this is an
2161/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2162/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002163bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002164 QualType& ConvertedType,
2165 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002166 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002167 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002168
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002169 // The set of qualifiers on the type we're converting from.
2170 Qualifiers FromQualifiers = FromType.getQualifiers();
2171
Steve Naroff14108da2009-07-10 23:34:53 +00002172 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002173 const ObjCObjectPointerType* ToObjCPtr =
2174 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002175 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002176 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002177
Steve Naroff14108da2009-07-10 23:34:53 +00002178 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002179 // If the pointee types are the same (ignoring qualifications),
2180 // then this is not a pointer conversion.
2181 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2182 FromObjCPtr->getPointeeType()))
2183 return false;
2184
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002185 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002186 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002187 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002188 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002189 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002190 return true;
2191 }
2192 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002193 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002194 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002195 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002196 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002197 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002198 return true;
2199 }
2200 // Objective C++: We're able to convert from a pointer to an
2201 // interface to a pointer to a different interface.
2202 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002203 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2204 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002205 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002206 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2207 FromObjCPtr->getPointeeType()))
2208 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002209 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002210 ToObjCPtr->getPointeeType(),
2211 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002212 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002213 return true;
2214 }
2215
2216 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2217 // Okay: this is some kind of implicit downcast of Objective-C
2218 // interfaces, which is permitted. However, we're going to
2219 // complain about it.
2220 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002222 ToObjCPtr->getPointeeType(),
2223 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002225 return true;
2226 }
Mike Stump1eb44332009-09-09 15:08:12 +00002227 }
Steve Naroff14108da2009-07-10 23:34:53 +00002228 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002229 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002230 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002231 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002232 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002233 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002234 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002235 // to a block pointer type.
2236 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002237 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002238 return true;
2239 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002240 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002242 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002243 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002245 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002246 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002247 return true;
2248 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002249 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002250 return false;
2251
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002252 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002253 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002254 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002255 else if (const BlockPointerType *FromBlockPtr =
2256 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002257 FromPointeeType = FromBlockPtr->getPointeeType();
2258 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002259 return false;
2260
Douglas Gregorc7887512008-12-19 19:13:09 +00002261 // If we have pointers to pointers, recursively check whether this
2262 // is an Objective-C conversion.
2263 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2264 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2265 IncompatibleObjC)) {
2266 // We always complain about this conversion.
2267 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002268 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002269 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002270 return true;
2271 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002272 // Allow conversion of pointee being objective-c pointer to another one;
2273 // as in I* to id.
2274 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2275 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2277 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002278
Douglas Gregorda80f742010-12-01 21:43:58 +00002279 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002280 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002281 return true;
2282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002283
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002284 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002285 // differences in the argument and result types are in Objective-C
2286 // pointer conversions. If so, we permit the conversion (but
2287 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002288 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002289 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002290 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002291 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002292 if (FromFunctionType && ToFunctionType) {
2293 // If the function types are exactly the same, this isn't an
2294 // Objective-C pointer conversion.
2295 if (Context.getCanonicalType(FromPointeeType)
2296 == Context.getCanonicalType(ToPointeeType))
2297 return false;
2298
2299 // Perform the quick checks that will tell us whether these
2300 // function types are obviously different.
2301 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2302 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2303 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2304 return false;
2305
2306 bool HasObjCConversion = false;
2307 if (Context.getCanonicalType(FromFunctionType->getResultType())
2308 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2309 // Okay, the types match exactly. Nothing to do.
2310 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2311 ToFunctionType->getResultType(),
2312 ConvertedType, IncompatibleObjC)) {
2313 // Okay, we have an Objective-C pointer conversion.
2314 HasObjCConversion = true;
2315 } else {
2316 // Function types are too different. Abort.
2317 return false;
2318 }
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Douglas Gregorc7887512008-12-19 19:13:09 +00002320 // Check argument types.
2321 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2322 ArgIdx != NumArgs; ++ArgIdx) {
2323 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2324 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2325 if (Context.getCanonicalType(FromArgType)
2326 == Context.getCanonicalType(ToArgType)) {
2327 // Okay, the types match exactly. Nothing to do.
2328 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2329 ConvertedType, IncompatibleObjC)) {
2330 // Okay, we have an Objective-C pointer conversion.
2331 HasObjCConversion = true;
2332 } else {
2333 // Argument types are too different. Abort.
2334 return false;
2335 }
2336 }
2337
2338 if (HasObjCConversion) {
2339 // We had an Objective-C conversion. Allow this pointer
2340 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002341 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002342 IncompatibleObjC = true;
2343 return true;
2344 }
2345 }
2346
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002347 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002348}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349
John McCallf85e1932011-06-15 23:02:42 +00002350/// \brief Determine whether this is an Objective-C writeback conversion,
2351/// used for parameter passing when performing automatic reference counting.
2352///
2353/// \param FromType The type we're converting form.
2354///
2355/// \param ToType The type we're converting to.
2356///
2357/// \param ConvertedType The type that will be produced after applying
2358/// this conversion.
2359bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2360 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002361 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002362 Context.hasSameUnqualifiedType(FromType, ToType))
2363 return false;
2364
2365 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2366 QualType ToPointee;
2367 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2368 ToPointee = ToPointer->getPointeeType();
2369 else
2370 return false;
2371
2372 Qualifiers ToQuals = ToPointee.getQualifiers();
2373 if (!ToPointee->isObjCLifetimeType() ||
2374 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002375 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002376 return false;
2377
2378 // Argument must be a pointer to __strong to __weak.
2379 QualType FromPointee;
2380 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2381 FromPointee = FromPointer->getPointeeType();
2382 else
2383 return false;
2384
2385 Qualifiers FromQuals = FromPointee.getQualifiers();
2386 if (!FromPointee->isObjCLifetimeType() ||
2387 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2388 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2389 return false;
2390
2391 // Make sure that we have compatible qualifiers.
2392 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2393 if (!ToQuals.compatiblyIncludes(FromQuals))
2394 return false;
2395
2396 // Remove qualifiers from the pointee type we're converting from; they
2397 // aren't used in the compatibility check belong, and we'll be adding back
2398 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2399 FromPointee = FromPointee.getUnqualifiedType();
2400
2401 // The unqualified form of the pointee types must be compatible.
2402 ToPointee = ToPointee.getUnqualifiedType();
2403 bool IncompatibleObjC;
2404 if (Context.typesAreCompatible(FromPointee, ToPointee))
2405 FromPointee = ToPointee;
2406 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2407 IncompatibleObjC))
2408 return false;
2409
2410 /// \brief Construct the type we're converting to, which is a pointer to
2411 /// __autoreleasing pointee.
2412 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2413 ConvertedType = Context.getPointerType(FromPointee);
2414 return true;
2415}
2416
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002417bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2418 QualType& ConvertedType) {
2419 QualType ToPointeeType;
2420 if (const BlockPointerType *ToBlockPtr =
2421 ToType->getAs<BlockPointerType>())
2422 ToPointeeType = ToBlockPtr->getPointeeType();
2423 else
2424 return false;
2425
2426 QualType FromPointeeType;
2427 if (const BlockPointerType *FromBlockPtr =
2428 FromType->getAs<BlockPointerType>())
2429 FromPointeeType = FromBlockPtr->getPointeeType();
2430 else
2431 return false;
2432 // We have pointer to blocks, check whether the only
2433 // differences in the argument and result types are in Objective-C
2434 // pointer conversions. If so, we permit the conversion.
2435
2436 const FunctionProtoType *FromFunctionType
2437 = FromPointeeType->getAs<FunctionProtoType>();
2438 const FunctionProtoType *ToFunctionType
2439 = ToPointeeType->getAs<FunctionProtoType>();
2440
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002441 if (!FromFunctionType || !ToFunctionType)
2442 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002443
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002444 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002445 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002446
2447 // Perform the quick checks that will tell us whether these
2448 // function types are obviously different.
2449 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2450 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2451 return false;
2452
2453 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2454 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2455 if (FromEInfo != ToEInfo)
2456 return false;
2457
2458 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002459 if (Context.hasSameType(FromFunctionType->getResultType(),
2460 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002461 // Okay, the types match exactly. Nothing to do.
2462 } else {
2463 QualType RHS = FromFunctionType->getResultType();
2464 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002465 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002466 !RHS.hasQualifiers() && LHS.hasQualifiers())
2467 LHS = LHS.getUnqualifiedType();
2468
2469 if (Context.hasSameType(RHS,LHS)) {
2470 // OK exact match.
2471 } else if (isObjCPointerConversion(RHS, LHS,
2472 ConvertedType, IncompatibleObjC)) {
2473 if (IncompatibleObjC)
2474 return false;
2475 // Okay, we have an Objective-C pointer conversion.
2476 }
2477 else
2478 return false;
2479 }
2480
2481 // Check argument types.
2482 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2483 ArgIdx != NumArgs; ++ArgIdx) {
2484 IncompatibleObjC = false;
2485 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2486 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2487 if (Context.hasSameType(FromArgType, ToArgType)) {
2488 // Okay, the types match exactly. Nothing to do.
2489 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2490 ConvertedType, IncompatibleObjC)) {
2491 if (IncompatibleObjC)
2492 return false;
2493 // Okay, we have an Objective-C pointer conversion.
2494 } else
2495 // Argument types are too different. Abort.
2496 return false;
2497 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002498 if (LangOpts.ObjCAutoRefCount &&
2499 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2500 ToFunctionType))
2501 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002502
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002503 ConvertedType = ToType;
2504 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002505}
2506
Richard Trieu6efd4c52011-11-23 22:32:32 +00002507enum {
2508 ft_default,
2509 ft_different_class,
2510 ft_parameter_arity,
2511 ft_parameter_mismatch,
2512 ft_return_type,
2513 ft_qualifer_mismatch
2514};
2515
2516/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2517/// function types. Catches different number of parameter, mismatch in
2518/// parameter types, and different return types.
2519void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2520 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002521 // If either type is not valid, include no extra info.
2522 if (FromType.isNull() || ToType.isNull()) {
2523 PDiag << ft_default;
2524 return;
2525 }
2526
Richard Trieu6efd4c52011-11-23 22:32:32 +00002527 // Get the function type from the pointers.
2528 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2529 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2530 *ToMember = ToType->getAs<MemberPointerType>();
2531 if (FromMember->getClass() != ToMember->getClass()) {
2532 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2533 << QualType(FromMember->getClass(), 0);
2534 return;
2535 }
2536 FromType = FromMember->getPointeeType();
2537 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002538 }
2539
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002540 if (FromType->isPointerType())
2541 FromType = FromType->getPointeeType();
2542 if (ToType->isPointerType())
2543 ToType = ToType->getPointeeType();
2544
2545 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002546 FromType = FromType.getNonReferenceType();
2547 ToType = ToType.getNonReferenceType();
2548
Richard Trieu6efd4c52011-11-23 22:32:32 +00002549 // Don't print extra info for non-specialized template functions.
2550 if (FromType->isInstantiationDependentType() &&
2551 !FromType->getAs<TemplateSpecializationType>()) {
2552 PDiag << ft_default;
2553 return;
2554 }
2555
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002556 // No extra info for same types.
2557 if (Context.hasSameType(FromType, ToType)) {
2558 PDiag << ft_default;
2559 return;
2560 }
2561
Richard Trieu6efd4c52011-11-23 22:32:32 +00002562 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2563 *ToFunction = ToType->getAs<FunctionProtoType>();
2564
2565 // Both types need to be function types.
2566 if (!FromFunction || !ToFunction) {
2567 PDiag << ft_default;
2568 return;
2569 }
2570
2571 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2572 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2573 << FromFunction->getNumArgs();
2574 return;
2575 }
2576
2577 // Handle different parameter types.
2578 unsigned ArgPos;
2579 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2580 PDiag << ft_parameter_mismatch << ArgPos + 1
2581 << ToFunction->getArgType(ArgPos)
2582 << FromFunction->getArgType(ArgPos);
2583 return;
2584 }
2585
2586 // Handle different return type.
2587 if (!Context.hasSameType(FromFunction->getResultType(),
2588 ToFunction->getResultType())) {
2589 PDiag << ft_return_type << ToFunction->getResultType()
2590 << FromFunction->getResultType();
2591 return;
2592 }
2593
2594 unsigned FromQuals = FromFunction->getTypeQuals(),
2595 ToQuals = ToFunction->getTypeQuals();
2596 if (FromQuals != ToQuals) {
2597 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2598 return;
2599 }
2600
2601 // Unable to find a difference, so add no extra info.
2602 PDiag << ft_default;
2603}
2604
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002605/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002606/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002607/// they have same number of arguments. If the parameters are different,
2608/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002609bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002610 const FunctionProtoType *NewType,
2611 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002612 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2613 N = NewType->arg_type_begin(),
2614 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Eli Friedman06017002013-06-18 22:41:37 +00002615 if (!Context.hasSameType(*O, *N)) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002616 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002617 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002618 }
2619 }
2620 return true;
2621}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002622
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002623/// CheckPointerConversion - Check the pointer conversion from the
2624/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002625/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002626/// conversions for which IsPointerConversion has already returned
2627/// true. It returns true and produces a diagnostic if there was an
2628/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002629bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002630 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002631 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002632 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002633 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002634 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002635
John McCalldaa8e4e2010-11-15 09:13:47 +00002636 Kind = CK_BitCast;
2637
David Blaikie50800fc2012-08-08 17:33:31 +00002638 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2639 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2640 Expr::NPCK_ZeroExpression) {
2641 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2642 DiagRuntimeBehavior(From->getExprLoc(), From,
2643 PDiag(diag::warn_impcast_bool_to_null_pointer)
2644 << ToType << From->getSourceRange());
2645 else if (!isUnevaluatedContext())
2646 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2647 << ToType << From->getSourceRange();
2648 }
John McCall1d9b3b22011-09-09 05:25:32 +00002649 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2650 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002651 QualType FromPointeeType = FromPtrType->getPointeeType(),
2652 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002653
Douglas Gregor5fccd362010-03-03 23:55:11 +00002654 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2655 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002656 // We must have a derived-to-base conversion. Check an
2657 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002658 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2659 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002660 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002661 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002662 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002663
Anders Carlsson61faec12009-09-12 04:46:44 +00002664 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002665 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002666 }
2667 }
John McCall1d9b3b22011-09-09 05:25:32 +00002668 } else if (const ObjCObjectPointerType *ToPtrType =
2669 ToType->getAs<ObjCObjectPointerType>()) {
2670 if (const ObjCObjectPointerType *FromPtrType =
2671 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002672 // Objective-C++ conversions are always okay.
2673 // FIXME: We should have a different class of conversions for the
2674 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002675 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002676 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002677 } else if (FromType->isBlockPointerType()) {
2678 Kind = CK_BlockPointerToObjCPointerCast;
2679 } else {
2680 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002681 }
John McCall1d9b3b22011-09-09 05:25:32 +00002682 } else if (ToType->isBlockPointerType()) {
2683 if (!FromType->isBlockPointerType())
2684 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002685 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002686
2687 // We shouldn't fall into this case unless it's valid for other
2688 // reasons.
2689 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2690 Kind = CK_NullToPointer;
2691
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002692 return false;
2693}
2694
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002695/// IsMemberPointerConversion - Determines whether the conversion of the
2696/// expression From, which has the (possibly adjusted) type FromType, can be
2697/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2698/// If so, returns true and places the converted type (that might differ from
2699/// ToType in its cv-qualifiers at some level) into ConvertedType.
2700bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002701 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002702 bool InOverloadResolution,
2703 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002704 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002705 if (!ToTypePtr)
2706 return false;
2707
2708 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002709 if (From->isNullPointerConstant(Context,
2710 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2711 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002712 ConvertedType = ToType;
2713 return true;
2714 }
2715
2716 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002717 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002718 if (!FromTypePtr)
2719 return false;
2720
2721 // A pointer to member of B can be converted to a pointer to member of D,
2722 // where D is derived from B (C++ 4.11p2).
2723 QualType FromClass(FromTypePtr->getClass(), 0);
2724 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002725
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002726 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002727 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002728 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002729 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2730 ToClass.getTypePtr());
2731 return true;
2732 }
2733
2734 return false;
2735}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002736
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002737/// CheckMemberPointerConversion - Check the member pointer conversion from the
2738/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002739/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002740/// for which IsMemberPointerConversion has already returned true. It returns
2741/// true and produces a diagnostic if there was an error, or returns false
2742/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002743bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002744 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002745 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002746 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002747 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002748 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002749 if (!FromPtrType) {
2750 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002751 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002752 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002753 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002754 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002755 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002756 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002757
Ted Kremenek6217b802009-07-29 21:53:49 +00002758 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002759 assert(ToPtrType && "No member pointer cast has a target type "
2760 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002761
Sebastian Redl21593ac2009-01-28 18:33:18 +00002762 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2763 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002764
Sebastian Redl21593ac2009-01-28 18:33:18 +00002765 // FIXME: What about dependent types?
2766 assert(FromClass->isRecordType() && "Pointer into non-class.");
2767 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002768
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002770 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002771 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2772 assert(DerivationOkay &&
2773 "Should not have been called if derivation isn't OK.");
2774 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002775
Sebastian Redl21593ac2009-01-28 18:33:18 +00002776 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2777 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002778 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2779 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2780 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2781 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002782 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002783
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002784 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002785 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2786 << FromClass << ToClass << QualType(VBase, 0)
2787 << From->getSourceRange();
2788 return true;
2789 }
2790
John McCall6b2accb2010-02-10 09:31:12 +00002791 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002792 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2793 Paths.front(),
2794 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002795
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002796 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002797 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002798 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002799 return false;
2800}
2801
Douglas Gregor98cd5992008-10-21 23:43:52 +00002802/// IsQualificationConversion - Determines whether the conversion from
2803/// an rvalue of type FromType to ToType is a qualification conversion
2804/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002805///
2806/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2807/// when the qualification conversion involves a change in the Objective-C
2808/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002809bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002811 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002812 FromType = Context.getCanonicalType(FromType);
2813 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002814 ObjCLifetimeConversion = false;
2815
Douglas Gregor98cd5992008-10-21 23:43:52 +00002816 // If FromType and ToType are the same type, this is not a
2817 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002818 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002819 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002820
Douglas Gregor98cd5992008-10-21 23:43:52 +00002821 // (C++ 4.4p4):
2822 // A conversion can add cv-qualifiers at levels other than the first
2823 // in multi-level pointers, subject to the following rules: [...]
2824 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002825 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002826 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002827 // Within each iteration of the loop, we check the qualifiers to
2828 // determine if this still looks like a qualification
2829 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002830 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002831 // until there are no more pointers or pointers-to-members left to
2832 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002833 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002834
Douglas Gregor621c92a2011-04-25 18:40:17 +00002835 Qualifiers FromQuals = FromType.getQualifiers();
2836 Qualifiers ToQuals = ToType.getQualifiers();
2837
John McCallf85e1932011-06-15 23:02:42 +00002838 // Objective-C ARC:
2839 // Check Objective-C lifetime conversions.
2840 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2841 UnwrappedAnyPointer) {
2842 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2843 ObjCLifetimeConversion = true;
2844 FromQuals.removeObjCLifetime();
2845 ToQuals.removeObjCLifetime();
2846 } else {
2847 // Qualification conversions cannot cast between different
2848 // Objective-C lifetime qualifiers.
2849 return false;
2850 }
2851 }
2852
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002853 // Allow addition/removal of GC attributes but not changing GC attributes.
2854 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2855 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2856 FromQuals.removeObjCGCAttr();
2857 ToQuals.removeObjCGCAttr();
2858 }
2859
Douglas Gregor98cd5992008-10-21 23:43:52 +00002860 // -- for every j > 0, if const is in cv 1,j then const is in cv
2861 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002862 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002863 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Douglas Gregor98cd5992008-10-21 23:43:52 +00002865 // -- if the cv 1,j and cv 2,j are different, then const is in
2866 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002867 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002868 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002869 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Douglas Gregor98cd5992008-10-21 23:43:52 +00002871 // Keep track of whether all prior cv-qualifiers in the "to" type
2872 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002873 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002874 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002875 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002876
2877 // We are left with FromType and ToType being the pointee types
2878 // after unwrapping the original FromType and ToType the same number
2879 // of types. If we unwrapped any pointers, and if FromType and
2880 // ToType have the same unqualified type (since we checked
2881 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002882 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002883}
2884
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002885/// \brief - Determine whether this is a conversion from a scalar type to an
2886/// atomic type.
2887///
2888/// If successful, updates \c SCS's second and third steps in the conversion
2889/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002890static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2891 bool InOverloadResolution,
2892 StandardConversionSequence &SCS,
2893 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002894 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2895 if (!ToAtomic)
2896 return false;
2897
2898 StandardConversionSequence InnerSCS;
2899 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2900 InOverloadResolution, InnerSCS,
2901 CStyle, /*AllowObjCWritebackConversion=*/false))
2902 return false;
2903
2904 SCS.Second = InnerSCS.Second;
2905 SCS.setToType(1, InnerSCS.getToType(1));
2906 SCS.Third = InnerSCS.Third;
2907 SCS.QualificationIncludesObjCLifetime
2908 = InnerSCS.QualificationIncludesObjCLifetime;
2909 SCS.setToType(2, InnerSCS.getToType(2));
2910 return true;
2911}
2912
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002913static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2914 CXXConstructorDecl *Constructor,
2915 QualType Type) {
2916 const FunctionProtoType *CtorType =
2917 Constructor->getType()->getAs<FunctionProtoType>();
2918 if (CtorType->getNumArgs() > 0) {
2919 QualType FirstArg = CtorType->getArgType(0);
2920 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2921 return true;
2922 }
2923 return false;
2924}
2925
Sebastian Redl56a04282012-02-11 23:51:08 +00002926static OverloadingResult
2927IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2928 CXXRecordDecl *To,
2929 UserDefinedConversionSequence &User,
2930 OverloadCandidateSet &CandidateSet,
2931 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002932 DeclContext::lookup_result R = S.LookupConstructors(To);
2933 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002934 Con != ConEnd; ++Con) {
2935 NamedDecl *D = *Con;
2936 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2937
2938 // Find the constructor (which may be a template).
2939 CXXConstructorDecl *Constructor = 0;
2940 FunctionTemplateDecl *ConstructorTmpl
2941 = dyn_cast<FunctionTemplateDecl>(D);
2942 if (ConstructorTmpl)
2943 Constructor
2944 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2945 else
2946 Constructor = cast<CXXConstructorDecl>(D);
2947
2948 bool Usable = !Constructor->isInvalidDecl() &&
2949 S.isInitListConstructor(Constructor) &&
2950 (AllowExplicit || !Constructor->isExplicit());
2951 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002952 // If the first argument is (a reference to) the target type,
2953 // suppress conversions.
2954 bool SuppressUserConversions =
2955 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002956 if (ConstructorTmpl)
2957 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2958 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002959 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002960 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002961 else
2962 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002963 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002964 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002965 }
2966 }
2967
2968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2969
2970 OverloadCandidateSet::iterator Best;
2971 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2972 case OR_Success: {
2973 // Record the standard conversion we used and the conversion function.
2974 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002975 QualType ThisType = Constructor->getThisType(S.Context);
2976 // Initializer lists don't have conversions as such.
2977 User.Before.setAsIdentityConversion();
2978 User.HadMultipleCandidates = HadMultipleCandidates;
2979 User.ConversionFunction = Constructor;
2980 User.FoundConversionFunction = Best->FoundDecl;
2981 User.After.setAsIdentityConversion();
2982 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2983 User.After.setAllToTypes(ToType);
2984 return OR_Success;
2985 }
2986
2987 case OR_No_Viable_Function:
2988 return OR_No_Viable_Function;
2989 case OR_Deleted:
2990 return OR_Deleted;
2991 case OR_Ambiguous:
2992 return OR_Ambiguous;
2993 }
2994
2995 llvm_unreachable("Invalid OverloadResult!");
2996}
2997
Douglas Gregor734d9862009-01-30 23:27:23 +00002998/// Determines whether there is a user-defined conversion sequence
2999/// (C++ [over.ics.user]) that converts expression From to the type
3000/// ToType. If such a conversion exists, User will contain the
3001/// user-defined conversion sequence that performs such a conversion
3002/// and this routine will return true. Otherwise, this routine returns
3003/// false and User is unspecified.
3004///
Douglas Gregor734d9862009-01-30 23:27:23 +00003005/// \param AllowExplicit true if the conversion should consider C++0x
3006/// "explicit" conversion functions as well as non-explicit conversion
3007/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003008static OverloadingResult
3009IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003010 UserDefinedConversionSequence &User,
3011 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003012 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003013 // Whether we will only visit constructors.
3014 bool ConstructorsOnly = false;
3015
3016 // If the type we are conversion to is a class type, enumerate its
3017 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003018 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003019 // C++ [over.match.ctor]p1:
3020 // When objects of class type are direct-initialized (8.5), or
3021 // copy-initialized from an expression of the same or a
3022 // derived class type (8.5), overload resolution selects the
3023 // constructor. [...] For copy-initialization, the candidate
3024 // functions are all the converting constructors (12.3.1) of
3025 // that class. The argument list is the expression-list within
3026 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003027 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003028 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003029 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003030 ConstructorsOnly = true;
3031
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003032 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003033 // RequireCompleteType may have returned true due to some invalid decl
3034 // during template instantiation, but ToType may be complete enough now
3035 // to try to recover.
3036 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003037 // We're not going to find any constructors.
3038 } else if (CXXRecordDecl *ToRecordDecl
3039 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003040
3041 Expr **Args = &From;
3042 unsigned NumArgs = 1;
3043 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003044 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003045 // But first, see if there is an init-list-contructor that will work.
3046 OverloadingResult Result = IsInitializerListConstructorConversion(
3047 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3048 if (Result != OR_No_Viable_Function)
3049 return Result;
3050 // Never mind.
3051 CandidateSet.clear();
3052
3053 // If we're list-initializing, we pass the individual elements as
3054 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003055 Args = InitList->getInits();
3056 NumArgs = InitList->getNumInits();
3057 ListInitializing = true;
3058 }
3059
David Blaikie3bc93e32012-12-19 00:45:41 +00003060 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3061 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003062 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003063 NamedDecl *D = *Con;
3064 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3065
Douglas Gregordec06662009-08-21 18:42:58 +00003066 // Find the constructor (which may be a template).
3067 CXXConstructorDecl *Constructor = 0;
3068 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003069 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003070 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003071 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003072 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3073 else
John McCall9aa472c2010-03-19 07:35:19 +00003074 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003075
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003076 bool Usable = !Constructor->isInvalidDecl();
3077 if (ListInitializing)
3078 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3079 else
3080 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3081 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003082 bool SuppressUserConversions = !ConstructorsOnly;
3083 if (SuppressUserConversions && ListInitializing) {
3084 SuppressUserConversions = false;
3085 if (NumArgs == 1) {
3086 // If the first argument is (a reference to) the target type,
3087 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003088 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3089 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003090 }
3091 }
Douglas Gregordec06662009-08-21 18:42:58 +00003092 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003093 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3094 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003095 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003096 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003097 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003098 // Allow one user-defined conversion when user specifies a
3099 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003100 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003101 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003102 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003103 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003104 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003105 }
3106 }
3107
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003108 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003109 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003110 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003111 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003112 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003113 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003114 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003115 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3116 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003117 std::pair<CXXRecordDecl::conversion_iterator,
3118 CXXRecordDecl::conversion_iterator>
3119 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3120 for (CXXRecordDecl::conversion_iterator
3121 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003122 DeclAccessPair FoundDecl = I.getPair();
3123 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003124 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3125 if (isa<UsingShadowDecl>(D))
3126 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3127
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003128 CXXConversionDecl *Conv;
3129 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003130 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3131 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003132 else
John McCall32daa422010-03-31 01:36:47 +00003133 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003134
3135 if (AllowExplicit || !Conv->isExplicit()) {
3136 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003137 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3138 ActingContext, From, ToType,
3139 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003140 else
John McCall120d63c2010-08-24 20:38:10 +00003141 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3142 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003143 }
3144 }
3145 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003146 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003147
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003148 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3149
Douglas Gregor60d62c22008-10-31 16:23:19 +00003150 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003151 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003152 case OR_Success:
3153 // Record the standard conversion we used and the conversion function.
3154 if (CXXConstructorDecl *Constructor
3155 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3156 // C++ [over.ics.user]p1:
3157 // If the user-defined conversion is specified by a
3158 // constructor (12.3.1), the initial standard conversion
3159 // sequence converts the source type to the type required by
3160 // the argument of the constructor.
3161 //
3162 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003163 if (isa<InitListExpr>(From)) {
3164 // Initializer lists don't have conversions as such.
3165 User.Before.setAsIdentityConversion();
3166 } else {
3167 if (Best->Conversions[0].isEllipsis())
3168 User.EllipsisConversion = true;
3169 else {
3170 User.Before = Best->Conversions[0].Standard;
3171 User.EllipsisConversion = false;
3172 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003173 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003174 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003175 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003176 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003177 User.After.setAsIdentityConversion();
3178 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3179 User.After.setAllToTypes(ToType);
3180 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003181 }
3182 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003183 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3184 // C++ [over.ics.user]p1:
3185 //
3186 // [...] If the user-defined conversion is specified by a
3187 // conversion function (12.3.2), the initial standard
3188 // conversion sequence converts the source type to the
3189 // implicit object parameter of the conversion function.
3190 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003191 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003192 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003193 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003194 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003195
John McCall120d63c2010-08-24 20:38:10 +00003196 // C++ [over.ics.user]p2:
3197 // The second standard conversion sequence converts the
3198 // result of the user-defined conversion to the target type
3199 // for the sequence. Since an implicit conversion sequence
3200 // is an initialization, the special rules for
3201 // initialization by user-defined conversion apply when
3202 // selecting the best user-defined conversion for a
3203 // user-defined conversion sequence (see 13.3.3 and
3204 // 13.3.3.1).
3205 User.After = Best->FinalConversion;
3206 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003207 }
David Blaikie7530c032012-01-17 06:56:22 +00003208 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003209
John McCall120d63c2010-08-24 20:38:10 +00003210 case OR_No_Viable_Function:
3211 return OR_No_Viable_Function;
3212 case OR_Deleted:
3213 // No conversion here! We're done.
3214 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
John McCall120d63c2010-08-24 20:38:10 +00003216 case OR_Ambiguous:
3217 return OR_Ambiguous;
3218 }
3219
David Blaikie7530c032012-01-17 06:56:22 +00003220 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003221}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003222
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003223bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003225 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003226 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003227 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003228 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003229 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003230 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003231 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003232 diag::err_typecheck_ambiguous_condition)
3233 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo7419d012013-06-27 01:50:25 +00003234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo288f76a2013-06-27 03:36:30 +00003235 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo7419d012013-06-27 01:50:25 +00003236 diag::err_typecheck_nonviable_condition_incomplete,
3237 From->getType(), From->getSourceRange()))
3238 Diag(From->getLocStart(),
3239 diag::err_typecheck_nonviable_condition)
3240 << From->getType() << From->getSourceRange() << ToType;
3241 }
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003242 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003243 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003244 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003245 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003246}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003247
Douglas Gregorb734e242012-02-22 17:32:19 +00003248/// \brief Compare the user-defined conversion functions or constructors
3249/// of two user-defined conversion sequences to determine whether any ordering
3250/// is possible.
3251static ImplicitConversionSequence::CompareKind
3252compareConversionFunctions(Sema &S,
3253 FunctionDecl *Function1,
3254 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003255 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003256 return ImplicitConversionSequence::Indistinguishable;
3257
3258 // Objective-C++:
3259 // If both conversion functions are implicitly-declared conversions from
3260 // a lambda closure type to a function pointer and a block pointer,
3261 // respectively, always prefer the conversion to a function pointer,
3262 // because the function pointer is more lightweight and is more likely
3263 // to keep code working.
3264 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3265 if (!Conv1)
3266 return ImplicitConversionSequence::Indistinguishable;
3267
3268 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3269 if (!Conv2)
3270 return ImplicitConversionSequence::Indistinguishable;
3271
3272 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3273 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3274 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3275 if (Block1 != Block2)
3276 return Block1? ImplicitConversionSequence::Worse
3277 : ImplicitConversionSequence::Better;
3278 }
3279
3280 return ImplicitConversionSequence::Indistinguishable;
3281}
3282
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003283/// CompareImplicitConversionSequences - Compare two implicit
3284/// conversion sequences to determine whether one is better than the
3285/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003286static ImplicitConversionSequence::CompareKind
3287CompareImplicitConversionSequences(Sema &S,
3288 const ImplicitConversionSequence& ICS1,
3289 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003290{
3291 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3292 // conversion sequences (as defined in 13.3.3.1)
3293 // -- a standard conversion sequence (13.3.3.1.1) is a better
3294 // conversion sequence than a user-defined conversion sequence or
3295 // an ellipsis conversion sequence, and
3296 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3297 // conversion sequence than an ellipsis conversion sequence
3298 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003299 //
John McCall1d318332010-01-12 00:44:57 +00003300 // C++0x [over.best.ics]p10:
3301 // For the purpose of ranking implicit conversion sequences as
3302 // described in 13.3.3.2, the ambiguous conversion sequence is
3303 // treated as a user-defined sequence that is indistinguishable
3304 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003305 if (ICS1.getKindRank() < ICS2.getKindRank())
3306 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003307 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003308 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003309
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003310 // The following checks require both conversion sequences to be of
3311 // the same kind.
3312 if (ICS1.getKind() != ICS2.getKind())
3313 return ImplicitConversionSequence::Indistinguishable;
3314
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003315 ImplicitConversionSequence::CompareKind Result =
3316 ImplicitConversionSequence::Indistinguishable;
3317
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003318 // Two implicit conversion sequences of the same form are
3319 // indistinguishable conversion sequences unless one of the
3320 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003321 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003322 Result = CompareStandardConversionSequences(S,
3323 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003324 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003325 // User-defined conversion sequence U1 is a better conversion
3326 // sequence than another user-defined conversion sequence U2 if
3327 // they contain the same user-defined conversion function or
3328 // constructor and if the second standard conversion sequence of
3329 // U1 is better than the second standard conversion sequence of
3330 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003331 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003332 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003333 Result = CompareStandardConversionSequences(S,
3334 ICS1.UserDefined.After,
3335 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003336 else
3337 Result = compareConversionFunctions(S,
3338 ICS1.UserDefined.ConversionFunction,
3339 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003340 }
3341
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003342 // List-initialization sequence L1 is a better conversion sequence than
3343 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3344 // for some X and L2 does not.
3345 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003346 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003347 ICS1.isListInitializationSequence() &&
3348 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003349 if (ICS1.isStdInitializerListElement() &&
3350 !ICS2.isStdInitializerListElement())
3351 return ImplicitConversionSequence::Better;
3352 if (!ICS1.isStdInitializerListElement() &&
3353 ICS2.isStdInitializerListElement())
3354 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003355 }
3356
3357 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003358}
3359
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003360static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3361 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3362 Qualifiers Quals;
3363 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003365 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003366
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003367 return Context.hasSameUnqualifiedType(T1, T2);
3368}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369
Douglas Gregorad323a82010-01-27 03:51:04 +00003370// Per 13.3.3.2p3, compare the given standard conversion sequences to
3371// determine if one is a proper subset of the other.
3372static ImplicitConversionSequence::CompareKind
3373compareStandardConversionSubsets(ASTContext &Context,
3374 const StandardConversionSequence& SCS1,
3375 const StandardConversionSequence& SCS2) {
3376 ImplicitConversionSequence::CompareKind Result
3377 = ImplicitConversionSequence::Indistinguishable;
3378
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003380 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003381 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3382 return ImplicitConversionSequence::Better;
3383 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3384 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
Douglas Gregorad323a82010-01-27 03:51:04 +00003386 if (SCS1.Second != SCS2.Second) {
3387 if (SCS1.Second == ICK_Identity)
3388 Result = ImplicitConversionSequence::Better;
3389 else if (SCS2.Second == ICK_Identity)
3390 Result = ImplicitConversionSequence::Worse;
3391 else
3392 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003393 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003394 return ImplicitConversionSequence::Indistinguishable;
3395
3396 if (SCS1.Third == SCS2.Third) {
3397 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3398 : ImplicitConversionSequence::Indistinguishable;
3399 }
3400
3401 if (SCS1.Third == ICK_Identity)
3402 return Result == ImplicitConversionSequence::Worse
3403 ? ImplicitConversionSequence::Indistinguishable
3404 : ImplicitConversionSequence::Better;
3405
3406 if (SCS2.Third == ICK_Identity)
3407 return Result == ImplicitConversionSequence::Better
3408 ? ImplicitConversionSequence::Indistinguishable
3409 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410
Douglas Gregorad323a82010-01-27 03:51:04 +00003411 return ImplicitConversionSequence::Indistinguishable;
3412}
3413
Douglas Gregor440a4832011-01-26 14:52:12 +00003414/// \brief Determine whether one of the given reference bindings is better
3415/// than the other based on what kind of bindings they are.
3416static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3417 const StandardConversionSequence &SCS2) {
3418 // C++0x [over.ics.rank]p3b4:
3419 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3420 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003421 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003422 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003424 // reference*.
3425 //
3426 // FIXME: Rvalue references. We're going rogue with the above edits,
3427 // because the semantics in the current C++0x working paper (N3225 at the
3428 // time of this writing) break the standard definition of std::forward
3429 // and std::reference_wrapper when dealing with references to functions.
3430 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003431 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3432 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3433 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003434
Douglas Gregor440a4832011-01-26 14:52:12 +00003435 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3436 SCS2.IsLvalueReference) ||
3437 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3438 !SCS2.IsLvalueReference);
3439}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003441/// CompareStandardConversionSequences - Compare two standard
3442/// conversion sequences to determine whether one is better than the
3443/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003444static ImplicitConversionSequence::CompareKind
3445CompareStandardConversionSequences(Sema &S,
3446 const StandardConversionSequence& SCS1,
3447 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003448{
3449 // Standard conversion sequence S1 is a better conversion sequence
3450 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3451
3452 // -- S1 is a proper subsequence of S2 (comparing the conversion
3453 // sequences in the canonical form defined by 13.3.3.1.1,
3454 // excluding any Lvalue Transformation; the identity conversion
3455 // sequence is considered to be a subsequence of any
3456 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003457 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003458 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003459 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003460
3461 // -- the rank of S1 is better than the rank of S2 (by the rules
3462 // defined below), or, if not that,
3463 ImplicitConversionRank Rank1 = SCS1.getRank();
3464 ImplicitConversionRank Rank2 = SCS2.getRank();
3465 if (Rank1 < Rank2)
3466 return ImplicitConversionSequence::Better;
3467 else if (Rank2 < Rank1)
3468 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003469
Douglas Gregor57373262008-10-22 14:17:15 +00003470 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3471 // are indistinguishable unless one of the following rules
3472 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Douglas Gregor57373262008-10-22 14:17:15 +00003474 // A conversion that is not a conversion of a pointer, or
3475 // pointer to member, to bool is better than another conversion
3476 // that is such a conversion.
3477 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3478 return SCS2.isPointerConversionToBool()
3479 ? ImplicitConversionSequence::Better
3480 : ImplicitConversionSequence::Worse;
3481
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003482 // C++ [over.ics.rank]p4b2:
3483 //
3484 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003485 // conversion of B* to A* is better than conversion of B* to
3486 // void*, and conversion of A* to void* is better than conversion
3487 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003488 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003489 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003490 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003491 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003492 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3493 // Exactly one of the conversion sequences is a conversion to
3494 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003495 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3496 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003497 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3498 // Neither conversion sequence converts to a void pointer; compare
3499 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003500 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003501 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003502 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003503 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3504 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003505 // Both conversion sequences are conversions to void
3506 // pointers. Compare the source types to determine if there's an
3507 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003508 QualType FromType1 = SCS1.getFromType();
3509 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003510
3511 // Adjust the types we're converting from via the array-to-pointer
3512 // conversion, if we need to.
3513 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003514 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003515 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003516 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003517
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003518 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3519 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003520
John McCall120d63c2010-08-24 20:38:10 +00003521 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003522 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003523 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003524 return ImplicitConversionSequence::Worse;
3525
3526 // Objective-C++: If one interface is more specific than the
3527 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003528 const ObjCObjectPointerType* FromObjCPtr1
3529 = FromType1->getAs<ObjCObjectPointerType>();
3530 const ObjCObjectPointerType* FromObjCPtr2
3531 = FromType2->getAs<ObjCObjectPointerType>();
3532 if (FromObjCPtr1 && FromObjCPtr2) {
3533 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3534 FromObjCPtr2);
3535 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3536 FromObjCPtr1);
3537 if (AssignLeft != AssignRight) {
3538 return AssignLeft? ImplicitConversionSequence::Better
3539 : ImplicitConversionSequence::Worse;
3540 }
Douglas Gregor01919692009-12-13 21:37:05 +00003541 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003542 }
Douglas Gregor57373262008-10-22 14:17:15 +00003543
3544 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3545 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003546 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003547 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003548 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003549
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003550 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003551 // Check for a better reference binding based on the kind of bindings.
3552 if (isBetterReferenceBindingKind(SCS1, SCS2))
3553 return ImplicitConversionSequence::Better;
3554 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3555 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003556
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003557 // C++ [over.ics.rank]p3b4:
3558 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3559 // which the references refer are the same type except for
3560 // top-level cv-qualifiers, and the type to which the reference
3561 // initialized by S2 refers is more cv-qualified than the type
3562 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003563 QualType T1 = SCS1.getToType(2);
3564 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003565 T1 = S.Context.getCanonicalType(T1);
3566 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003567 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003568 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3569 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003570 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003571 // Objective-C++ ARC: If the references refer to objects with different
3572 // lifetimes, prefer bindings that don't change lifetime.
3573 if (SCS1.ObjCLifetimeConversionBinding !=
3574 SCS2.ObjCLifetimeConversionBinding) {
3575 return SCS1.ObjCLifetimeConversionBinding
3576 ? ImplicitConversionSequence::Worse
3577 : ImplicitConversionSequence::Better;
3578 }
3579
Chandler Carruth6df868e2010-12-12 08:17:55 +00003580 // If the type is an array type, promote the element qualifiers to the
3581 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003582 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003583 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003584 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003585 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003586 if (T2.isMoreQualifiedThan(T1))
3587 return ImplicitConversionSequence::Better;
3588 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003589 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003590 }
3591 }
Douglas Gregor57373262008-10-22 14:17:15 +00003592
Francois Pichet1c98d622011-09-18 21:37:37 +00003593 // In Microsoft mode, prefer an integral conversion to a
3594 // floating-to-integral conversion if the integral conversion
3595 // is between types of the same size.
3596 // For example:
3597 // void f(float);
3598 // void f(int);
3599 // int main {
3600 // long a;
3601 // f(a);
3602 // }
3603 // Here, MSVC will call f(int) instead of generating a compile error
3604 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003605 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003606 SCS1.Second == ICK_Integral_Conversion &&
3607 SCS2.Second == ICK_Floating_Integral &&
3608 S.Context.getTypeSize(SCS1.getFromType()) ==
3609 S.Context.getTypeSize(SCS1.getToType(2)))
3610 return ImplicitConversionSequence::Better;
3611
Douglas Gregor57373262008-10-22 14:17:15 +00003612 return ImplicitConversionSequence::Indistinguishable;
3613}
3614
3615/// CompareQualificationConversions - Compares two standard conversion
3616/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003617/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3618ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003619CompareQualificationConversions(Sema &S,
3620 const StandardConversionSequence& SCS1,
3621 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003622 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003623 // -- S1 and S2 differ only in their qualification conversion and
3624 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3625 // cv-qualification signature of type T1 is a proper subset of
3626 // the cv-qualification signature of type T2, and S1 is not the
3627 // deprecated string literal array-to-pointer conversion (4.2).
3628 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3629 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3630 return ImplicitConversionSequence::Indistinguishable;
3631
3632 // FIXME: the example in the standard doesn't use a qualification
3633 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003634 QualType T1 = SCS1.getToType(2);
3635 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003636 T1 = S.Context.getCanonicalType(T1);
3637 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003638 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003639 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3640 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003641
3642 // If the types are the same, we won't learn anything by unwrapped
3643 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003644 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003645 return ImplicitConversionSequence::Indistinguishable;
3646
Chandler Carruth28e318c2009-12-29 07:16:59 +00003647 // If the type is an array type, promote the element qualifiers to the type
3648 // for comparison.
3649 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003650 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003651 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003652 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003653
Mike Stump1eb44332009-09-09 15:08:12 +00003654 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003655 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003656
3657 // Objective-C++ ARC:
3658 // Prefer qualification conversions not involving a change in lifetime
3659 // to qualification conversions that do not change lifetime.
3660 if (SCS1.QualificationIncludesObjCLifetime !=
3661 SCS2.QualificationIncludesObjCLifetime) {
3662 Result = SCS1.QualificationIncludesObjCLifetime
3663 ? ImplicitConversionSequence::Worse
3664 : ImplicitConversionSequence::Better;
3665 }
3666
John McCall120d63c2010-08-24 20:38:10 +00003667 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003668 // Within each iteration of the loop, we check the qualifiers to
3669 // determine if this still looks like a qualification
3670 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003671 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003672 // until there are no more pointers or pointers-to-members left
3673 // to unwrap. This essentially mimics what
3674 // IsQualificationConversion does, but here we're checking for a
3675 // strict subset of qualifiers.
3676 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3677 // The qualifiers are the same, so this doesn't tell us anything
3678 // about how the sequences rank.
3679 ;
3680 else if (T2.isMoreQualifiedThan(T1)) {
3681 // T1 has fewer qualifiers, so it could be the better sequence.
3682 if (Result == ImplicitConversionSequence::Worse)
3683 // Neither has qualifiers that are a subset of the other's
3684 // qualifiers.
3685 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Douglas Gregor57373262008-10-22 14:17:15 +00003687 Result = ImplicitConversionSequence::Better;
3688 } else if (T1.isMoreQualifiedThan(T2)) {
3689 // T2 has fewer qualifiers, so it could be the better sequence.
3690 if (Result == ImplicitConversionSequence::Better)
3691 // Neither has qualifiers that are a subset of the other's
3692 // qualifiers.
3693 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Douglas Gregor57373262008-10-22 14:17:15 +00003695 Result = ImplicitConversionSequence::Worse;
3696 } else {
3697 // Qualifiers are disjoint.
3698 return ImplicitConversionSequence::Indistinguishable;
3699 }
3700
3701 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003702 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003703 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003704 }
3705
Douglas Gregor57373262008-10-22 14:17:15 +00003706 // Check that the winning standard conversion sequence isn't using
3707 // the deprecated string literal array to pointer conversion.
3708 switch (Result) {
3709 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003710 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003711 Result = ImplicitConversionSequence::Indistinguishable;
3712 break;
3713
3714 case ImplicitConversionSequence::Indistinguishable:
3715 break;
3716
3717 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003718 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003719 Result = ImplicitConversionSequence::Indistinguishable;
3720 break;
3721 }
3722
3723 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003724}
3725
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726/// CompareDerivedToBaseConversions - Compares two standard conversion
3727/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003728/// various kinds of derived-to-base conversions (C++
3729/// [over.ics.rank]p4b3). As part of these checks, we also look at
3730/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003731ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003732CompareDerivedToBaseConversions(Sema &S,
3733 const StandardConversionSequence& SCS1,
3734 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003735 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003736 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003737 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003738 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003739
3740 // Adjust the types we're converting from via the array-to-pointer
3741 // conversion, if we need to.
3742 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003743 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003744 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003745 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003746
3747 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003748 FromType1 = S.Context.getCanonicalType(FromType1);
3749 ToType1 = S.Context.getCanonicalType(ToType1);
3750 FromType2 = S.Context.getCanonicalType(FromType2);
3751 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003752
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003753 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003754 //
3755 // If class B is derived directly or indirectly from class A and
3756 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003757 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003758 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003759 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003760 SCS2.Second == ICK_Pointer_Conversion &&
3761 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3762 FromType1->isPointerType() && FromType2->isPointerType() &&
3763 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003764 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003765 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003766 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003767 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003768 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003769 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003770 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003771 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003772
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003773 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003774 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003775 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003776 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003777 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003778 return ImplicitConversionSequence::Worse;
3779 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003780
3781 // -- conversion of B* to A* is better than conversion of C* to A*,
3782 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003783 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003784 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003785 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003786 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003787 }
3788 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3789 SCS2.Second == ICK_Pointer_Conversion) {
3790 const ObjCObjectPointerType *FromPtr1
3791 = FromType1->getAs<ObjCObjectPointerType>();
3792 const ObjCObjectPointerType *FromPtr2
3793 = FromType2->getAs<ObjCObjectPointerType>();
3794 const ObjCObjectPointerType *ToPtr1
3795 = ToType1->getAs<ObjCObjectPointerType>();
3796 const ObjCObjectPointerType *ToPtr2
3797 = ToType2->getAs<ObjCObjectPointerType>();
3798
3799 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3800 // Apply the same conversion ranking rules for Objective-C pointer types
3801 // that we do for C++ pointers to class types. However, we employ the
3802 // Objective-C pseudo-subtyping relationship used for assignment of
3803 // Objective-C pointer types.
3804 bool FromAssignLeft
3805 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3806 bool FromAssignRight
3807 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3808 bool ToAssignLeft
3809 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3810 bool ToAssignRight
3811 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3812
3813 // A conversion to an a non-id object pointer type or qualified 'id'
3814 // type is better than a conversion to 'id'.
3815 if (ToPtr1->isObjCIdType() &&
3816 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3817 return ImplicitConversionSequence::Worse;
3818 if (ToPtr2->isObjCIdType() &&
3819 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3820 return ImplicitConversionSequence::Better;
3821
3822 // A conversion to a non-id object pointer type is better than a
3823 // conversion to a qualified 'id' type
3824 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3825 return ImplicitConversionSequence::Worse;
3826 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3827 return ImplicitConversionSequence::Better;
3828
3829 // A conversion to an a non-Class object pointer type or qualified 'Class'
3830 // type is better than a conversion to 'Class'.
3831 if (ToPtr1->isObjCClassType() &&
3832 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3833 return ImplicitConversionSequence::Worse;
3834 if (ToPtr2->isObjCClassType() &&
3835 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3836 return ImplicitConversionSequence::Better;
3837
3838 // A conversion to a non-Class object pointer type is better than a
3839 // conversion to a qualified 'Class' type.
3840 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3841 return ImplicitConversionSequence::Worse;
3842 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3843 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Douglas Gregor395cc372011-01-31 18:51:41 +00003845 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3846 if (S.Context.hasSameType(FromType1, FromType2) &&
3847 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3848 (ToAssignLeft != ToAssignRight))
3849 return ToAssignLeft? ImplicitConversionSequence::Worse
3850 : ImplicitConversionSequence::Better;
3851
3852 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3853 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3854 (FromAssignLeft != FromAssignRight))
3855 return FromAssignLeft? ImplicitConversionSequence::Better
3856 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003857 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003858 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003859
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003860 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003861 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3862 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3863 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003865 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003866 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003867 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003869 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003870 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003871 ToType2->getAs<MemberPointerType>();
3872 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3873 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3874 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3875 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3876 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3877 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3878 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3879 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003880 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003881 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003882 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003883 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003884 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003885 return ImplicitConversionSequence::Better;
3886 }
3887 // conversion of B::* to C::* is better than conversion of A::* to C::*
3888 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003889 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003890 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003891 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003892 return ImplicitConversionSequence::Worse;
3893 }
3894 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003895
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003896 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003897 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003898 // -- binding of an expression of type C to a reference of type
3899 // B& is better than binding an expression of type C to a
3900 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003901 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3902 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3903 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003904 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003905 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003906 return ImplicitConversionSequence::Worse;
3907 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003908
Douglas Gregor225c41e2008-11-03 19:09:14 +00003909 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003910 // -- binding of an expression of type B to a reference of type
3911 // A& is better than binding an expression of type C to a
3912 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003913 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3914 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3915 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003916 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003917 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003918 return ImplicitConversionSequence::Worse;
3919 }
3920 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003921
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003922 return ImplicitConversionSequence::Indistinguishable;
3923}
3924
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003925/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3926/// C++ class.
3927static bool isTypeValid(QualType T) {
3928 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3929 return !Record->isInvalidDecl();
3930
3931 return true;
3932}
3933
Douglas Gregorabe183d2010-04-13 16:31:36 +00003934/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3935/// determine whether they are reference-related,
3936/// reference-compatible, reference-compatible with added
3937/// qualification, or incompatible, for use in C++ initialization by
3938/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3939/// type, and the first type (T1) is the pointee type of the reference
3940/// type being initialized.
3941Sema::ReferenceCompareResult
3942Sema::CompareReferenceRelationship(SourceLocation Loc,
3943 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003944 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003945 bool &ObjCConversion,
3946 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003947 assert(!OrigT1->isReferenceType() &&
3948 "T1 must be the pointee type of the reference type");
3949 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3950
3951 QualType T1 = Context.getCanonicalType(OrigT1);
3952 QualType T2 = Context.getCanonicalType(OrigT2);
3953 Qualifiers T1Quals, T2Quals;
3954 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3955 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3956
3957 // C++ [dcl.init.ref]p4:
3958 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3959 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3960 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003961 DerivedToBase = false;
3962 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003963 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003964 if (UnqualT1 == UnqualT2) {
3965 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003966 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003967 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3968 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003969 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003970 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3971 UnqualT2->isObjCObjectOrInterfaceType() &&
3972 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3973 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003974 else
3975 return Ref_Incompatible;
3976
3977 // At this point, we know that T1 and T2 are reference-related (at
3978 // least).
3979
3980 // If the type is an array type, promote the element qualifiers to the type
3981 // for comparison.
3982 if (isa<ArrayType>(T1) && T1Quals)
3983 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3984 if (isa<ArrayType>(T2) && T2Quals)
3985 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3986
3987 // C++ [dcl.init.ref]p4:
3988 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3989 // reference-related to T2 and cv1 is the same cv-qualification
3990 // as, or greater cv-qualification than, cv2. For purposes of
3991 // overload resolution, cases for which cv1 is greater
3992 // cv-qualification than cv2 are identified as
3993 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003994 //
3995 // Note that we also require equivalence of Objective-C GC and address-space
3996 // qualifiers when performing these computations, so that e.g., an int in
3997 // address space 1 is not reference-compatible with an int in address
3998 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003999 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4000 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4001 T1Quals.removeObjCLifetime();
4002 T2Quals.removeObjCLifetime();
4003 ObjCLifetimeConversion = true;
4004 }
4005
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004006 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004007 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004008 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004009 return Ref_Compatible_With_Added_Qualification;
4010 else
4011 return Ref_Related;
4012}
4013
Douglas Gregor604eb652010-08-11 02:15:33 +00004014/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004015/// with DeclType. Return true if something definite is found.
4016static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004017FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4018 QualType DeclType, SourceLocation DeclLoc,
4019 Expr *Init, QualType T2, bool AllowRvalues,
4020 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004021 assert(T2->isRecordType() && "Can only find conversions of record types.");
4022 CXXRecordDecl *T2RecordDecl
4023 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4024
4025 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004026 std::pair<CXXRecordDecl::conversion_iterator,
4027 CXXRecordDecl::conversion_iterator>
4028 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4029 for (CXXRecordDecl::conversion_iterator
4030 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004031 NamedDecl *D = *I;
4032 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4033 if (isa<UsingShadowDecl>(D))
4034 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4035
4036 FunctionTemplateDecl *ConvTemplate
4037 = dyn_cast<FunctionTemplateDecl>(D);
4038 CXXConversionDecl *Conv;
4039 if (ConvTemplate)
4040 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4041 else
4042 Conv = cast<CXXConversionDecl>(D);
4043
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004045 // explicit conversions, skip it.
4046 if (!AllowExplicit && Conv->isExplicit())
4047 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048
Douglas Gregor604eb652010-08-11 02:15:33 +00004049 if (AllowRvalues) {
4050 bool DerivedToBase = false;
4051 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004052 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004053
4054 // If we are initializing an rvalue reference, don't permit conversion
4055 // functions that return lvalues.
4056 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4057 const ReferenceType *RefType
4058 = Conv->getConversionType()->getAs<LValueReferenceType>();
4059 if (RefType && !RefType->getPointeeType()->isFunctionType())
4060 continue;
4061 }
4062
Douglas Gregor604eb652010-08-11 02:15:33 +00004063 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004064 S.CompareReferenceRelationship(
4065 DeclLoc,
4066 Conv->getConversionType().getNonReferenceType()
4067 .getUnqualifiedType(),
4068 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004069 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004070 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004071 continue;
4072 } else {
4073 // If the conversion function doesn't return a reference type,
4074 // it can't be considered for this conversion. An rvalue reference
4075 // is only acceptable if its referencee is a function type.
4076
4077 const ReferenceType *RefType =
4078 Conv->getConversionType()->getAs<ReferenceType>();
4079 if (!RefType ||
4080 (!RefType->isLValueReferenceType() &&
4081 !RefType->getPointeeType()->isFunctionType()))
4082 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004084
Douglas Gregor604eb652010-08-11 02:15:33 +00004085 if (ConvTemplate)
4086 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004087 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004088 else
4089 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004090 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004091 }
4092
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004093 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4094
Sebastian Redl4680bf22010-06-30 18:13:39 +00004095 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004096 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004097 case OR_Success:
4098 // C++ [over.ics.ref]p1:
4099 //
4100 // [...] If the parameter binds directly to the result of
4101 // applying a conversion function to the argument
4102 // expression, the implicit conversion sequence is a
4103 // user-defined conversion sequence (13.3.3.1.2), with the
4104 // second standard conversion sequence either an identity
4105 // conversion or, if the conversion function returns an
4106 // entity of a type that is a derived class of the parameter
4107 // type, a derived-to-base Conversion.
4108 if (!Best->FinalConversion.DirectBinding)
4109 return false;
4110
4111 ICS.setUserDefined();
4112 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4113 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004114 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004115 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004116 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004117 ICS.UserDefined.EllipsisConversion = false;
4118 assert(ICS.UserDefined.After.ReferenceBinding &&
4119 ICS.UserDefined.After.DirectBinding &&
4120 "Expected a direct reference binding!");
4121 return true;
4122
4123 case OR_Ambiguous:
4124 ICS.setAmbiguous();
4125 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4126 Cand != CandidateSet.end(); ++Cand)
4127 if (Cand->Viable)
4128 ICS.Ambiguous.addConversion(Cand->Function);
4129 return true;
4130
4131 case OR_No_Viable_Function:
4132 case OR_Deleted:
4133 // There was no suitable conversion, or we found a deleted
4134 // conversion; continue with other checks.
4135 return false;
4136 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004137
David Blaikie7530c032012-01-17 06:56:22 +00004138 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004139}
4140
Douglas Gregorabe183d2010-04-13 16:31:36 +00004141/// \brief Compute an implicit conversion sequence for reference
4142/// initialization.
4143static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004144TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004145 SourceLocation DeclLoc,
4146 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004147 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004148 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4149
4150 // Most paths end in a failed conversion.
4151 ImplicitConversionSequence ICS;
4152 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4153
4154 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4155 QualType T2 = Init->getType();
4156
4157 // If the initializer is the address of an overloaded function, try
4158 // to resolve the overloaded function. If all goes well, T2 is the
4159 // type of the resulting function.
4160 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4161 DeclAccessPair Found;
4162 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4163 false, Found))
4164 T2 = Fn->getType();
4165 }
4166
4167 // Compute some basic properties of the types and the initializer.
4168 bool isRValRef = DeclType->isRValueReferenceType();
4169 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004170 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004171 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004172 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004173 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004174 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004175 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004176
Douglas Gregorabe183d2010-04-13 16:31:36 +00004177
Sebastian Redl4680bf22010-06-30 18:13:39 +00004178 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004179 // A reference to type "cv1 T1" is initialized by an expression
4180 // of type "cv2 T2" as follows:
4181
Sebastian Redl4680bf22010-06-30 18:13:39 +00004182 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004183 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004184 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4185 // reference-compatible with "cv2 T2," or
4186 //
4187 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4188 if (InitCategory.isLValue() &&
4189 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004190 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004191 // When a parameter of reference type binds directly (8.5.3)
4192 // to an argument expression, the implicit conversion sequence
4193 // is the identity conversion, unless the argument expression
4194 // has a type that is a derived class of the parameter type,
4195 // in which case the implicit conversion sequence is a
4196 // derived-to-base Conversion (13.3.3.1).
4197 ICS.setStandard();
4198 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004199 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4200 : ObjCConversion? ICK_Compatible_Conversion
4201 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004202 ICS.Standard.Third = ICK_Identity;
4203 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4204 ICS.Standard.setToType(0, T2);
4205 ICS.Standard.setToType(1, T1);
4206 ICS.Standard.setToType(2, T1);
4207 ICS.Standard.ReferenceBinding = true;
4208 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004209 ICS.Standard.IsLvalueReference = !isRValRef;
4210 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4211 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004212 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004213 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004214 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004215
Sebastian Redl4680bf22010-06-30 18:13:39 +00004216 // Nothing more to do: the inaccessibility/ambiguity check for
4217 // derived-to-base conversions is suppressed when we're
4218 // computing the implicit conversion sequence (C++
4219 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004220 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004221 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004222
Sebastian Redl4680bf22010-06-30 18:13:39 +00004223 // -- has a class type (i.e., T2 is a class type), where T1 is
4224 // not reference-related to T2, and can be implicitly
4225 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4226 // is reference-compatible with "cv3 T3" 92) (this
4227 // conversion is selected by enumerating the applicable
4228 // conversion functions (13.3.1.6) and choosing the best
4229 // one through overload resolution (13.3)),
4230 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004231 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004232 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004233 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4234 Init, T2, /*AllowRvalues=*/false,
4235 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004236 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004237 }
4238 }
4239
Sebastian Redl4680bf22010-06-30 18:13:39 +00004240 // -- Otherwise, the reference shall be an lvalue reference to a
4241 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004242 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004243 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004244 // We actually handle one oddity of C++ [over.ics.ref] at this
4245 // point, which is that, due to p2 (which short-circuits reference
4246 // binding by only attempting a simple conversion for non-direct
4247 // bindings) and p3's strange wording, we allow a const volatile
4248 // reference to bind to an rvalue. Hence the check for the presence
4249 // of "const" rather than checking for "const" being the only
4250 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004251 // This is also the point where rvalue references and lvalue inits no longer
4252 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004253 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004254 return ICS;
4255
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004256 // -- If the initializer expression
4257 //
4258 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004259 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004260 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4261 (InitCategory.isXValue() ||
4262 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4263 (InitCategory.isLValue() && T2->isFunctionType()))) {
4264 ICS.setStandard();
4265 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004266 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004267 : ObjCConversion? ICK_Compatible_Conversion
4268 : ICK_Identity;
4269 ICS.Standard.Third = ICK_Identity;
4270 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4271 ICS.Standard.setToType(0, T2);
4272 ICS.Standard.setToType(1, T1);
4273 ICS.Standard.setToType(2, T1);
4274 ICS.Standard.ReferenceBinding = true;
4275 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4276 // binding unless we're binding to a class prvalue.
4277 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4278 // allow the use of rvalue references in C++98/03 for the benefit of
4279 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004280 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004281 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004282 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004283 ICS.Standard.IsLvalueReference = !isRValRef;
4284 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004286 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004287 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004288 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004290 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004291
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004292 // -- has a class type (i.e., T2 is a class type), where T1 is not
4293 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004294 // an xvalue, class prvalue, or function lvalue of type
4295 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004296 // "cv3 T3",
4297 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004298 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004299 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004301 // class subobject).
4302 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004303 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004304 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4305 Init, T2, /*AllowRvalues=*/true,
4306 AllowExplicit)) {
4307 // In the second case, if the reference is an rvalue reference
4308 // and the second standard conversion sequence of the
4309 // user-defined conversion sequence includes an lvalue-to-rvalue
4310 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004311 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004312 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4313 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4314
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004315 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004316 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004317
Douglas Gregorabe183d2010-04-13 16:31:36 +00004318 // -- Otherwise, a temporary of type "cv1 T1" is created and
4319 // initialized from the initializer expression using the
4320 // rules for a non-reference copy initialization (8.5). The
4321 // reference is then bound to the temporary. If T1 is
4322 // reference-related to T2, cv1 must be the same
4323 // cv-qualification as, or greater cv-qualification than,
4324 // cv2; otherwise, the program is ill-formed.
4325 if (RefRelationship == Sema::Ref_Related) {
4326 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4327 // we would be reference-compatible or reference-compatible with
4328 // added qualification. But that wasn't the case, so the reference
4329 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004330 //
4331 // Note that we only want to check address spaces and cvr-qualifiers here.
4332 // ObjC GC and lifetime qualifiers aren't important.
4333 Qualifiers T1Quals = T1.getQualifiers();
4334 Qualifiers T2Quals = T2.getQualifiers();
4335 T1Quals.removeObjCGCAttr();
4336 T1Quals.removeObjCLifetime();
4337 T2Quals.removeObjCGCAttr();
4338 T2Quals.removeObjCLifetime();
4339 if (!T1Quals.compatiblyIncludes(T2Quals))
4340 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004341 }
4342
4343 // If at least one of the types is a class type, the types are not
4344 // related, and we aren't allowed any user conversions, the
4345 // reference binding fails. This case is important for breaking
4346 // recursion, since TryImplicitConversion below will attempt to
4347 // create a temporary through the use of a copy constructor.
4348 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4349 (T1->isRecordType() || T2->isRecordType()))
4350 return ICS;
4351
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004352 // If T1 is reference-related to T2 and the reference is an rvalue
4353 // reference, the initializer expression shall not be an lvalue.
4354 if (RefRelationship >= Sema::Ref_Related &&
4355 isRValRef && Init->Classify(S.Context).isLValue())
4356 return ICS;
4357
Douglas Gregorabe183d2010-04-13 16:31:36 +00004358 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004359 // When a parameter of reference type is not bound directly to
4360 // an argument expression, the conversion sequence is the one
4361 // required to convert the argument expression to the
4362 // underlying type of the reference according to
4363 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4364 // to copy-initializing a temporary of the underlying type with
4365 // the argument expression. Any difference in top-level
4366 // cv-qualification is subsumed by the initialization itself
4367 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004368 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4369 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004370 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004371 /*CStyle=*/false,
4372 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004373
4374 // Of course, that's still a reference binding.
4375 if (ICS.isStandard()) {
4376 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004377 ICS.Standard.IsLvalueReference = !isRValRef;
4378 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4379 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004380 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004381 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004382 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004383 // Don't allow rvalue references to bind to lvalues.
4384 if (DeclType->isRValueReferenceType()) {
4385 if (const ReferenceType *RefType
4386 = ICS.UserDefined.ConversionFunction->getResultType()
4387 ->getAs<LValueReferenceType>()) {
4388 if (!RefType->getPointeeType()->isFunctionType()) {
4389 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4390 DeclType);
4391 return ICS;
4392 }
4393 }
4394 }
4395
Douglas Gregorabe183d2010-04-13 16:31:36 +00004396 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004397 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4398 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4399 ICS.UserDefined.After.BindsToRvalue = true;
4400 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4401 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004402 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004403
Douglas Gregorabe183d2010-04-13 16:31:36 +00004404 return ICS;
4405}
4406
Sebastian Redl5405b812011-10-16 18:19:34 +00004407static ImplicitConversionSequence
4408TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4409 bool SuppressUserConversions,
4410 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004411 bool AllowObjCWritebackConversion,
4412 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004413
4414/// TryListConversion - Try to copy-initialize a value of type ToType from the
4415/// initializer list From.
4416static ImplicitConversionSequence
4417TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4418 bool SuppressUserConversions,
4419 bool InOverloadResolution,
4420 bool AllowObjCWritebackConversion) {
4421 // C++11 [over.ics.list]p1:
4422 // When an argument is an initializer list, it is not an expression and
4423 // special rules apply for converting it to a parameter type.
4424
4425 ImplicitConversionSequence Result;
4426 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004427 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004428
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004429 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004430 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004431 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004432 return Result;
4433
Sebastian Redl5405b812011-10-16 18:19:34 +00004434 // C++11 [over.ics.list]p2:
4435 // If the parameter type is std::initializer_list<X> or "array of X" and
4436 // all the elements can be implicitly converted to X, the implicit
4437 // conversion sequence is the worst conversion necessary to convert an
4438 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004439 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004440 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004441 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004442 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004443 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004444 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004445 if (!X.isNull()) {
4446 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4447 Expr *Init = From->getInit(i);
4448 ImplicitConversionSequence ICS =
4449 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4450 InOverloadResolution,
4451 AllowObjCWritebackConversion);
4452 // If a single element isn't convertible, fail.
4453 if (ICS.isBad()) {
4454 Result = ICS;
4455 break;
4456 }
4457 // Otherwise, look for the worst conversion.
4458 if (Result.isBad() ||
4459 CompareImplicitConversionSequences(S, ICS, Result) ==
4460 ImplicitConversionSequence::Worse)
4461 Result = ICS;
4462 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004463
4464 // For an empty list, we won't have computed any conversion sequence.
4465 // Introduce the identity conversion sequence.
4466 if (From->getNumInits() == 0) {
4467 Result.setStandard();
4468 Result.Standard.setAsIdentityConversion();
4469 Result.Standard.setFromType(ToType);
4470 Result.Standard.setAllToTypes(ToType);
4471 }
4472
Sebastian Redlfe592282012-01-17 22:49:48 +00004473 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004474 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004475 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004476 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004477
4478 // C++11 [over.ics.list]p3:
4479 // Otherwise, if the parameter is a non-aggregate class X and overload
4480 // resolution chooses a single best constructor [...] the implicit
4481 // conversion sequence is a user-defined conversion sequence. If multiple
4482 // constructors are viable but none is better than the others, the
4483 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004484 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4485 // This function can deal with initializer lists.
4486 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4487 /*AllowExplicit=*/false,
4488 InOverloadResolution, /*CStyle=*/false,
4489 AllowObjCWritebackConversion);
4490 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004491 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004492 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004493
4494 // C++11 [over.ics.list]p4:
4495 // Otherwise, if the parameter has an aggregate type which can be
4496 // initialized from the initializer list [...] the implicit conversion
4497 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004498 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004499 // Type is an aggregate, argument is an init list. At this point it comes
4500 // down to checking whether the initialization works.
4501 // FIXME: Find out whether this parameter is consumed or not.
4502 InitializedEntity Entity =
4503 InitializedEntity::InitializeParameter(S.Context, ToType,
4504 /*Consumed=*/false);
4505 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4506 Result.setUserDefined();
4507 Result.UserDefined.Before.setAsIdentityConversion();
4508 // Initializer lists don't have a type.
4509 Result.UserDefined.Before.setFromType(QualType());
4510 Result.UserDefined.Before.setAllToTypes(QualType());
4511
4512 Result.UserDefined.After.setAsIdentityConversion();
4513 Result.UserDefined.After.setFromType(ToType);
4514 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004515 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004516 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004517 return Result;
4518 }
4519
4520 // C++11 [over.ics.list]p5:
4521 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004522 if (ToType->isReferenceType()) {
4523 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4524 // mention initializer lists in any way. So we go by what list-
4525 // initialization would do and try to extrapolate from that.
4526
4527 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4528
4529 // If the initializer list has a single element that is reference-related
4530 // to the parameter type, we initialize the reference from that.
4531 if (From->getNumInits() == 1) {
4532 Expr *Init = From->getInit(0);
4533
4534 QualType T2 = Init->getType();
4535
4536 // If the initializer is the address of an overloaded function, try
4537 // to resolve the overloaded function. If all goes well, T2 is the
4538 // type of the resulting function.
4539 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4540 DeclAccessPair Found;
4541 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4542 Init, ToType, false, Found))
4543 T2 = Fn->getType();
4544 }
4545
4546 // Compute some basic properties of the types and the initializer.
4547 bool dummy1 = false;
4548 bool dummy2 = false;
4549 bool dummy3 = false;
4550 Sema::ReferenceCompareResult RefRelationship
4551 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4552 dummy2, dummy3);
4553
4554 if (RefRelationship >= Sema::Ref_Related)
4555 return TryReferenceInit(S, Init, ToType,
4556 /*FIXME:*/From->getLocStart(),
4557 SuppressUserConversions,
4558 /*AllowExplicit=*/false);
4559 }
4560
4561 // Otherwise, we bind the reference to a temporary created from the
4562 // initializer list.
4563 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4564 InOverloadResolution,
4565 AllowObjCWritebackConversion);
4566 if (Result.isFailure())
4567 return Result;
4568 assert(!Result.isEllipsis() &&
4569 "Sub-initialization cannot result in ellipsis conversion.");
4570
4571 // Can we even bind to a temporary?
4572 if (ToType->isRValueReferenceType() ||
4573 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4574 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4575 Result.UserDefined.After;
4576 SCS.ReferenceBinding = true;
4577 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4578 SCS.BindsToRvalue = true;
4579 SCS.BindsToFunctionLvalue = false;
4580 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4581 SCS.ObjCLifetimeConversionBinding = false;
4582 } else
4583 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4584 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004585 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004586 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004587
4588 // C++11 [over.ics.list]p6:
4589 // Otherwise, if the parameter type is not a class:
4590 if (!ToType->isRecordType()) {
4591 // - if the initializer list has one element, the implicit conversion
4592 // sequence is the one required to convert the element to the
4593 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004594 unsigned NumInits = From->getNumInits();
4595 if (NumInits == 1)
4596 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4597 SuppressUserConversions,
4598 InOverloadResolution,
4599 AllowObjCWritebackConversion);
4600 // - if the initializer list has no elements, the implicit conversion
4601 // sequence is the identity conversion.
4602 else if (NumInits == 0) {
4603 Result.setStandard();
4604 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004605 Result.Standard.setFromType(ToType);
4606 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004607 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004608 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004609 return Result;
4610 }
4611
4612 // C++11 [over.ics.list]p7:
4613 // In all cases other than those enumerated above, no conversion is possible
4614 return Result;
4615}
4616
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004617/// TryCopyInitialization - Try to copy-initialize a value of type
4618/// ToType from the expression From. Return the implicit conversion
4619/// sequence required to pass this argument, which may be a bad
4620/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004621/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004622/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004623static ImplicitConversionSequence
4624TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004625 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004626 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004627 bool AllowObjCWritebackConversion,
4628 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004629 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4630 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4631 InOverloadResolution,AllowObjCWritebackConversion);
4632
Douglas Gregorabe183d2010-04-13 16:31:36 +00004633 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004634 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004635 /*FIXME:*/From->getLocStart(),
4636 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004637 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004638
John McCall120d63c2010-08-24 20:38:10 +00004639 return TryImplicitConversion(S, From, ToType,
4640 SuppressUserConversions,
4641 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004642 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004643 /*CStyle=*/false,
4644 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004645}
4646
Anna Zaksf3546ee2011-07-28 19:46:48 +00004647static bool TryCopyInitialization(const CanQualType FromQTy,
4648 const CanQualType ToQTy,
4649 Sema &S,
4650 SourceLocation Loc,
4651 ExprValueKind FromVK) {
4652 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4653 ImplicitConversionSequence ICS =
4654 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4655
4656 return !ICS.isBad();
4657}
4658
Douglas Gregor96176b32008-11-18 23:14:02 +00004659/// TryObjectArgumentInitialization - Try to initialize the object
4660/// parameter of the given member function (@c Method) from the
4661/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004662static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004663TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004664 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004665 CXXMethodDecl *Method,
4666 CXXRecordDecl *ActingContext) {
4667 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004668 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4669 // const volatile object.
4670 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4671 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004672 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004673
4674 // Set up the conversion sequence as a "bad" conversion, to allow us
4675 // to exit early.
4676 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004677
4678 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004679 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004680 FromType = PT->getPointeeType();
4681
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004682 // When we had a pointer, it's implicitly dereferenced, so we
4683 // better have an lvalue.
4684 assert(FromClassification.isLValue());
4685 }
4686
Anders Carlssona552f7c2009-05-01 18:34:30 +00004687 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004688
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004689 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004690 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004691 // parameter is
4692 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004693 // - "lvalue reference to cv X" for functions declared without a
4694 // ref-qualifier or with the & ref-qualifier
4695 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004696 // ref-qualifier
4697 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004698 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004699 // cv-qualification on the member function declaration.
4700 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004701 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004702 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004703 // (C++ [over.match.funcs]p5). We perform a simplified version of
4704 // reference binding here, that allows class rvalues to bind to
4705 // non-constant references.
4706
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004707 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004708 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004709 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004710 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004711 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004712 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004713 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004714 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004715 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004716
4717 // Check that we have either the same type or a derived type. It
4718 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004719 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004720 ImplicitConversionKind SecondKind;
4721 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4722 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004723 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004724 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004725 else {
John McCallb1bdc622010-02-25 01:37:24 +00004726 ICS.setBad(BadConversionSequence::unrelated_class,
4727 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004728 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004729 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004730
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004731 // Check the ref-qualifier.
4732 switch (Method->getRefQualifier()) {
4733 case RQ_None:
4734 // Do nothing; we don't care about lvalueness or rvalueness.
4735 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004737 case RQ_LValue:
4738 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4739 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004740 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004741 ImplicitParamType);
4742 return ICS;
4743 }
4744 break;
4745
4746 case RQ_RValue:
4747 if (!FromClassification.isRValue()) {
4748 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004749 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004750 ImplicitParamType);
4751 return ICS;
4752 }
4753 break;
4754 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004755
Douglas Gregor96176b32008-11-18 23:14:02 +00004756 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004757 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004758 ICS.Standard.setAsIdentityConversion();
4759 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004760 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004761 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004762 ICS.Standard.ReferenceBinding = true;
4763 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004764 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004765 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004766 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4767 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4768 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004769 return ICS;
4770}
4771
4772/// PerformObjectArgumentInitialization - Perform initialization of
4773/// the implicit object parameter for the given Method with the given
4774/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004775ExprResult
4776Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004777 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004778 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004779 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004780 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004781 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004782 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004783
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004784 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004785 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004786 FromRecordType = PT->getPointeeType();
4787 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004788 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004789 } else {
4790 FromRecordType = From->getType();
4791 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004792 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004793 }
4794
John McCall701c89e2009-12-03 04:06:58 +00004795 // Note that we always use the true parent context when performing
4796 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004797 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004798 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4799 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004800 if (ICS.isBad()) {
4801 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4802 Qualifiers FromQs = FromRecordType.getQualifiers();
4803 Qualifiers ToQs = DestType.getQualifiers();
4804 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4805 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004806 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004807 diag::err_member_function_call_bad_cvr)
4808 << Method->getDeclName() << FromRecordType << (CVR - 1)
4809 << From->getSourceRange();
4810 Diag(Method->getLocation(), diag::note_previous_decl)
4811 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004812 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004813 }
4814 }
4815
Daniel Dunbar96a00142012-03-09 18:35:03 +00004816 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004817 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004818 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004819 }
Mike Stump1eb44332009-09-09 15:08:12 +00004820
John Wiegley429bb272011-04-08 18:41:53 +00004821 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4822 ExprResult FromRes =
4823 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4824 if (FromRes.isInvalid())
4825 return ExprError();
4826 From = FromRes.take();
4827 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004828
Douglas Gregor5fccd362010-03-03 23:55:11 +00004829 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004830 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004831 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004832 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004833}
4834
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004835/// TryContextuallyConvertToBool - Attempt to contextually convert the
4836/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004837static ImplicitConversionSequence
4838TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004839 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004840 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004841 // FIXME: Are these flags correct?
4842 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004843 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004844 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004845 /*CStyle=*/false,
4846 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004847}
4848
4849/// PerformContextuallyConvertToBool - Perform a contextual conversion
4850/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004851ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004852 if (checkPlaceholderForOverload(*this, From))
4853 return ExprError();
4854
John McCall120d63c2010-08-24 20:38:10 +00004855 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004856 if (!ICS.isBad())
4857 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004858
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004859 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004860 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004861 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004862 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004863 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004864}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004865
Richard Smith8ef7b202012-01-18 23:55:52 +00004866/// Check that the specified conversion is permitted in a converted constant
4867/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4868/// is acceptable.
4869static bool CheckConvertedConstantConversions(Sema &S,
4870 StandardConversionSequence &SCS) {
4871 // Since we know that the target type is an integral or unscoped enumeration
4872 // type, most conversion kinds are impossible. All possible First and Third
4873 // conversions are fine.
4874 switch (SCS.Second) {
4875 case ICK_Identity:
4876 case ICK_Integral_Promotion:
4877 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004878 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004879 return true;
4880
4881 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004882 // Conversion from an integral or unscoped enumeration type to bool is
4883 // classified as ICK_Boolean_Conversion, but it's also an integral
4884 // conversion, so it's permitted in a converted constant expression.
4885 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4886 SCS.getToType(2)->isBooleanType();
4887
Richard Smith8ef7b202012-01-18 23:55:52 +00004888 case ICK_Floating_Integral:
4889 case ICK_Complex_Real:
4890 return false;
4891
4892 case ICK_Lvalue_To_Rvalue:
4893 case ICK_Array_To_Pointer:
4894 case ICK_Function_To_Pointer:
4895 case ICK_NoReturn_Adjustment:
4896 case ICK_Qualification:
4897 case ICK_Compatible_Conversion:
4898 case ICK_Vector_Conversion:
4899 case ICK_Vector_Splat:
4900 case ICK_Derived_To_Base:
4901 case ICK_Pointer_Conversion:
4902 case ICK_Pointer_Member:
4903 case ICK_Block_Pointer_Conversion:
4904 case ICK_Writeback_Conversion:
4905 case ICK_Floating_Promotion:
4906 case ICK_Complex_Promotion:
4907 case ICK_Complex_Conversion:
4908 case ICK_Floating_Conversion:
4909 case ICK_TransparentUnionConversion:
4910 llvm_unreachable("unexpected second conversion kind");
4911
4912 case ICK_Num_Conversion_Kinds:
4913 break;
4914 }
4915
4916 llvm_unreachable("unknown conversion kind");
4917}
4918
4919/// CheckConvertedConstantExpression - Check that the expression From is a
4920/// converted constant expression of type T, perform the conversion and produce
4921/// the converted expression, per C++11 [expr.const]p3.
4922ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4923 llvm::APSInt &Value,
4924 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004925 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004926 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4927
4928 if (checkPlaceholderForOverload(*this, From))
4929 return ExprError();
4930
4931 // C++11 [expr.const]p3 with proposed wording fixes:
4932 // A converted constant expression of type T is a core constant expression,
4933 // implicitly converted to a prvalue of type T, where the converted
4934 // expression is a literal constant expression and the implicit conversion
4935 // sequence contains only user-defined conversions, lvalue-to-rvalue
4936 // conversions, integral promotions, and integral conversions other than
4937 // narrowing conversions.
4938 ImplicitConversionSequence ICS =
4939 TryImplicitConversion(From, T,
4940 /*SuppressUserConversions=*/false,
4941 /*AllowExplicit=*/false,
4942 /*InOverloadResolution=*/false,
4943 /*CStyle=*/false,
4944 /*AllowObjcWritebackConversion=*/false);
4945 StandardConversionSequence *SCS = 0;
4946 switch (ICS.getKind()) {
4947 case ImplicitConversionSequence::StandardConversion:
4948 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004949 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004950 diag::err_typecheck_converted_constant_expression_disallowed)
4951 << From->getType() << From->getSourceRange() << T;
4952 SCS = &ICS.Standard;
4953 break;
4954 case ImplicitConversionSequence::UserDefinedConversion:
4955 // We are converting from class type to an integral or enumeration type, so
4956 // the Before sequence must be trivial.
4957 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004958 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004959 diag::err_typecheck_converted_constant_expression_disallowed)
4960 << From->getType() << From->getSourceRange() << T;
4961 SCS = &ICS.UserDefined.After;
4962 break;
4963 case ImplicitConversionSequence::AmbiguousConversion:
4964 case ImplicitConversionSequence::BadConversion:
4965 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004966 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004967 diag::err_typecheck_converted_constant_expression)
4968 << From->getType() << From->getSourceRange() << T;
4969 return ExprError();
4970
4971 case ImplicitConversionSequence::EllipsisConversion:
4972 llvm_unreachable("ellipsis conversion in converted constant expression");
4973 }
4974
4975 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4976 if (Result.isInvalid())
4977 return Result;
4978
4979 // Check for a narrowing implicit conversion.
4980 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004981 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004982 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4983 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004984 case NK_Variable_Narrowing:
4985 // Implicit conversion to a narrower type, and the value is not a constant
4986 // expression. We'll diagnose this in a moment.
4987 case NK_Not_Narrowing:
4988 break;
4989
4990 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004991 Diag(From->getLocStart(),
4992 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4993 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004994 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004995 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004996 break;
4997
4998 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004999 Diag(From->getLocStart(),
5000 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5001 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005002 << CCE << /*Constant*/0 << From->getType() << T;
5003 break;
5004 }
5005
5006 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005007 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005008 Expr::EvalResult Eval;
5009 Eval.Diag = &Notes;
5010
Douglas Gregor484f6fa2013-04-08 23:24:07 +00005011 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005012 // The expression can't be folded, so we can't keep it at this position in
5013 // the AST.
5014 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005015 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005016 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005017
5018 if (Notes.empty()) {
5019 // It's a constant expression.
5020 return Result;
5021 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005022 }
5023
5024 // It's not a constant expression. Produce an appropriate diagnostic.
5025 if (Notes.size() == 1 &&
5026 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5027 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5028 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005029 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005030 << CCE << From->getSourceRange();
5031 for (unsigned I = 0; I < Notes.size(); ++I)
5032 Diag(Notes[I].first, Notes[I].second);
5033 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005034 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005035}
5036
John McCall0bcc9bc2011-09-09 06:11:02 +00005037/// dropPointerConversions - If the given standard conversion sequence
5038/// involves any pointer conversions, remove them. This may change
5039/// the result type of the conversion sequence.
5040static void dropPointerConversion(StandardConversionSequence &SCS) {
5041 if (SCS.Second == ICK_Pointer_Conversion) {
5042 SCS.Second = ICK_Identity;
5043 SCS.Third = ICK_Identity;
5044 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5045 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005046}
John McCall120d63c2010-08-24 20:38:10 +00005047
John McCall0bcc9bc2011-09-09 06:11:02 +00005048/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5049/// convert the expression From to an Objective-C pointer type.
5050static ImplicitConversionSequence
5051TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5052 // Do an implicit conversion to 'id'.
5053 QualType Ty = S.Context.getObjCIdType();
5054 ImplicitConversionSequence ICS
5055 = TryImplicitConversion(S, From, Ty,
5056 // FIXME: Are these flags correct?
5057 /*SuppressUserConversions=*/false,
5058 /*AllowExplicit=*/true,
5059 /*InOverloadResolution=*/false,
5060 /*CStyle=*/false,
5061 /*AllowObjCWritebackConversion=*/false);
5062
5063 // Strip off any final conversions to 'id'.
5064 switch (ICS.getKind()) {
5065 case ImplicitConversionSequence::BadConversion:
5066 case ImplicitConversionSequence::AmbiguousConversion:
5067 case ImplicitConversionSequence::EllipsisConversion:
5068 break;
5069
5070 case ImplicitConversionSequence::UserDefinedConversion:
5071 dropPointerConversion(ICS.UserDefined.After);
5072 break;
5073
5074 case ImplicitConversionSequence::StandardConversion:
5075 dropPointerConversion(ICS.Standard);
5076 break;
5077 }
5078
5079 return ICS;
5080}
5081
5082/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5083/// conversion of the expression From to an Objective-C pointer type.
5084ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005085 if (checkPlaceholderForOverload(*this, From))
5086 return ExprError();
5087
John McCallc12c5bb2010-05-15 11:32:37 +00005088 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005089 ImplicitConversionSequence ICS =
5090 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005091 if (!ICS.isBad())
5092 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005093 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005094}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005095
Richard Smithf39aec12012-02-04 07:07:42 +00005096/// Determine whether the provided type is an integral type, or an enumeration
5097/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005098bool Sema::ICEConvertDiagnoser::match(QualType T) {
5099 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5100 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005101}
5102
Larisse Voufo50b60b32013-06-10 06:50:24 +00005103static ExprResult
5104diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5105 Sema::ContextualImplicitConverter &Converter,
5106 QualType T, UnresolvedSetImpl &ViableConversions) {
5107
5108 if (Converter.Suppress)
5109 return ExprError();
5110
5111 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5112 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5113 CXXConversionDecl *Conv =
5114 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5115 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5116 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5117 }
5118 return SemaRef.Owned(From);
5119}
5120
5121static bool
5122diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5123 Sema::ContextualImplicitConverter &Converter,
5124 QualType T, bool HadMultipleCandidates,
5125 UnresolvedSetImpl &ExplicitConversions) {
5126 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5127 DeclAccessPair Found = ExplicitConversions[0];
5128 CXXConversionDecl *Conversion =
5129 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5130
5131 // The user probably meant to invoke the given explicit
5132 // conversion; use it.
5133 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5134 std::string TypeStr;
5135 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5136
5137 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5138 << FixItHint::CreateInsertion(From->getLocStart(),
5139 "static_cast<" + TypeStr + ">(")
5140 << FixItHint::CreateInsertion(
5141 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5142 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5143
5144 // If we aren't in a SFINAE context, build a call to the
5145 // explicit conversion function.
5146 if (SemaRef.isSFINAEContext())
5147 return true;
5148
5149 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5150 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5151 HadMultipleCandidates);
5152 if (Result.isInvalid())
5153 return true;
5154 // Record usage of conversion in an implicit cast.
5155 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5156 CK_UserDefinedConversion, Result.get(), 0,
5157 Result.get()->getValueKind());
5158 }
5159 return false;
5160}
5161
5162static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5163 Sema::ContextualImplicitConverter &Converter,
5164 QualType T, bool HadMultipleCandidates,
5165 DeclAccessPair &Found) {
5166 CXXConversionDecl *Conversion =
5167 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5168 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5169
5170 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5171 if (!Converter.SuppressConversion) {
5172 if (SemaRef.isSFINAEContext())
5173 return true;
5174
5175 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5176 << From->getSourceRange();
5177 }
5178
5179 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5180 HadMultipleCandidates);
5181 if (Result.isInvalid())
5182 return true;
5183 // Record usage of conversion in an implicit cast.
5184 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5185 CK_UserDefinedConversion, Result.get(), 0,
5186 Result.get()->getValueKind());
5187 return false;
5188}
5189
5190static ExprResult finishContextualImplicitConversion(
5191 Sema &SemaRef, SourceLocation Loc, Expr *From,
5192 Sema::ContextualImplicitConverter &Converter) {
5193 if (!Converter.match(From->getType()) && !Converter.Suppress)
5194 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5195 << From->getSourceRange();
5196
5197 return SemaRef.DefaultLvalueConversion(From);
5198}
5199
5200static void
5201collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5202 UnresolvedSetImpl &ViableConversions,
5203 OverloadCandidateSet &CandidateSet) {
5204 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5205 DeclAccessPair FoundDecl = ViableConversions[I];
5206 NamedDecl *D = FoundDecl.getDecl();
5207 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5208 if (isa<UsingShadowDecl>(D))
5209 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5210
5211 CXXConversionDecl *Conv;
5212 FunctionTemplateDecl *ConvTemplate;
5213 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5214 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5215 else
5216 Conv = cast<CXXConversionDecl>(D);
5217
5218 if (ConvTemplate)
5219 SemaRef.AddTemplateConversionCandidate(
5220 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5221 else
5222 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5223 ToType, CandidateSet);
5224 }
5225}
5226
Richard Smith097e0a22013-05-21 19:05:48 +00005227/// \brief Attempt to convert the given expression to a type which is accepted
5228/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005229///
Richard Smith097e0a22013-05-21 19:05:48 +00005230/// This routine will attempt to convert an expression of class type to a
5231/// type accepted by the specified converter. In C++11 and before, the class
5232/// must have a single non-explicit conversion function converting to a matching
5233/// type. In C++1y, there can be multiple such conversion functions, but only
5234/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005235///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005236/// \param Loc The source location of the construct that requires the
5237/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005238///
James Dennett40ae6662012-06-22 08:52:37 +00005239/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005240///
Richard Smith097e0a22013-05-21 19:05:48 +00005241/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005242///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005243/// \returns The expression, converted to an integral or enumeration type if
5244/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005245ExprResult Sema::PerformContextualImplicitConversion(
5246 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005247 // We can't perform any more checking for type-dependent expressions.
5248 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005249 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005250
Eli Friedmanceccab92012-01-26 00:26:18 +00005251 // Process placeholders immediately.
5252 if (From->hasPlaceholderType()) {
5253 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005254 if (result.isInvalid())
5255 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005256 From = result.take();
5257 }
5258
Richard Smith097e0a22013-05-21 19:05:48 +00005259 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005260 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005261 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005262 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005263
5264 // FIXME: Check for missing '()' if T is a function type?
5265
Richard Smith097e0a22013-05-21 19:05:48 +00005266 // We can only perform contextual implicit conversions on objects of class
5267 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005268 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005269 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005270 if (!Converter.Suppress)
5271 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005272 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005273 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005274
Douglas Gregorc30614b2010-06-29 23:17:37 +00005275 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005276 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005277 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005278 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005279
5280 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5281 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5282
Douglas Gregord10099e2012-05-04 16:32:21 +00005283 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005284 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005285 }
Richard Smith097e0a22013-05-21 19:05:48 +00005286 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005287
5288 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005289 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005290
Douglas Gregorc30614b2010-06-29 23:17:37 +00005291 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005292 UnresolvedSet<4>
5293 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005294 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005295 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005296 CXXRecordDecl::conversion_iterator> Conversions =
5297 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005298
Larisse Voufo50b60b32013-06-10 06:50:24 +00005299 bool HadMultipleCandidates =
5300 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005301
Larisse Voufo50b60b32013-06-10 06:50:24 +00005302 // To check that there is only one target type, in C++1y:
5303 QualType ToType;
5304 bool HasUniqueTargetType = true;
5305
5306 // Collect explicit or viable (potentially in C++1y) conversions.
5307 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5308 E = Conversions.second;
5309 I != E; ++I) {
5310 NamedDecl *D = (*I)->getUnderlyingDecl();
5311 CXXConversionDecl *Conversion;
5312 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5313 if (ConvTemplate) {
5314 if (getLangOpts().CPlusPlus1y)
5315 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5316 else
5317 continue; // C++11 does not consider conversion operator templates(?).
5318 } else
5319 Conversion = cast<CXXConversionDecl>(D);
5320
5321 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5322 "Conversion operator templates are considered potentially "
5323 "viable in C++1y");
5324
5325 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5326 if (Converter.match(CurToType) || ConvTemplate) {
5327
5328 if (Conversion->isExplicit()) {
5329 // FIXME: For C++1y, do we need this restriction?
5330 // cf. diagnoseNoViableConversion()
5331 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005332 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005333 } else {
5334 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5335 if (ToType.isNull())
5336 ToType = CurToType.getUnqualifiedType();
5337 else if (HasUniqueTargetType &&
5338 (CurToType.getUnqualifiedType() != ToType))
5339 HasUniqueTargetType = false;
5340 }
5341 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005342 }
Richard Smithf39aec12012-02-04 07:07:42 +00005343 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005345
Larisse Voufo50b60b32013-06-10 06:50:24 +00005346 if (getLangOpts().CPlusPlus1y) {
5347 // C++1y [conv]p6:
5348 // ... An expression e of class type E appearing in such a context
5349 // is said to be contextually implicitly converted to a specified
5350 // type T and is well-formed if and only if e can be implicitly
5351 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005352 // for conversion functions whose return type is cv T or reference to
5353 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005354 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005355
Larisse Voufo50b60b32013-06-10 06:50:24 +00005356 // If no unique T is found:
5357 if (ToType.isNull()) {
5358 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5359 HadMultipleCandidates,
5360 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005361 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005362 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005363 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005364
Larisse Voufo50b60b32013-06-10 06:50:24 +00005365 // If more than one unique Ts are found:
5366 if (!HasUniqueTargetType)
5367 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5368 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005369
Larisse Voufo50b60b32013-06-10 06:50:24 +00005370 // If one unique T is found:
5371 // First, build a candidate set from the previously recorded
5372 // potentially viable conversions.
5373 OverloadCandidateSet CandidateSet(Loc);
5374 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5375 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005376
Larisse Voufo50b60b32013-06-10 06:50:24 +00005377 // Then, perform overload resolution over the candidate set.
5378 OverloadCandidateSet::iterator Best;
5379 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5380 case OR_Success: {
5381 // Apply this conversion.
5382 DeclAccessPair Found =
5383 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5384 if (recordConversion(*this, Loc, From, Converter, T,
5385 HadMultipleCandidates, Found))
5386 return ExprError();
5387 break;
5388 }
5389 case OR_Ambiguous:
5390 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5391 ViableConversions);
5392 case OR_No_Viable_Function:
5393 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5394 HadMultipleCandidates,
5395 ExplicitConversions))
5396 return ExprError();
5397 // fall through 'OR_Deleted' case.
5398 case OR_Deleted:
5399 // We'll complain below about a non-integral condition type.
5400 break;
5401 }
5402 } else {
5403 switch (ViableConversions.size()) {
5404 case 0: {
5405 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5406 HadMultipleCandidates,
5407 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005408 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005409
Larisse Voufo50b60b32013-06-10 06:50:24 +00005410 // We'll complain below about a non-integral condition type.
5411 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005412 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005413 case 1: {
5414 // Apply this conversion.
5415 DeclAccessPair Found = ViableConversions[0];
5416 if (recordConversion(*this, Loc, From, Converter, T,
5417 HadMultipleCandidates, Found))
5418 return ExprError();
5419 break;
5420 }
5421 default:
5422 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5423 ViableConversions);
5424 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005425 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005426
Larisse Voufo50b60b32013-06-10 06:50:24 +00005427 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005428}
5429
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005430/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005431/// candidate functions, using the given function call arguments. If
5432/// @p SuppressUserConversions, then don't allow user-defined
5433/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005434///
James Dennett699c9042012-06-15 07:13:21 +00005435/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005436/// based on an incomplete set of function arguments. This feature is used by
5437/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005438void
5439Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005440 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005441 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005442 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005443 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005444 bool PartialOverloading,
5445 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005446 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005447 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005448 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005449 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005450 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005451
Douglas Gregor88a35142008-12-22 05:46:06 +00005452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005453 if (!isa<CXXConstructorDecl>(Method)) {
5454 // If we get here, it's because we're calling a member function
5455 // that is named without a member access expression (e.g.,
5456 // "this->f") that was either written explicitly or created
5457 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005458 // function, e.g., X::f(). We use an empty type for the implied
5459 // object argument (C++ [over.call.func]p3), and the acting context
5460 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005461 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005462 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005463 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005464 return;
5465 }
5466 // We treat a constructor like a non-member function, since its object
5467 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005468 }
5469
Douglas Gregorfd476482009-11-13 23:59:09 +00005470 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005471 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005472
Douglas Gregor7edfb692009-11-23 12:27:39 +00005473 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005474 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005475
Douglas Gregor66724ea2009-11-14 01:20:54 +00005476 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5477 // C++ [class.copy]p3:
5478 // A member function template is never instantiated to perform the copy
5479 // of a class object to an object of its class type.
5480 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005481 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005482 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005483 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5484 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005485 return;
5486 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005487
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005488 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005489 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005490 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005491 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005492 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005493 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005494 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005495 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005496
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005497 unsigned NumArgsInProto = Proto->getNumArgs();
5498
5499 // (C++ 13.3.2p2): A candidate function having fewer than m
5500 // parameters is viable only if it has an ellipsis in its parameter
5501 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005502 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005503 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005504 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005505 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005506 return;
5507 }
5508
5509 // (C++ 13.3.2p2): A candidate function having more than m parameters
5510 // is viable only if the (m+1)st parameter has a default argument
5511 // (8.3.6). For the purposes of overload resolution, the
5512 // parameter list is truncated on the right, so that there are
5513 // exactly m parameters.
5514 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005515 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005516 // Not enough arguments.
5517 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005518 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005519 return;
5520 }
5521
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005522 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005523 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005524 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5525 if (CheckCUDATarget(Caller, Function)) {
5526 Candidate.Viable = false;
5527 Candidate.FailureKind = ovl_fail_bad_target;
5528 return;
5529 }
5530
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005531 // Determine the implicit conversion sequences for each of the
5532 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005533 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005534 if (ArgIdx < NumArgsInProto) {
5535 // (C++ 13.3.2p3): for F to be a viable function, there shall
5536 // exist for each argument an implicit conversion sequence
5537 // (13.3.3.1) that converts that argument to the corresponding
5538 // parameter of F.
5539 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005540 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005541 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005542 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005543 /*InOverloadResolution=*/true,
5544 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005545 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005546 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005547 if (Candidate.Conversions[ArgIdx].isBad()) {
5548 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005549 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005550 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005551 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005552 } else {
5553 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5554 // argument for which there is no corresponding parameter is
5555 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005556 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005557 }
5558 }
5559}
5560
Douglas Gregor063daf62009-03-13 18:40:31 +00005561/// \brief Add all of the function declarations in the given function set to
5562/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005563void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005564 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005565 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005566 bool SuppressUserConversions,
5567 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005568 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005569 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5570 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005571 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005572 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005573 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005574 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005575 Args.slice(1), CandidateSet,
5576 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005577 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005578 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005579 SuppressUserConversions);
5580 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005581 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005582 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5583 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005584 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005585 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005586 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005587 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005588 Args[0]->Classify(Context), Args.slice(1),
5589 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005590 else
John McCall9aa472c2010-03-19 07:35:19 +00005591 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005592 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005593 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005594 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005595 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005596}
5597
John McCall314be4e2009-11-17 07:50:12 +00005598/// AddMethodCandidate - Adds a named decl (which is some kind of
5599/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005600void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005601 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005602 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005603 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005604 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005605 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005606 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005607 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005608
5609 if (isa<UsingShadowDecl>(Decl))
5610 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005611
John McCall314be4e2009-11-17 07:50:12 +00005612 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5613 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5614 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005615 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5616 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005617 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005618 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005619 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005620 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005621 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005622 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005623 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005624 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005625 }
5626}
5627
Douglas Gregor96176b32008-11-18 23:14:02 +00005628/// AddMethodCandidate - Adds the given C++ member function to the set
5629/// of candidate functions, using the given function call arguments
5630/// and the object argument (@c Object). For example, in a call
5631/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5632/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5633/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005634/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005635void
John McCall9aa472c2010-03-19 07:35:19 +00005636Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005637 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005638 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005639 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005640 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005641 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005642 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005643 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005644 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005645 assert(!isa<CXXConstructorDecl>(Method) &&
5646 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005647
Douglas Gregor3f396022009-09-28 04:47:19 +00005648 if (!CandidateSet.isNewCandidate(Method))
5649 return;
5650
Douglas Gregor7edfb692009-11-23 12:27:39 +00005651 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005652 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005653
Douglas Gregor96176b32008-11-18 23:14:02 +00005654 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005655 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005656 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005657 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005658 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005659 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005660 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005661
5662 unsigned NumArgsInProto = Proto->getNumArgs();
5663
5664 // (C++ 13.3.2p2): A candidate function having fewer than m
5665 // parameters is viable only if it has an ellipsis in its parameter
5666 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005667 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005668 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005669 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005670 return;
5671 }
5672
5673 // (C++ 13.3.2p2): A candidate function having more than m parameters
5674 // is viable only if the (m+1)st parameter has a default argument
5675 // (8.3.6). For the purposes of overload resolution, the
5676 // parameter list is truncated on the right, so that there are
5677 // exactly m parameters.
5678 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005679 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005680 // Not enough arguments.
5681 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005682 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005683 return;
5684 }
5685
5686 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005687
John McCall701c89e2009-12-03 04:06:58 +00005688 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005689 // The implicit object argument is ignored.
5690 Candidate.IgnoreObjectArgument = true;
5691 else {
5692 // Determine the implicit conversion sequence for the object
5693 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005694 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005695 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5696 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005697 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005698 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005699 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005700 return;
5701 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005702 }
5703
5704 // Determine the implicit conversion sequences for each of the
5705 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005706 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005707 if (ArgIdx < NumArgsInProto) {
5708 // (C++ 13.3.2p3): for F to be a viable function, there shall
5709 // exist for each argument an implicit conversion sequence
5710 // (13.3.3.1) that converts that argument to the corresponding
5711 // parameter of F.
5712 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005713 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005714 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005715 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005716 /*InOverloadResolution=*/true,
5717 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005718 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005719 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005720 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005721 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005722 break;
5723 }
5724 } else {
5725 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5726 // argument for which there is no corresponding parameter is
5727 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005728 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005729 }
5730 }
5731}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005732
Douglas Gregor6b906862009-08-21 00:16:32 +00005733/// \brief Add a C++ member function template as a candidate to the candidate
5734/// set, using template argument deduction to produce an appropriate member
5735/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005736void
Douglas Gregor6b906862009-08-21 00:16:32 +00005737Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005738 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005739 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005740 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005741 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005742 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005743 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005744 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005745 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005746 if (!CandidateSet.isNewCandidate(MethodTmpl))
5747 return;
5748
Douglas Gregor6b906862009-08-21 00:16:32 +00005749 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005750 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005751 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005752 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005753 // candidate functions in the usual way.113) A given name can refer to one
5754 // or more function templates and also to a set of overloaded non-template
5755 // functions. In such a case, the candidate functions generated from each
5756 // function template are combined with the set of non-template candidate
5757 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005758 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005759 FunctionDecl *Specialization = 0;
5760 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005761 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5762 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005763 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005764 Candidate.FoundDecl = FoundDecl;
5765 Candidate.Function = MethodTmpl->getTemplatedDecl();
5766 Candidate.Viable = false;
5767 Candidate.FailureKind = ovl_fail_bad_deduction;
5768 Candidate.IsSurrogate = false;
5769 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005770 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005771 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005772 Info);
5773 return;
5774 }
Mike Stump1eb44332009-09-09 15:08:12 +00005775
Douglas Gregor6b906862009-08-21 00:16:32 +00005776 // Add the function template specialization produced by template argument
5777 // deduction as a candidate.
5778 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005779 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005780 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005781 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005782 ActingContext, ObjectType, ObjectClassification, Args,
5783 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005784}
5785
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005786/// \brief Add a C++ function template specialization as a candidate
5787/// in the candidate set, using template argument deduction to produce
5788/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005789void
Douglas Gregore53060f2009-06-25 22:08:12 +00005790Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005791 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005792 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005793 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005794 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005795 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005796 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5797 return;
5798
Douglas Gregore53060f2009-06-25 22:08:12 +00005799 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005800 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005801 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005802 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005803 // candidate functions in the usual way.113) A given name can refer to one
5804 // or more function templates and also to a set of overloaded non-template
5805 // functions. In such a case, the candidate functions generated from each
5806 // function template are combined with the set of non-template candidate
5807 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005808 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005809 FunctionDecl *Specialization = 0;
5810 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005811 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5812 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005813 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005814 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005815 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5816 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005817 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005818 Candidate.IsSurrogate = false;
5819 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005820 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005821 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005822 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005823 return;
5824 }
Mike Stump1eb44332009-09-09 15:08:12 +00005825
Douglas Gregore53060f2009-06-25 22:08:12 +00005826 // Add the function template specialization produced by template argument
5827 // deduction as a candidate.
5828 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005829 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005830 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005831}
Mike Stump1eb44332009-09-09 15:08:12 +00005832
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005833/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005834/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005835/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005836/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005837/// (which may or may not be the same type as the type that the
5838/// conversion function produces).
5839void
5840Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005841 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005842 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005843 Expr *From, QualType ToType,
5844 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005845 assert(!Conversion->getDescribedFunctionTemplate() &&
5846 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005847 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005848 if (!CandidateSet.isNewCandidate(Conversion))
5849 return;
5850
Richard Smith60e141e2013-05-04 07:00:32 +00005851 // If the conversion function has an undeduced return type, trigger its
5852 // deduction now.
5853 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5854 if (DeduceReturnType(Conversion, From->getExprLoc()))
5855 return;
5856 ConvType = Conversion->getConversionType().getNonReferenceType();
5857 }
5858
Douglas Gregor7edfb692009-11-23 12:27:39 +00005859 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005860 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005861
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005862 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005863 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005864 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005865 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005866 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005867 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005868 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005869 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005870 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005871 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005872 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005873
Douglas Gregorbca39322010-08-19 15:37:02 +00005874 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005875 // For conversion functions, the function is considered to be a member of
5876 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005877 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005878 //
5879 // Determine the implicit conversion sequence for the implicit
5880 // object parameter.
5881 QualType ImplicitParamType = From->getType();
5882 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5883 ImplicitParamType = FromPtrType->getPointeeType();
5884 CXXRecordDecl *ConversionContext
5885 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005886
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005887 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005888 = TryObjectArgumentInitialization(*this, From->getType(),
5889 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005890 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005891
John McCall1d318332010-01-12 00:44:57 +00005892 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005893 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005894 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005895 return;
5896 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005897
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005898 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005899 // derived to base as such conversions are given Conversion Rank. They only
5900 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5901 QualType FromCanon
5902 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5903 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5904 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5905 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005906 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005907 return;
5908 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005909
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005910 // To determine what the conversion from the result of calling the
5911 // conversion function to the type we're eventually trying to
5912 // convert to (ToType), we need to synthesize a call to the
5913 // conversion function and attempt copy initialization from it. This
5914 // makes sure that we get the right semantics with respect to
5915 // lvalues/rvalues and the type. Fortunately, we can allocate this
5916 // call on the stack and we don't need its arguments to be
5917 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005918 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005919 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005920 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5921 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005922 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005923 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005924
Richard Smith87c1f1f2011-07-13 22:53:21 +00005925 QualType ConversionType = Conversion->getConversionType();
5926 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005927 Candidate.Viable = false;
5928 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5929 return;
5930 }
5931
Richard Smith87c1f1f2011-07-13 22:53:21 +00005932 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005933
Mike Stump1eb44332009-09-09 15:08:12 +00005934 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005935 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5936 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005937 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005938 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005939 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005940 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005941 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005942 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005943 /*InOverloadResolution=*/false,
5944 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005945
John McCall1d318332010-01-12 00:44:57 +00005946 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005947 case ImplicitConversionSequence::StandardConversion:
5948 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005949
Douglas Gregorc520c842010-04-12 23:42:09 +00005950 // C++ [over.ics.user]p3:
5951 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005953 // shall have exact match rank.
5954 if (Conversion->getPrimaryTemplate() &&
5955 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5956 Candidate.Viable = false;
5957 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5958 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005959
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005960 // C++0x [dcl.init.ref]p5:
5961 // In the second case, if the reference is an rvalue reference and
5962 // the second standard conversion sequence of the user-defined
5963 // conversion sequence includes an lvalue-to-rvalue conversion, the
5964 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005965 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005966 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5967 Candidate.Viable = false;
5968 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5969 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005970 break;
5971
5972 case ImplicitConversionSequence::BadConversion:
5973 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005974 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005975 break;
5976
5977 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005978 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005979 "Can only end up with a standard conversion sequence or failure");
5980 }
5981}
5982
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005983/// \brief Adds a conversion function template specialization
5984/// candidate to the overload set, using template argument deduction
5985/// to deduce the template arguments of the conversion function
5986/// template from the type that we are converting to (C++
5987/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005988void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005989Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005990 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005991 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005992 Expr *From, QualType ToType,
5993 OverloadCandidateSet &CandidateSet) {
5994 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5995 "Only conversion function templates permitted here");
5996
Douglas Gregor3f396022009-09-28 04:47:19 +00005997 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5998 return;
5999
Craig Topper93e45992012-09-19 02:26:47 +00006000 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006001 CXXConversionDecl *Specialization = 0;
6002 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00006003 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006004 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006005 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00006006 Candidate.FoundDecl = FoundDecl;
6007 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6008 Candidate.Viable = false;
6009 Candidate.FailureKind = ovl_fail_bad_deduction;
6010 Candidate.IsSurrogate = false;
6011 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006012 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006013 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00006014 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006015 return;
6016 }
Mike Stump1eb44332009-09-09 15:08:12 +00006017
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006018 // Add the conversion function template specialization produced by
6019 // template argument deduction as a candidate.
6020 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00006021 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00006022 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006023}
6024
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006025/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6026/// converts the given @c Object to a function pointer via the
6027/// conversion function @c Conversion, and then attempts to call it
6028/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6029/// the type of function that we'll eventually be calling.
6030void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006031 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006032 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006033 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006034 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006035 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006036 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006037 if (!CandidateSet.isNewCandidate(Conversion))
6038 return;
6039
Douglas Gregor7edfb692009-11-23 12:27:39 +00006040 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006041 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006042
Ahmed Charles13a140c2012-02-25 11:00:22 +00006043 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006044 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006045 Candidate.Function = 0;
6046 Candidate.Surrogate = Conversion;
6047 Candidate.Viable = true;
6048 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006049 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006050 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006051
6052 // Determine the implicit conversion sequence for the implicit
6053 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006054 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006055 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006056 Object->Classify(Context),
6057 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006058 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006059 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006060 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006061 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006062 return;
6063 }
6064
6065 // The first conversion is actually a user-defined conversion whose
6066 // first conversion is ObjectInit's standard conversion (which is
6067 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006068 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006069 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006070 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006071 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006072 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006073 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006074 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006075 = Candidate.Conversions[0].UserDefined.Before;
6076 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6077
Mike Stump1eb44332009-09-09 15:08:12 +00006078 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006079 unsigned NumArgsInProto = Proto->getNumArgs();
6080
6081 // (C++ 13.3.2p2): A candidate function having fewer than m
6082 // parameters is viable only if it has an ellipsis in its parameter
6083 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006084 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006085 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006086 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006087 return;
6088 }
6089
6090 // Function types don't have any default arguments, so just check if
6091 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006092 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006093 // Not enough arguments.
6094 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006095 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006096 return;
6097 }
6098
6099 // Determine the implicit conversion sequences for each of the
6100 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006101 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006102 if (ArgIdx < NumArgsInProto) {
6103 // (C++ 13.3.2p3): for F to be a viable function, there shall
6104 // exist for each argument an implicit conversion sequence
6105 // (13.3.3.1) that converts that argument to the corresponding
6106 // parameter of F.
6107 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006108 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006109 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006110 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006111 /*InOverloadResolution=*/false,
6112 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006113 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006114 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006115 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006116 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006117 break;
6118 }
6119 } else {
6120 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6121 // argument for which there is no corresponding parameter is
6122 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006123 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006124 }
6125 }
6126}
6127
Douglas Gregor063daf62009-03-13 18:40:31 +00006128/// \brief Add overload candidates for overloaded operators that are
6129/// member functions.
6130///
6131/// Add the overloaded operator candidates that are member functions
6132/// for the operator Op that was used in an operator expression such
6133/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6134/// CandidateSet will store the added overload candidates. (C++
6135/// [over.match.oper]).
6136void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6137 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006138 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006139 OverloadCandidateSet& CandidateSet,
6140 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006141 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6142
6143 // C++ [over.match.oper]p3:
6144 // For a unary operator @ with an operand of a type whose
6145 // cv-unqualified version is T1, and for a binary operator @ with
6146 // a left operand of a type whose cv-unqualified version is T1 and
6147 // a right operand of a type whose cv-unqualified version is T2,
6148 // three sets of candidate functions, designated member
6149 // candidates, non-member candidates and built-in candidates, are
6150 // constructed as follows:
6151 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006152
Richard Smithe410be92013-04-20 12:41:22 +00006153 // -- If T1 is a complete class type or a class currently being
6154 // defined, the set of member candidates is the result of the
6155 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6156 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006157 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006158 // Complete the type if it can be completed.
6159 RequireCompleteType(OpLoc, T1, 0);
6160 // If the type is neither complete nor being defined, bail out now.
6161 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006162 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006163
John McCalla24dc2e2009-11-17 02:14:36 +00006164 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6165 LookupQualifiedName(Operators, T1Rec->getDecl());
6166 Operators.suppressDiagnostics();
6167
Mike Stump1eb44332009-09-09 15:08:12 +00006168 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006169 OperEnd = Operators.end();
6170 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006171 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006172 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006173 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006174 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006175 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006176 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006177 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006178}
6179
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006180/// AddBuiltinCandidate - Add a candidate for a built-in
6181/// operator. ResultTy and ParamTys are the result and parameter types
6182/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006183/// arguments being passed to the candidate. IsAssignmentOperator
6184/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006185/// operator. NumContextualBoolArguments is the number of arguments
6186/// (at the beginning of the argument list) that will be contextually
6187/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006188void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006189 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006190 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006191 bool IsAssignmentOperator,
6192 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006193 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006194 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006195
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006196 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006197 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006198 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006199 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006200 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006201 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006202 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006203 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006204 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6205
6206 // Determine the implicit conversion sequences for each of the
6207 // arguments.
6208 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006209 Candidate.ExplicitCallArguments = Args.size();
6210 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006211 // C++ [over.match.oper]p4:
6212 // For the built-in assignment operators, conversions of the
6213 // left operand are restricted as follows:
6214 // -- no temporaries are introduced to hold the left operand, and
6215 // -- no user-defined conversions are applied to the left
6216 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006217 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006218 //
6219 // We block these conversions by turning off user-defined
6220 // conversions, since that is the only way that initialization of
6221 // a reference to a non-class type can occur from something that
6222 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006223 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006224 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006225 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006226 Candidate.Conversions[ArgIdx]
6227 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006228 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006229 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006230 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006231 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006232 /*InOverloadResolution=*/false,
6233 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006234 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006235 }
John McCall1d318332010-01-12 00:44:57 +00006236 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006237 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006238 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006239 break;
6240 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006241 }
6242}
6243
6244/// BuiltinCandidateTypeSet - A set of types that will be used for the
6245/// candidate operator functions for built-in operators (C++
6246/// [over.built]). The types are separated into pointer types and
6247/// enumeration types.
6248class BuiltinCandidateTypeSet {
6249 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006250 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006251
6252 /// PointerTypes - The set of pointer types that will be used in the
6253 /// built-in candidates.
6254 TypeSet PointerTypes;
6255
Sebastian Redl78eb8742009-04-19 21:53:20 +00006256 /// MemberPointerTypes - The set of member pointer types that will be
6257 /// used in the built-in candidates.
6258 TypeSet MemberPointerTypes;
6259
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006260 /// EnumerationTypes - The set of enumeration types that will be
6261 /// used in the built-in candidates.
6262 TypeSet EnumerationTypes;
6263
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006264 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006265 /// candidates.
6266 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006267
6268 /// \brief A flag indicating non-record types are viable candidates
6269 bool HasNonRecordTypes;
6270
6271 /// \brief A flag indicating whether either arithmetic or enumeration types
6272 /// were present in the candidate set.
6273 bool HasArithmeticOrEnumeralTypes;
6274
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006275 /// \brief A flag indicating whether the nullptr type was present in the
6276 /// candidate set.
6277 bool HasNullPtrType;
6278
Douglas Gregor5842ba92009-08-24 15:23:48 +00006279 /// Sema - The semantic analysis instance where we are building the
6280 /// candidate type set.
6281 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006282
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006283 /// Context - The AST context in which we will build the type sets.
6284 ASTContext &Context;
6285
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006286 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6287 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006288 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006289
6290public:
6291 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006292 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006293
Mike Stump1eb44332009-09-09 15:08:12 +00006294 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006295 : HasNonRecordTypes(false),
6296 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006297 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006298 SemaRef(SemaRef),
6299 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006300
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006301 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006302 SourceLocation Loc,
6303 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006304 bool AllowExplicitConversions,
6305 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006306
6307 /// pointer_begin - First pointer type found;
6308 iterator pointer_begin() { return PointerTypes.begin(); }
6309
Sebastian Redl78eb8742009-04-19 21:53:20 +00006310 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006311 iterator pointer_end() { return PointerTypes.end(); }
6312
Sebastian Redl78eb8742009-04-19 21:53:20 +00006313 /// member_pointer_begin - First member pointer type found;
6314 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6315
6316 /// member_pointer_end - Past the last member pointer type found;
6317 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6318
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006319 /// enumeration_begin - First enumeration type found;
6320 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6321
Sebastian Redl78eb8742009-04-19 21:53:20 +00006322 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006323 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006324
Douglas Gregor26bcf672010-05-19 03:21:00 +00006325 iterator vector_begin() { return VectorTypes.begin(); }
6326 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006327
6328 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6329 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006330 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006331};
6332
Sebastian Redl78eb8742009-04-19 21:53:20 +00006333/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006334/// the set of pointer types along with any more-qualified variants of
6335/// that type. For example, if @p Ty is "int const *", this routine
6336/// will add "int const *", "int const volatile *", "int const
6337/// restrict *", and "int const volatile restrict *" to the set of
6338/// pointer types. Returns true if the add of @p Ty itself succeeded,
6339/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006340///
6341/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006342bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006343BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6344 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006345
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006346 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006347 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006348 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006349
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006350 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006351 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006352 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006353 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006354 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6355 PointeeTy = PTy->getPointeeType();
6356 buildObjCPtr = true;
6357 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006358 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006359 }
6360
Sebastian Redla9efada2009-11-18 20:39:26 +00006361 // Don't add qualified variants of arrays. For one, they're not allowed
6362 // (the qualifier would sink to the element type), and for another, the
6363 // only overload situation where it matters is subscript or pointer +- int,
6364 // and those shouldn't have qualifier variants anyway.
6365 if (PointeeTy->isArrayType())
6366 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006367
John McCall0953e762009-09-24 19:53:00 +00006368 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006369 bool hasVolatile = VisibleQuals.hasVolatile();
6370 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006371
John McCall0953e762009-09-24 19:53:00 +00006372 // Iterate through all strict supersets of BaseCVR.
6373 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6374 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006375 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006376 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006377
6378 // Skip over restrict if no restrict found anywhere in the types, or if
6379 // the type cannot be restrict-qualified.
6380 if ((CVR & Qualifiers::Restrict) &&
6381 (!hasRestrict ||
6382 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6383 continue;
6384
6385 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006386 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006387
6388 // Build qualified pointer type.
6389 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006390 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006391 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006392 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006393 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6394
6395 // Insert qualified pointer type.
6396 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006397 }
6398
6399 return true;
6400}
6401
Sebastian Redl78eb8742009-04-19 21:53:20 +00006402/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6403/// to the set of pointer types along with any more-qualified variants of
6404/// that type. For example, if @p Ty is "int const *", this routine
6405/// will add "int const *", "int const volatile *", "int const
6406/// restrict *", and "int const volatile restrict *" to the set of
6407/// pointer types. Returns true if the add of @p Ty itself succeeded,
6408/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006409///
6410/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006411bool
6412BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6413 QualType Ty) {
6414 // Insert this type.
6415 if (!MemberPointerTypes.insert(Ty))
6416 return false;
6417
John McCall0953e762009-09-24 19:53:00 +00006418 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6419 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006420
John McCall0953e762009-09-24 19:53:00 +00006421 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006422 // Don't add qualified variants of arrays. For one, they're not allowed
6423 // (the qualifier would sink to the element type), and for another, the
6424 // only overload situation where it matters is subscript or pointer +- int,
6425 // and those shouldn't have qualifier variants anyway.
6426 if (PointeeTy->isArrayType())
6427 return true;
John McCall0953e762009-09-24 19:53:00 +00006428 const Type *ClassTy = PointerTy->getClass();
6429
6430 // Iterate through all strict supersets of the pointee type's CVR
6431 // qualifiers.
6432 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6433 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6434 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006435
John McCall0953e762009-09-24 19:53:00 +00006436 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006437 MemberPointerTypes.insert(
6438 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006439 }
6440
6441 return true;
6442}
6443
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006444/// AddTypesConvertedFrom - Add each of the types to which the type @p
6445/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006446/// primarily interested in pointer types and enumeration types. We also
6447/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006448/// AllowUserConversions is true if we should look at the conversion
6449/// functions of a class type, and AllowExplicitConversions if we
6450/// should also include the explicit conversion functions of a class
6451/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006452void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006453BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006454 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006455 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006456 bool AllowExplicitConversions,
6457 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006458 // Only deal with canonical types.
6459 Ty = Context.getCanonicalType(Ty);
6460
6461 // Look through reference types; they aren't part of the type of an
6462 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006463 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006464 Ty = RefTy->getPointeeType();
6465
John McCall3b657512011-01-19 10:06:00 +00006466 // If we're dealing with an array type, decay to the pointer.
6467 if (Ty->isArrayType())
6468 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6469
6470 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006471 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006472
Chandler Carruth6a577462010-12-13 01:44:01 +00006473 // Flag if we ever add a non-record type.
6474 const RecordType *TyRec = Ty->getAs<RecordType>();
6475 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6476
Chandler Carruth6a577462010-12-13 01:44:01 +00006477 // Flag if we encounter an arithmetic type.
6478 HasArithmeticOrEnumeralTypes =
6479 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6480
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006481 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6482 PointerTypes.insert(Ty);
6483 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006484 // Insert our type, and its more-qualified variants, into the set
6485 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006486 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006487 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006488 } else if (Ty->isMemberPointerType()) {
6489 // Member pointers are far easier, since the pointee can't be converted.
6490 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6491 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006492 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006493 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006494 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006495 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006496 // We treat vector types as arithmetic types in many contexts as an
6497 // extension.
6498 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006499 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006500 } else if (Ty->isNullPtrType()) {
6501 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006502 } else if (AllowUserConversions && TyRec) {
6503 // No conversion functions in incomplete types.
6504 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6505 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006506
Chandler Carruth6a577462010-12-13 01:44:01 +00006507 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006508 std::pair<CXXRecordDecl::conversion_iterator,
6509 CXXRecordDecl::conversion_iterator>
6510 Conversions = ClassDecl->getVisibleConversionFunctions();
6511 for (CXXRecordDecl::conversion_iterator
6512 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006513 NamedDecl *D = I.getDecl();
6514 if (isa<UsingShadowDecl>(D))
6515 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006516
Chandler Carruth6a577462010-12-13 01:44:01 +00006517 // Skip conversion function templates; they don't tell us anything
6518 // about which builtin types we can convert to.
6519 if (isa<FunctionTemplateDecl>(D))
6520 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006521
Chandler Carruth6a577462010-12-13 01:44:01 +00006522 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6523 if (AllowExplicitConversions || !Conv->isExplicit()) {
6524 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6525 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006526 }
6527 }
6528 }
6529}
6530
Douglas Gregor19b7b152009-08-24 13:43:27 +00006531/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6532/// the volatile- and non-volatile-qualified assignment operators for the
6533/// given type to the candidate set.
6534static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6535 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006536 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006537 OverloadCandidateSet &CandidateSet) {
6538 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006539
Douglas Gregor19b7b152009-08-24 13:43:27 +00006540 // T& operator=(T&, T)
6541 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6542 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006543 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006544 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006545
Douglas Gregor19b7b152009-08-24 13:43:27 +00006546 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6547 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006548 ParamTypes[0]
6549 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006550 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006551 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006552 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006553 }
6554}
Mike Stump1eb44332009-09-09 15:08:12 +00006555
Sebastian Redl9994a342009-10-25 17:03:50 +00006556/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6557/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006558static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6559 Qualifiers VRQuals;
6560 const RecordType *TyRec;
6561 if (const MemberPointerType *RHSMPType =
6562 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006563 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006564 else
6565 TyRec = ArgExpr->getType()->getAs<RecordType>();
6566 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006567 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006568 VRQuals.addVolatile();
6569 VRQuals.addRestrict();
6570 return VRQuals;
6571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006572
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006573 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006574 if (!ClassDecl->hasDefinition())
6575 return VRQuals;
6576
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006577 std::pair<CXXRecordDecl::conversion_iterator,
6578 CXXRecordDecl::conversion_iterator>
6579 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006580
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006581 for (CXXRecordDecl::conversion_iterator
6582 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006583 NamedDecl *D = I.getDecl();
6584 if (isa<UsingShadowDecl>(D))
6585 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6586 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006587 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6588 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6589 CanTy = ResTypeRef->getPointeeType();
6590 // Need to go down the pointer/mempointer chain and add qualifiers
6591 // as see them.
6592 bool done = false;
6593 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006594 if (CanTy.isRestrictQualified())
6595 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006596 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6597 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006598 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006599 CanTy->getAs<MemberPointerType>())
6600 CanTy = ResTypeMPtr->getPointeeType();
6601 else
6602 done = true;
6603 if (CanTy.isVolatileQualified())
6604 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006605 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6606 return VRQuals;
6607 }
6608 }
6609 }
6610 return VRQuals;
6611}
John McCall00071ec2010-11-13 05:51:15 +00006612
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006613namespace {
John McCall00071ec2010-11-13 05:51:15 +00006614
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006615/// \brief Helper class to manage the addition of builtin operator overload
6616/// candidates. It provides shared state and utility methods used throughout
6617/// the process, as well as a helper method to add each group of builtin
6618/// operator overloads from the standard to a candidate set.
6619class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006620 // Common instance state available to all overload candidate addition methods.
6621 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006622 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006623 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006624 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006625 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006626 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006627
Chandler Carruth6d695582010-12-12 10:35:00 +00006628 // Define some constants used to index and iterate over the arithemetic types
6629 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006630 // The "promoted arithmetic types" are the arithmetic
6631 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006632 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006633 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006634 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006635 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006636 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006637 LastPromotedArithmeticType = 11;
6638 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006639
Chandler Carruth6d695582010-12-12 10:35:00 +00006640 /// \brief Get the canonical type for a given arithmetic type index.
6641 CanQualType getArithmeticType(unsigned index) {
6642 assert(index < NumArithmeticTypes);
6643 static CanQualType ASTContext::* const
6644 ArithmeticTypes[NumArithmeticTypes] = {
6645 // Start of promoted types.
6646 &ASTContext::FloatTy,
6647 &ASTContext::DoubleTy,
6648 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006649
Chandler Carruth6d695582010-12-12 10:35:00 +00006650 // Start of integral types.
6651 &ASTContext::IntTy,
6652 &ASTContext::LongTy,
6653 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006654 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006655 &ASTContext::UnsignedIntTy,
6656 &ASTContext::UnsignedLongTy,
6657 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006658 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006659 // End of promoted types.
6660
6661 &ASTContext::BoolTy,
6662 &ASTContext::CharTy,
6663 &ASTContext::WCharTy,
6664 &ASTContext::Char16Ty,
6665 &ASTContext::Char32Ty,
6666 &ASTContext::SignedCharTy,
6667 &ASTContext::ShortTy,
6668 &ASTContext::UnsignedCharTy,
6669 &ASTContext::UnsignedShortTy,
6670 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006671 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006672 };
6673 return S.Context.*ArithmeticTypes[index];
6674 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006675
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006676 /// \brief Gets the canonical type resulting from the usual arithemetic
6677 /// converions for the given arithmetic types.
6678 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6679 // Accelerator table for performing the usual arithmetic conversions.
6680 // The rules are basically:
6681 // - if either is floating-point, use the wider floating-point
6682 // - if same signedness, use the higher rank
6683 // - if same size, use unsigned of the higher rank
6684 // - use the larger type
6685 // These rules, together with the axiom that higher ranks are
6686 // never smaller, are sufficient to precompute all of these results
6687 // *except* when dealing with signed types of higher rank.
6688 // (we could precompute SLL x UI for all known platforms, but it's
6689 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006690 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006691 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006692 Dep=-1,
6693 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006694 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006695 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006696 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006697/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6698/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6699/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6700/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6701/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6702/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6703/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6704/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6705/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6706/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6707/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006708 };
6709
6710 assert(L < LastPromotedArithmeticType);
6711 assert(R < LastPromotedArithmeticType);
6712 int Idx = ConversionsTable[L][R];
6713
6714 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006715 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006716
6717 // Slow path: we need to compare widths.
6718 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006719 CanQualType LT = getArithmeticType(L),
6720 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006721 unsigned LW = S.Context.getIntWidth(LT),
6722 RW = S.Context.getIntWidth(RT);
6723
6724 // If they're different widths, use the signed type.
6725 if (LW > RW) return LT;
6726 else if (LW < RW) return RT;
6727
6728 // Otherwise, use the unsigned type of the signed type's rank.
6729 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6730 assert(L == SLL || R == SLL);
6731 return S.Context.UnsignedLongLongTy;
6732 }
6733
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006734 /// \brief Helper method to factor out the common pattern of adding overloads
6735 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006736 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006737 bool HasVolatile,
6738 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006739 QualType ParamTypes[2] = {
6740 S.Context.getLValueReferenceType(CandidateTy),
6741 S.Context.IntTy
6742 };
6743
6744 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006745 if (Args.size() == 1)
6746 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006747 else
Richard Smith958ba642013-05-05 15:51:06 +00006748 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006749
6750 // Use a heuristic to reduce number of builtin candidates in the set:
6751 // add volatile version only if there are conversions to a volatile type.
6752 if (HasVolatile) {
6753 ParamTypes[0] =
6754 S.Context.getLValueReferenceType(
6755 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006756 if (Args.size() == 1)
6757 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006758 else
Richard Smith958ba642013-05-05 15:51:06 +00006759 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006760 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006761
6762 // Add restrict version only if there are conversions to a restrict type
6763 // and our candidate type is a non-restrict-qualified pointer.
6764 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6765 !CandidateTy.isRestrictQualified()) {
6766 ParamTypes[0]
6767 = S.Context.getLValueReferenceType(
6768 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006769 if (Args.size() == 1)
6770 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006771 else
Richard Smith958ba642013-05-05 15:51:06 +00006772 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006773
6774 if (HasVolatile) {
6775 ParamTypes[0]
6776 = S.Context.getLValueReferenceType(
6777 S.Context.getCVRQualifiedType(CandidateTy,
6778 (Qualifiers::Volatile |
6779 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006780 if (Args.size() == 1)
6781 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006782 else
Richard Smith958ba642013-05-05 15:51:06 +00006783 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006784 }
6785 }
6786
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006787 }
6788
6789public:
6790 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006791 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006792 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006793 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006794 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006795 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006796 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006797 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006798 HasArithmeticOrEnumeralCandidateType(
6799 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006800 CandidateTypes(CandidateTypes),
6801 CandidateSet(CandidateSet) {
6802 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006803 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006804 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006805 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006806 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006807 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006808 assert(getArithmeticType(FirstPromotedArithmeticType)
6809 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006810 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006811 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006812 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006813 "Invalid last promoted arithmetic type");
6814 }
6815
6816 // C++ [over.built]p3:
6817 //
6818 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6819 // is either volatile or empty, there exist candidate operator
6820 // functions of the form
6821 //
6822 // VQ T& operator++(VQ T&);
6823 // T operator++(VQ T&, int);
6824 //
6825 // C++ [over.built]p4:
6826 //
6827 // For every pair (T, VQ), where T is an arithmetic type other
6828 // than bool, and VQ is either volatile or empty, there exist
6829 // candidate operator functions of the form
6830 //
6831 // VQ T& operator--(VQ T&);
6832 // T operator--(VQ T&, int);
6833 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006834 if (!HasArithmeticOrEnumeralCandidateType)
6835 return;
6836
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006837 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6838 Arith < NumArithmeticTypes; ++Arith) {
6839 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006840 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006841 VisibleTypeConversionsQuals.hasVolatile(),
6842 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006843 }
6844 }
6845
6846 // C++ [over.built]p5:
6847 //
6848 // For every pair (T, VQ), where T is a cv-qualified or
6849 // cv-unqualified object type, and VQ is either volatile or
6850 // empty, there exist candidate operator functions of the form
6851 //
6852 // T*VQ& operator++(T*VQ&);
6853 // T*VQ& operator--(T*VQ&);
6854 // T* operator++(T*VQ&, int);
6855 // T* operator--(T*VQ&, int);
6856 void addPlusPlusMinusMinusPointerOverloads() {
6857 for (BuiltinCandidateTypeSet::iterator
6858 Ptr = CandidateTypes[0].pointer_begin(),
6859 PtrEnd = CandidateTypes[0].pointer_end();
6860 Ptr != PtrEnd; ++Ptr) {
6861 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006862 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006863 continue;
6864
6865 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006866 (!(*Ptr).isVolatileQualified() &&
6867 VisibleTypeConversionsQuals.hasVolatile()),
6868 (!(*Ptr).isRestrictQualified() &&
6869 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006870 }
6871 }
6872
6873 // C++ [over.built]p6:
6874 // For every cv-qualified or cv-unqualified object type T, there
6875 // exist candidate operator functions of the form
6876 //
6877 // T& operator*(T*);
6878 //
6879 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006880 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006881 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006882 // T& operator*(T*);
6883 void addUnaryStarPointerOverloads() {
6884 for (BuiltinCandidateTypeSet::iterator
6885 Ptr = CandidateTypes[0].pointer_begin(),
6886 PtrEnd = CandidateTypes[0].pointer_end();
6887 Ptr != PtrEnd; ++Ptr) {
6888 QualType ParamTy = *Ptr;
6889 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006890 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6891 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006892
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006893 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6894 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6895 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006896
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006897 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006898 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006899 }
6900 }
6901
6902 // C++ [over.built]p9:
6903 // For every promoted arithmetic type T, there exist candidate
6904 // operator functions of the form
6905 //
6906 // T operator+(T);
6907 // T operator-(T);
6908 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006909 if (!HasArithmeticOrEnumeralCandidateType)
6910 return;
6911
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006912 for (unsigned Arith = FirstPromotedArithmeticType;
6913 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006914 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006915 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006916 }
6917
6918 // Extension: We also add these operators for vector types.
6919 for (BuiltinCandidateTypeSet::iterator
6920 Vec = CandidateTypes[0].vector_begin(),
6921 VecEnd = CandidateTypes[0].vector_end();
6922 Vec != VecEnd; ++Vec) {
6923 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006924 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006925 }
6926 }
6927
6928 // C++ [over.built]p8:
6929 // For every type T, there exist candidate operator functions of
6930 // the form
6931 //
6932 // T* operator+(T*);
6933 void addUnaryPlusPointerOverloads() {
6934 for (BuiltinCandidateTypeSet::iterator
6935 Ptr = CandidateTypes[0].pointer_begin(),
6936 PtrEnd = CandidateTypes[0].pointer_end();
6937 Ptr != PtrEnd; ++Ptr) {
6938 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006939 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006940 }
6941 }
6942
6943 // C++ [over.built]p10:
6944 // For every promoted integral type T, there exist candidate
6945 // operator functions of the form
6946 //
6947 // T operator~(T);
6948 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006949 if (!HasArithmeticOrEnumeralCandidateType)
6950 return;
6951
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006952 for (unsigned Int = FirstPromotedIntegralType;
6953 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006954 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006955 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006956 }
6957
6958 // Extension: We also add this operator for vector types.
6959 for (BuiltinCandidateTypeSet::iterator
6960 Vec = CandidateTypes[0].vector_begin(),
6961 VecEnd = CandidateTypes[0].vector_end();
6962 Vec != VecEnd; ++Vec) {
6963 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006964 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006965 }
6966 }
6967
6968 // C++ [over.match.oper]p16:
6969 // For every pointer to member type T, there exist candidate operator
6970 // functions of the form
6971 //
6972 // bool operator==(T,T);
6973 // bool operator!=(T,T);
6974 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6975 /// Set of (canonical) types that we've already handled.
6976 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6977
Richard Smith958ba642013-05-05 15:51:06 +00006978 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006979 for (BuiltinCandidateTypeSet::iterator
6980 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6981 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6982 MemPtr != MemPtrEnd;
6983 ++MemPtr) {
6984 // Don't add the same builtin candidate twice.
6985 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6986 continue;
6987
6988 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006989 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006990 }
6991 }
6992 }
6993
6994 // C++ [over.built]p15:
6995 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006996 // For every T, where T is an enumeration type, a pointer type, or
6997 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006998 //
6999 // bool operator<(T, T);
7000 // bool operator>(T, T);
7001 // bool operator<=(T, T);
7002 // bool operator>=(T, T);
7003 // bool operator==(T, T);
7004 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007005 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00007006 // C++ [over.match.oper]p3:
7007 // [...]the built-in candidates include all of the candidate operator
7008 // functions defined in 13.6 that, compared to the given operator, [...]
7009 // do not have the same parameter-type-list as any non-template non-member
7010 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007011 //
Eli Friedman97c67392012-09-18 21:52:24 +00007012 // Note that in practice, this only affects enumeration types because there
7013 // aren't any built-in candidates of record type, and a user-defined operator
7014 // must have an operand of record or enumeration type. Also, the only other
7015 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007016 // cannot be overloaded for enumeration types, so this is the only place
7017 // where we must suppress candidates like this.
7018 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7019 UserDefinedBinaryOperators;
7020
Richard Smith958ba642013-05-05 15:51:06 +00007021 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007022 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7023 CandidateTypes[ArgIdx].enumeration_end()) {
7024 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7025 CEnd = CandidateSet.end();
7026 C != CEnd; ++C) {
7027 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7028 continue;
7029
Eli Friedman97c67392012-09-18 21:52:24 +00007030 if (C->Function->isFunctionTemplateSpecialization())
7031 continue;
7032
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007033 QualType FirstParamType =
7034 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7035 QualType SecondParamType =
7036 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7037
7038 // Skip if either parameter isn't of enumeral type.
7039 if (!FirstParamType->isEnumeralType() ||
7040 !SecondParamType->isEnumeralType())
7041 continue;
7042
7043 // Add this operator to the set of known user-defined operators.
7044 UserDefinedBinaryOperators.insert(
7045 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7046 S.Context.getCanonicalType(SecondParamType)));
7047 }
7048 }
7049 }
7050
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007051 /// Set of (canonical) types that we've already handled.
7052 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7053
Richard Smith958ba642013-05-05 15:51:06 +00007054 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007055 for (BuiltinCandidateTypeSet::iterator
7056 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7057 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7058 Ptr != PtrEnd; ++Ptr) {
7059 // Don't add the same builtin candidate twice.
7060 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7061 continue;
7062
7063 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007064 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007065 }
7066 for (BuiltinCandidateTypeSet::iterator
7067 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7068 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7069 Enum != EnumEnd; ++Enum) {
7070 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7071
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007072 // Don't add the same builtin candidate twice, or if a user defined
7073 // candidate exists.
7074 if (!AddedTypes.insert(CanonType) ||
7075 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7076 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007077 continue;
7078
7079 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007080 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007081 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007082
7083 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7084 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7085 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007086 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007087 NullPtrTy))) {
7088 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007089 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007090 CandidateSet);
7091 }
7092 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007093 }
7094 }
7095
7096 // C++ [over.built]p13:
7097 //
7098 // For every cv-qualified or cv-unqualified object type T
7099 // there exist candidate operator functions of the form
7100 //
7101 // T* operator+(T*, ptrdiff_t);
7102 // T& operator[](T*, ptrdiff_t); [BELOW]
7103 // T* operator-(T*, ptrdiff_t);
7104 // T* operator+(ptrdiff_t, T*);
7105 // T& operator[](ptrdiff_t, T*); [BELOW]
7106 //
7107 // C++ [over.built]p14:
7108 //
7109 // For every T, where T is a pointer to object type, there
7110 // exist candidate operator functions of the form
7111 //
7112 // ptrdiff_t operator-(T, T);
7113 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7114 /// Set of (canonical) types that we've already handled.
7115 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7116
7117 for (int Arg = 0; Arg < 2; ++Arg) {
7118 QualType AsymetricParamTypes[2] = {
7119 S.Context.getPointerDiffType(),
7120 S.Context.getPointerDiffType(),
7121 };
7122 for (BuiltinCandidateTypeSet::iterator
7123 Ptr = CandidateTypes[Arg].pointer_begin(),
7124 PtrEnd = CandidateTypes[Arg].pointer_end();
7125 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007126 QualType PointeeTy = (*Ptr)->getPointeeType();
7127 if (!PointeeTy->isObjectType())
7128 continue;
7129
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007130 AsymetricParamTypes[Arg] = *Ptr;
7131 if (Arg == 0 || Op == OO_Plus) {
7132 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7133 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007134 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007135 }
7136 if (Op == OO_Minus) {
7137 // ptrdiff_t operator-(T, T);
7138 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7139 continue;
7140
7141 QualType ParamTypes[2] = { *Ptr, *Ptr };
7142 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007143 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007144 }
7145 }
7146 }
7147 }
7148
7149 // C++ [over.built]p12:
7150 //
7151 // For every pair of promoted arithmetic types L and R, there
7152 // exist candidate operator functions of the form
7153 //
7154 // LR operator*(L, R);
7155 // LR operator/(L, R);
7156 // LR operator+(L, R);
7157 // LR operator-(L, R);
7158 // bool operator<(L, R);
7159 // bool operator>(L, R);
7160 // bool operator<=(L, R);
7161 // bool operator>=(L, R);
7162 // bool operator==(L, R);
7163 // bool operator!=(L, R);
7164 //
7165 // where LR is the result of the usual arithmetic conversions
7166 // between types L and R.
7167 //
7168 // C++ [over.built]p24:
7169 //
7170 // For every pair of promoted arithmetic types L and R, there exist
7171 // candidate operator functions of the form
7172 //
7173 // LR operator?(bool, L, R);
7174 //
7175 // where LR is the result of the usual arithmetic conversions
7176 // between types L and R.
7177 // Our candidates ignore the first parameter.
7178 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007179 if (!HasArithmeticOrEnumeralCandidateType)
7180 return;
7181
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007182 for (unsigned Left = FirstPromotedArithmeticType;
7183 Left < LastPromotedArithmeticType; ++Left) {
7184 for (unsigned Right = FirstPromotedArithmeticType;
7185 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007186 QualType LandR[2] = { getArithmeticType(Left),
7187 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007188 QualType Result =
7189 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007190 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007191 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007192 }
7193 }
7194
7195 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7196 // conditional operator for vector types.
7197 for (BuiltinCandidateTypeSet::iterator
7198 Vec1 = CandidateTypes[0].vector_begin(),
7199 Vec1End = CandidateTypes[0].vector_end();
7200 Vec1 != Vec1End; ++Vec1) {
7201 for (BuiltinCandidateTypeSet::iterator
7202 Vec2 = CandidateTypes[1].vector_begin(),
7203 Vec2End = CandidateTypes[1].vector_end();
7204 Vec2 != Vec2End; ++Vec2) {
7205 QualType LandR[2] = { *Vec1, *Vec2 };
7206 QualType Result = S.Context.BoolTy;
7207 if (!isComparison) {
7208 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7209 Result = *Vec1;
7210 else
7211 Result = *Vec2;
7212 }
7213
Richard Smith958ba642013-05-05 15:51:06 +00007214 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007215 }
7216 }
7217 }
7218
7219 // C++ [over.built]p17:
7220 //
7221 // For every pair of promoted integral types L and R, there
7222 // exist candidate operator functions of the form
7223 //
7224 // LR operator%(L, R);
7225 // LR operator&(L, R);
7226 // LR operator^(L, R);
7227 // LR operator|(L, R);
7228 // L operator<<(L, R);
7229 // L operator>>(L, R);
7230 //
7231 // where LR is the result of the usual arithmetic conversions
7232 // between types L and R.
7233 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007234 if (!HasArithmeticOrEnumeralCandidateType)
7235 return;
7236
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007237 for (unsigned Left = FirstPromotedIntegralType;
7238 Left < LastPromotedIntegralType; ++Left) {
7239 for (unsigned Right = FirstPromotedIntegralType;
7240 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007241 QualType LandR[2] = { getArithmeticType(Left),
7242 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007243 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7244 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007245 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007246 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007247 }
7248 }
7249 }
7250
7251 // C++ [over.built]p20:
7252 //
7253 // For every pair (T, VQ), where T is an enumeration or
7254 // pointer to member type and VQ is either volatile or
7255 // empty, there exist candidate operator functions of the form
7256 //
7257 // VQ T& operator=(VQ T&, T);
7258 void addAssignmentMemberPointerOrEnumeralOverloads() {
7259 /// Set of (canonical) types that we've already handled.
7260 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7261
7262 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7263 for (BuiltinCandidateTypeSet::iterator
7264 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7265 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7266 Enum != EnumEnd; ++Enum) {
7267 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7268 continue;
7269
Richard Smith958ba642013-05-05 15:51:06 +00007270 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007271 }
7272
7273 for (BuiltinCandidateTypeSet::iterator
7274 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7275 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7276 MemPtr != MemPtrEnd; ++MemPtr) {
7277 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7278 continue;
7279
Richard Smith958ba642013-05-05 15:51:06 +00007280 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007281 }
7282 }
7283 }
7284
7285 // C++ [over.built]p19:
7286 //
7287 // For every pair (T, VQ), where T is any type and VQ is either
7288 // volatile or empty, there exist candidate operator functions
7289 // of the form
7290 //
7291 // T*VQ& operator=(T*VQ&, T*);
7292 //
7293 // C++ [over.built]p21:
7294 //
7295 // For every pair (T, VQ), where T is a cv-qualified or
7296 // cv-unqualified object type and VQ is either volatile or
7297 // empty, there exist candidate operator functions of the form
7298 //
7299 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7300 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7301 void addAssignmentPointerOverloads(bool isEqualOp) {
7302 /// Set of (canonical) types that we've already handled.
7303 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7304
7305 for (BuiltinCandidateTypeSet::iterator
7306 Ptr = CandidateTypes[0].pointer_begin(),
7307 PtrEnd = CandidateTypes[0].pointer_end();
7308 Ptr != PtrEnd; ++Ptr) {
7309 // If this is operator=, keep track of the builtin candidates we added.
7310 if (isEqualOp)
7311 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007312 else if (!(*Ptr)->getPointeeType()->isObjectType())
7313 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007314
7315 // non-volatile version
7316 QualType ParamTypes[2] = {
7317 S.Context.getLValueReferenceType(*Ptr),
7318 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7319 };
Richard Smith958ba642013-05-05 15:51:06 +00007320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007321 /*IsAssigmentOperator=*/ isEqualOp);
7322
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007323 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7324 VisibleTypeConversionsQuals.hasVolatile();
7325 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007326 // volatile version
7327 ParamTypes[0] =
7328 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007329 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007330 /*IsAssigmentOperator=*/isEqualOp);
7331 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007332
7333 if (!(*Ptr).isRestrictQualified() &&
7334 VisibleTypeConversionsQuals.hasRestrict()) {
7335 // restrict version
7336 ParamTypes[0]
7337 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007338 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007339 /*IsAssigmentOperator=*/isEqualOp);
7340
7341 if (NeedVolatile) {
7342 // volatile restrict version
7343 ParamTypes[0]
7344 = S.Context.getLValueReferenceType(
7345 S.Context.getCVRQualifiedType(*Ptr,
7346 (Qualifiers::Volatile |
7347 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007348 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007349 /*IsAssigmentOperator=*/isEqualOp);
7350 }
7351 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007352 }
7353
7354 if (isEqualOp) {
7355 for (BuiltinCandidateTypeSet::iterator
7356 Ptr = CandidateTypes[1].pointer_begin(),
7357 PtrEnd = CandidateTypes[1].pointer_end();
7358 Ptr != PtrEnd; ++Ptr) {
7359 // Make sure we don't add the same candidate twice.
7360 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7361 continue;
7362
Chandler Carruth6df868e2010-12-12 08:17:55 +00007363 QualType ParamTypes[2] = {
7364 S.Context.getLValueReferenceType(*Ptr),
7365 *Ptr,
7366 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007367
7368 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007369 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007370 /*IsAssigmentOperator=*/true);
7371
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007372 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7373 VisibleTypeConversionsQuals.hasVolatile();
7374 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007375 // volatile version
7376 ParamTypes[0] =
7377 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007378 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7379 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007380 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007381
7382 if (!(*Ptr).isRestrictQualified() &&
7383 VisibleTypeConversionsQuals.hasRestrict()) {
7384 // restrict version
7385 ParamTypes[0]
7386 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007387 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7388 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007389
7390 if (NeedVolatile) {
7391 // volatile restrict version
7392 ParamTypes[0]
7393 = S.Context.getLValueReferenceType(
7394 S.Context.getCVRQualifiedType(*Ptr,
7395 (Qualifiers::Volatile |
7396 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007397 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7398 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007399 }
7400 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007401 }
7402 }
7403 }
7404
7405 // C++ [over.built]p18:
7406 //
7407 // For every triple (L, VQ, R), where L is an arithmetic type,
7408 // VQ is either volatile or empty, and R is a promoted
7409 // arithmetic type, there exist candidate operator functions of
7410 // the form
7411 //
7412 // VQ L& operator=(VQ L&, R);
7413 // VQ L& operator*=(VQ L&, R);
7414 // VQ L& operator/=(VQ L&, R);
7415 // VQ L& operator+=(VQ L&, R);
7416 // VQ L& operator-=(VQ L&, R);
7417 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007418 if (!HasArithmeticOrEnumeralCandidateType)
7419 return;
7420
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007421 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7422 for (unsigned Right = FirstPromotedArithmeticType;
7423 Right < LastPromotedArithmeticType; ++Right) {
7424 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007425 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007426
7427 // Add this built-in operator as a candidate (VQ is empty).
7428 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007429 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007430 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007431 /*IsAssigmentOperator=*/isEqualOp);
7432
7433 // Add this built-in operator as a candidate (VQ is 'volatile').
7434 if (VisibleTypeConversionsQuals.hasVolatile()) {
7435 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007436 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007437 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007438 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007439 /*IsAssigmentOperator=*/isEqualOp);
7440 }
7441 }
7442 }
7443
7444 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7445 for (BuiltinCandidateTypeSet::iterator
7446 Vec1 = CandidateTypes[0].vector_begin(),
7447 Vec1End = CandidateTypes[0].vector_end();
7448 Vec1 != Vec1End; ++Vec1) {
7449 for (BuiltinCandidateTypeSet::iterator
7450 Vec2 = CandidateTypes[1].vector_begin(),
7451 Vec2End = CandidateTypes[1].vector_end();
7452 Vec2 != Vec2End; ++Vec2) {
7453 QualType ParamTypes[2];
7454 ParamTypes[1] = *Vec2;
7455 // Add this built-in operator as a candidate (VQ is empty).
7456 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007457 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007458 /*IsAssigmentOperator=*/isEqualOp);
7459
7460 // Add this built-in operator as a candidate (VQ is 'volatile').
7461 if (VisibleTypeConversionsQuals.hasVolatile()) {
7462 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7463 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007464 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007465 /*IsAssigmentOperator=*/isEqualOp);
7466 }
7467 }
7468 }
7469 }
7470
7471 // C++ [over.built]p22:
7472 //
7473 // For every triple (L, VQ, R), where L is an integral type, VQ
7474 // is either volatile or empty, and R is a promoted integral
7475 // type, there exist candidate operator functions of the form
7476 //
7477 // VQ L& operator%=(VQ L&, R);
7478 // VQ L& operator<<=(VQ L&, R);
7479 // VQ L& operator>>=(VQ L&, R);
7480 // VQ L& operator&=(VQ L&, R);
7481 // VQ L& operator^=(VQ L&, R);
7482 // VQ L& operator|=(VQ L&, R);
7483 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007484 if (!HasArithmeticOrEnumeralCandidateType)
7485 return;
7486
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007487 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7488 for (unsigned Right = FirstPromotedIntegralType;
7489 Right < LastPromotedIntegralType; ++Right) {
7490 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007491 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007492
7493 // Add this built-in operator as a candidate (VQ is empty).
7494 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007495 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007496 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007497 if (VisibleTypeConversionsQuals.hasVolatile()) {
7498 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007499 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007500 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7501 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007502 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007503 }
7504 }
7505 }
7506 }
7507
7508 // C++ [over.operator]p23:
7509 //
7510 // There also exist candidate operator functions of the form
7511 //
7512 // bool operator!(bool);
7513 // bool operator&&(bool, bool);
7514 // bool operator||(bool, bool);
7515 void addExclaimOverload() {
7516 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007517 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007518 /*IsAssignmentOperator=*/false,
7519 /*NumContextualBoolArguments=*/1);
7520 }
7521 void addAmpAmpOrPipePipeOverload() {
7522 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007523 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007524 /*IsAssignmentOperator=*/false,
7525 /*NumContextualBoolArguments=*/2);
7526 }
7527
7528 // C++ [over.built]p13:
7529 //
7530 // For every cv-qualified or cv-unqualified object type T there
7531 // exist candidate operator functions of the form
7532 //
7533 // T* operator+(T*, ptrdiff_t); [ABOVE]
7534 // T& operator[](T*, ptrdiff_t);
7535 // T* operator-(T*, ptrdiff_t); [ABOVE]
7536 // T* operator+(ptrdiff_t, T*); [ABOVE]
7537 // T& operator[](ptrdiff_t, T*);
7538 void addSubscriptOverloads() {
7539 for (BuiltinCandidateTypeSet::iterator
7540 Ptr = CandidateTypes[0].pointer_begin(),
7541 PtrEnd = CandidateTypes[0].pointer_end();
7542 Ptr != PtrEnd; ++Ptr) {
7543 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7544 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007545 if (!PointeeType->isObjectType())
7546 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007547
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007548 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7549
7550 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007551 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007552 }
7553
7554 for (BuiltinCandidateTypeSet::iterator
7555 Ptr = CandidateTypes[1].pointer_begin(),
7556 PtrEnd = CandidateTypes[1].pointer_end();
7557 Ptr != PtrEnd; ++Ptr) {
7558 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7559 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007560 if (!PointeeType->isObjectType())
7561 continue;
7562
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007563 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7564
7565 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007566 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007567 }
7568 }
7569
7570 // C++ [over.built]p11:
7571 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7572 // C1 is the same type as C2 or is a derived class of C2, T is an object
7573 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7574 // there exist candidate operator functions of the form
7575 //
7576 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7577 //
7578 // where CV12 is the union of CV1 and CV2.
7579 void addArrowStarOverloads() {
7580 for (BuiltinCandidateTypeSet::iterator
7581 Ptr = CandidateTypes[0].pointer_begin(),
7582 PtrEnd = CandidateTypes[0].pointer_end();
7583 Ptr != PtrEnd; ++Ptr) {
7584 QualType C1Ty = (*Ptr);
7585 QualType C1;
7586 QualifierCollector Q1;
7587 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7588 if (!isa<RecordType>(C1))
7589 continue;
7590 // heuristic to reduce number of builtin candidates in the set.
7591 // Add volatile/restrict version only if there are conversions to a
7592 // volatile/restrict type.
7593 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7594 continue;
7595 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7596 continue;
7597 for (BuiltinCandidateTypeSet::iterator
7598 MemPtr = CandidateTypes[1].member_pointer_begin(),
7599 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7600 MemPtr != MemPtrEnd; ++MemPtr) {
7601 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7602 QualType C2 = QualType(mptr->getClass(), 0);
7603 C2 = C2.getUnqualifiedType();
7604 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7605 break;
7606 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7607 // build CV12 T&
7608 QualType T = mptr->getPointeeType();
7609 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7610 T.isVolatileQualified())
7611 continue;
7612 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7613 T.isRestrictQualified())
7614 continue;
7615 T = Q1.apply(S.Context, T);
7616 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007617 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007618 }
7619 }
7620 }
7621
7622 // Note that we don't consider the first argument, since it has been
7623 // contextually converted to bool long ago. The candidates below are
7624 // therefore added as binary.
7625 //
7626 // C++ [over.built]p25:
7627 // For every type T, where T is a pointer, pointer-to-member, or scoped
7628 // enumeration type, there exist candidate operator functions of the form
7629 //
7630 // T operator?(bool, T, T);
7631 //
7632 void addConditionalOperatorOverloads() {
7633 /// Set of (canonical) types that we've already handled.
7634 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7635
7636 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7637 for (BuiltinCandidateTypeSet::iterator
7638 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7639 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7640 Ptr != PtrEnd; ++Ptr) {
7641 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7642 continue;
7643
7644 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007645 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007646 }
7647
7648 for (BuiltinCandidateTypeSet::iterator
7649 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7650 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7651 MemPtr != MemPtrEnd; ++MemPtr) {
7652 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7653 continue;
7654
7655 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007656 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007657 }
7658
Richard Smith80ad52f2013-01-02 11:42:31 +00007659 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007660 for (BuiltinCandidateTypeSet::iterator
7661 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7662 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7663 Enum != EnumEnd; ++Enum) {
7664 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7665 continue;
7666
7667 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7668 continue;
7669
7670 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007671 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007672 }
7673 }
7674 }
7675 }
7676};
7677
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007678} // end anonymous namespace
7679
7680/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7681/// operator overloads to the candidate set (C++ [over.built]), based
7682/// on the operator @p Op and the arguments given. For example, if the
7683/// operator is a binary '+', this routine might add "int
7684/// operator+(int, int)" to cover integer addition.
7685void
7686Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7687 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00007688 llvm::ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007689 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007690 // Find all of the types that the arguments can convert to, but only
7691 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007692 // that make use of these types. Also record whether we encounter non-record
7693 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007694 Qualifiers VisibleTypeConversionsQuals;
7695 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007696 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007697 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007698
7699 bool HasNonRecordCandidateType = false;
7700 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007701 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007702 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007703 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7704 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7705 OpLoc,
7706 true,
7707 (Op == OO_Exclaim ||
7708 Op == OO_AmpAmp ||
7709 Op == OO_PipePipe),
7710 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007711 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7712 CandidateTypes[ArgIdx].hasNonRecordTypes();
7713 HasArithmeticOrEnumeralCandidateType =
7714 HasArithmeticOrEnumeralCandidateType ||
7715 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007716 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007717
Chandler Carruth6a577462010-12-13 01:44:01 +00007718 // Exit early when no non-record types have been added to the candidate set
7719 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007720 //
7721 // We can't exit early for !, ||, or &&, since there we have always have
7722 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007723 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007724 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007725 return;
7726
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007727 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007728 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007729 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007730 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007731 CandidateTypes, CandidateSet);
7732
7733 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007734 switch (Op) {
7735 case OO_None:
7736 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007737 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007738
Chandler Carruthabb71842010-12-12 08:51:33 +00007739 case OO_New:
7740 case OO_Delete:
7741 case OO_Array_New:
7742 case OO_Array_Delete:
7743 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007744 llvm_unreachable(
7745 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007746
7747 case OO_Comma:
7748 case OO_Arrow:
7749 // C++ [over.match.oper]p3:
7750 // -- For the operator ',', the unary operator '&', or the
7751 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007752 break;
7753
7754 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007755 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007756 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007757 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007758
7759 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007760 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007761 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007762 } else {
7763 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7764 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7765 }
Douglas Gregor74253732008-11-19 15:42:04 +00007766 break;
7767
Chandler Carruthabb71842010-12-12 08:51:33 +00007768 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007769 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007770 OpBuilder.addUnaryStarPointerOverloads();
7771 else
7772 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7773 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007774
Chandler Carruthabb71842010-12-12 08:51:33 +00007775 case OO_Slash:
7776 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007777 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007778
7779 case OO_PlusPlus:
7780 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007781 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7782 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007783 break;
7784
Douglas Gregor19b7b152009-08-24 13:43:27 +00007785 case OO_EqualEqual:
7786 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007787 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007788 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007789
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007790 case OO_Less:
7791 case OO_Greater:
7792 case OO_LessEqual:
7793 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007794 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007795 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7796 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007797
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007798 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007799 case OO_Caret:
7800 case OO_Pipe:
7801 case OO_LessLess:
7802 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007803 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007804 break;
7805
Chandler Carruthabb71842010-12-12 08:51:33 +00007806 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007807 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007808 // C++ [over.match.oper]p3:
7809 // -- For the operator ',', the unary operator '&', or the
7810 // operator '->', the built-in candidates set is empty.
7811 break;
7812
7813 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7814 break;
7815
7816 case OO_Tilde:
7817 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7818 break;
7819
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007820 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007821 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007822 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007823
7824 case OO_PlusEqual:
7825 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007826 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007827 // Fall through.
7828
7829 case OO_StarEqual:
7830 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007831 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007832 break;
7833
7834 case OO_PercentEqual:
7835 case OO_LessLessEqual:
7836 case OO_GreaterGreaterEqual:
7837 case OO_AmpEqual:
7838 case OO_CaretEqual:
7839 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007840 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007841 break;
7842
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007843 case OO_Exclaim:
7844 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007845 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007846
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007847 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007848 case OO_PipePipe:
7849 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007850 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007851
7852 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007853 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007854 break;
7855
7856 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007857 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007858 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007859
7860 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007861 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007862 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7863 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007864 }
7865}
7866
Douglas Gregorfa047642009-02-04 00:32:51 +00007867/// \brief Add function candidates found via argument-dependent lookup
7868/// to the set of overloading candidates.
7869///
7870/// This routine performs argument-dependent name lookup based on the
7871/// given function name (which may also be an operator name) and adds
7872/// all of the overload candidates found by ADL to the overload
7873/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007874void
Douglas Gregorfa047642009-02-04 00:32:51 +00007875Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007876 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007877 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007878 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007879 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007880 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007881 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007882
John McCalla113e722010-01-26 06:04:06 +00007883 // FIXME: This approach for uniquing ADL results (and removing
7884 // redundant candidates from the set) relies on pointer-equality,
7885 // which means we need to key off the canonical decl. However,
7886 // always going back to the canonical decl might not get us the
7887 // right set of default arguments. What default arguments are
7888 // we supposed to consider on ADL candidates, anyway?
7889
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007890 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007891 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007892
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007893 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007894 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7895 CandEnd = CandidateSet.end();
7896 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007897 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007898 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007899 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007900 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007901 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007902
7903 // For each of the ADL candidates we found, add it to the overload
7904 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007905 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007906 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007907 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007908 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007909 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007910
Ahmed Charles13a140c2012-02-25 11:00:22 +00007911 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7912 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007913 } else
John McCall6e266892010-01-26 03:27:55 +00007914 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007915 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007916 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007917 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007918}
7919
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007920/// isBetterOverloadCandidate - Determines whether the first overload
7921/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007922bool
John McCall120d63c2010-08-24 20:38:10 +00007923isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007924 const OverloadCandidate &Cand1,
7925 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007926 SourceLocation Loc,
7927 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007928 // Define viable functions to be better candidates than non-viable
7929 // functions.
7930 if (!Cand2.Viable)
7931 return Cand1.Viable;
7932 else if (!Cand1.Viable)
7933 return false;
7934
Douglas Gregor88a35142008-12-22 05:46:06 +00007935 // C++ [over.match.best]p1:
7936 //
7937 // -- if F is a static member function, ICS1(F) is defined such
7938 // that ICS1(F) is neither better nor worse than ICS1(G) for
7939 // any function G, and, symmetrically, ICS1(G) is neither
7940 // better nor worse than ICS1(F).
7941 unsigned StartArg = 0;
7942 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7943 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007944
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007945 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007946 // A viable function F1 is defined to be a better function than another
7947 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007948 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007949 unsigned NumArgs = Cand1.NumConversions;
7950 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007951 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007952 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007953 switch (CompareImplicitConversionSequences(S,
7954 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007955 Cand2.Conversions[ArgIdx])) {
7956 case ImplicitConversionSequence::Better:
7957 // Cand1 has a better conversion sequence.
7958 HasBetterConversion = true;
7959 break;
7960
7961 case ImplicitConversionSequence::Worse:
7962 // Cand1 can't be better than Cand2.
7963 return false;
7964
7965 case ImplicitConversionSequence::Indistinguishable:
7966 // Do nothing.
7967 break;
7968 }
7969 }
7970
Mike Stump1eb44332009-09-09 15:08:12 +00007971 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007972 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007973 if (HasBetterConversion)
7974 return true;
7975
Mike Stump1eb44332009-09-09 15:08:12 +00007976 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007977 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007978 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007979 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7980 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007981
7982 // -- F1 and F2 are function template specializations, and the function
7983 // template for F1 is more specialized than the template for F2
7984 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007985 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007986 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007987 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007988 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007989 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7990 Cand2.Function->getPrimaryTemplate(),
7991 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007992 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007993 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007994 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007995 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007996 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007997
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007998 // -- the context is an initialization by user-defined conversion
7999 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8000 // from the return type of F1 to the destination type (i.e.,
8001 // the type of the entity being initialized) is a better
8002 // conversion sequence than the standard conversion sequence
8003 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008004 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00008005 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008006 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00008007 // First check whether we prefer one of the conversion functions over the
8008 // other. This only distinguishes the results in non-standard, extension
8009 // cases such as the conversion from a lambda closure type to a function
8010 // pointer or block.
8011 ImplicitConversionSequence::CompareKind FuncResult
8012 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8013 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8014 return FuncResult;
8015
John McCall120d63c2010-08-24 20:38:10 +00008016 switch (CompareStandardConversionSequences(S,
8017 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008018 Cand2.FinalConversion)) {
8019 case ImplicitConversionSequence::Better:
8020 // Cand1 has a better conversion sequence.
8021 return true;
8022
8023 case ImplicitConversionSequence::Worse:
8024 // Cand1 can't be better than Cand2.
8025 return false;
8026
8027 case ImplicitConversionSequence::Indistinguishable:
8028 // Do nothing
8029 break;
8030 }
8031 }
8032
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008033 return false;
8034}
8035
Mike Stump1eb44332009-09-09 15:08:12 +00008036/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008037/// within an overload candidate set.
8038///
James Dennettefce31f2012-06-22 08:10:18 +00008039/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008040/// which overload resolution occurs.
8041///
James Dennettefce31f2012-06-22 08:10:18 +00008042/// \param Best If overload resolution was successful or found a deleted
8043/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008044///
8045/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008046OverloadingResult
8047OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008048 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008049 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008050 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008051 Best = end();
8052 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8053 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008054 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008055 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008056 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008057 }
8058
8059 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008060 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008061 return OR_No_Viable_Function;
8062
8063 // Make sure that this function is better than every other viable
8064 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008065 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008066 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008067 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008068 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008069 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008070 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008071 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008072 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008073 }
Mike Stump1eb44332009-09-09 15:08:12 +00008074
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008075 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008076 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008077 (Best->Function->isDeleted() ||
8078 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008079 return OR_Deleted;
8080
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008081 return OR_Success;
8082}
8083
John McCall3c80f572010-01-12 02:15:36 +00008084namespace {
8085
8086enum OverloadCandidateKind {
8087 oc_function,
8088 oc_method,
8089 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008090 oc_function_template,
8091 oc_method_template,
8092 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008093 oc_implicit_default_constructor,
8094 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008095 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008096 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008097 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008098 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008099};
8100
John McCall220ccbf2010-01-13 00:25:19 +00008101OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8102 FunctionDecl *Fn,
8103 std::string &Description) {
8104 bool isTemplate = false;
8105
8106 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8107 isTemplate = true;
8108 Description = S.getTemplateArgumentBindingsText(
8109 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8110 }
John McCallb1622a12010-01-06 09:43:14 +00008111
8112 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008113 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008114 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008115
Sebastian Redlf677ea32011-02-05 19:23:19 +00008116 if (Ctor->getInheritedConstructor())
8117 return oc_implicit_inherited_constructor;
8118
Sean Hunt82713172011-05-25 23:16:36 +00008119 if (Ctor->isDefaultConstructor())
8120 return oc_implicit_default_constructor;
8121
8122 if (Ctor->isMoveConstructor())
8123 return oc_implicit_move_constructor;
8124
8125 assert(Ctor->isCopyConstructor() &&
8126 "unexpected sort of implicit constructor");
8127 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008128 }
8129
8130 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8131 // This actually gets spelled 'candidate function' for now, but
8132 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008133 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008134 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008135
Sean Hunt82713172011-05-25 23:16:36 +00008136 if (Meth->isMoveAssignmentOperator())
8137 return oc_implicit_move_assignment;
8138
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008139 if (Meth->isCopyAssignmentOperator())
8140 return oc_implicit_copy_assignment;
8141
8142 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8143 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008144 }
8145
John McCall220ccbf2010-01-13 00:25:19 +00008146 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008147}
8148
Sebastian Redlf677ea32011-02-05 19:23:19 +00008149void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8150 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8151 if (!Ctor) return;
8152
8153 Ctor = Ctor->getInheritedConstructor();
8154 if (!Ctor) return;
8155
8156 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8157}
8158
John McCall3c80f572010-01-12 02:15:36 +00008159} // end anonymous namespace
8160
8161// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008162void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008163 std::string FnDesc;
8164 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008165 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8166 << (unsigned) K << FnDesc;
8167 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8168 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008169 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008170}
8171
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008172//Notes the location of all overload candidates designated through
8173// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008174void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008175 assert(OverloadedExpr->getType() == Context.OverloadTy);
8176
8177 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8178 OverloadExpr *OvlExpr = Ovl.Expression;
8179
8180 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8181 IEnd = OvlExpr->decls_end();
8182 I != IEnd; ++I) {
8183 if (FunctionTemplateDecl *FunTmpl =
8184 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008185 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008186 } else if (FunctionDecl *Fun
8187 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008188 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008189 }
8190 }
8191}
8192
John McCall1d318332010-01-12 00:44:57 +00008193/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8194/// "lead" diagnostic; it will be given two arguments, the source and
8195/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008196void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8197 Sema &S,
8198 SourceLocation CaretLoc,
8199 const PartialDiagnostic &PDiag) const {
8200 S.Diag(CaretLoc, PDiag)
8201 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008202 // FIXME: The note limiting machinery is borrowed from
8203 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8204 // refactoring here.
8205 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8206 unsigned CandsShown = 0;
8207 AmbiguousConversionSequence::const_iterator I, E;
8208 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8209 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8210 break;
8211 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008212 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008213 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008214 if (I != E)
8215 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008216}
8217
John McCall1d318332010-01-12 00:44:57 +00008218namespace {
8219
John McCalladbb8f82010-01-13 09:16:55 +00008220void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8221 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8222 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008223 assert(Cand->Function && "for now, candidate must be a function");
8224 FunctionDecl *Fn = Cand->Function;
8225
8226 // There's a conversion slot for the object argument if this is a
8227 // non-constructor method. Note that 'I' corresponds the
8228 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008229 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008230 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008231 if (I == 0)
8232 isObjectArgument = true;
8233 else
8234 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008235 }
8236
John McCall220ccbf2010-01-13 00:25:19 +00008237 std::string FnDesc;
8238 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8239
John McCalladbb8f82010-01-13 09:16:55 +00008240 Expr *FromExpr = Conv.Bad.FromExpr;
8241 QualType FromTy = Conv.Bad.getFromType();
8242 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008243
John McCall5920dbb2010-02-02 02:42:52 +00008244 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008245 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008246 Expr *E = FromExpr->IgnoreParens();
8247 if (isa<UnaryOperator>(E))
8248 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008249 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008250
8251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8252 << (unsigned) FnKind << FnDesc
8253 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8254 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008255 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008256 return;
8257 }
8258
John McCall258b2032010-01-23 08:10:49 +00008259 // Do some hand-waving analysis to see if the non-viability is due
8260 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008261 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8262 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8263 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8264 CToTy = RT->getPointeeType();
8265 else {
8266 // TODO: detect and diagnose the full richness of const mismatches.
8267 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8268 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8269 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8270 }
8271
8272 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8273 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008274 Qualifiers FromQs = CFromTy.getQualifiers();
8275 Qualifiers ToQs = CToTy.getQualifiers();
8276
8277 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8279 << (unsigned) FnKind << FnDesc
8280 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8281 << FromTy
8282 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8283 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008284 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008285 return;
8286 }
8287
John McCallf85e1932011-06-15 23:02:42 +00008288 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008289 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008290 << (unsigned) FnKind << FnDesc
8291 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8292 << FromTy
8293 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8294 << (unsigned) isObjectArgument << I+1;
8295 MaybeEmitInheritedConstructorNote(S, Fn);
8296 return;
8297 }
8298
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008299 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8301 << (unsigned) FnKind << FnDesc
8302 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8303 << FromTy
8304 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8305 << (unsigned) isObjectArgument << I+1;
8306 MaybeEmitInheritedConstructorNote(S, Fn);
8307 return;
8308 }
8309
John McCall651f3ee2010-01-14 03:28:57 +00008310 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8311 assert(CVR && "unexpected qualifiers mismatch");
8312
8313 if (isObjectArgument) {
8314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8315 << (unsigned) FnKind << FnDesc
8316 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8317 << FromTy << (CVR - 1);
8318 } else {
8319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8320 << (unsigned) FnKind << FnDesc
8321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8322 << FromTy << (CVR - 1) << I+1;
8323 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008324 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008325 return;
8326 }
8327
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008328 // Special diagnostic for failure to convert an initializer list, since
8329 // telling the user that it has type void is not useful.
8330 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8331 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8332 << (unsigned) FnKind << FnDesc
8333 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8334 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8335 MaybeEmitInheritedConstructorNote(S, Fn);
8336 return;
8337 }
8338
John McCall258b2032010-01-23 08:10:49 +00008339 // Diagnose references or pointers to incomplete types differently,
8340 // since it's far from impossible that the incompleteness triggered
8341 // the failure.
8342 QualType TempFromTy = FromTy.getNonReferenceType();
8343 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8344 TempFromTy = PTy->getPointeeType();
8345 if (TempFromTy->isIncompleteType()) {
8346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8347 << (unsigned) FnKind << FnDesc
8348 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8349 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008350 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008351 return;
8352 }
8353
Douglas Gregor85789812010-06-30 23:01:39 +00008354 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008355 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008356 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8357 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8358 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8359 FromPtrTy->getPointeeType()) &&
8360 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8361 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008362 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008363 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008364 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008365 }
8366 } else if (const ObjCObjectPointerType *FromPtrTy
8367 = FromTy->getAs<ObjCObjectPointerType>()) {
8368 if (const ObjCObjectPointerType *ToPtrTy
8369 = ToTy->getAs<ObjCObjectPointerType>())
8370 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8371 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8372 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8373 FromPtrTy->getPointeeType()) &&
8374 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008375 BaseToDerivedConversion = 2;
8376 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008377 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8378 !FromTy->isIncompleteType() &&
8379 !ToRefTy->getPointeeType()->isIncompleteType() &&
8380 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8381 BaseToDerivedConversion = 3;
8382 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8383 ToTy.getNonReferenceType().getCanonicalType() ==
8384 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008385 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8386 << (unsigned) FnKind << FnDesc
8387 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8388 << (unsigned) isObjectArgument << I + 1;
8389 MaybeEmitInheritedConstructorNote(S, Fn);
8390 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008391 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008392 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008393
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008394 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008395 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008396 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008397 << (unsigned) FnKind << FnDesc
8398 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008399 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008400 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008401 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008402 return;
8403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008404
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008405 if (isa<ObjCObjectPointerType>(CFromTy) &&
8406 isa<PointerType>(CToTy)) {
8407 Qualifiers FromQs = CFromTy.getQualifiers();
8408 Qualifiers ToQs = CToTy.getQualifiers();
8409 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8410 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8411 << (unsigned) FnKind << FnDesc
8412 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8413 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8414 MaybeEmitInheritedConstructorNote(S, Fn);
8415 return;
8416 }
8417 }
8418
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008419 // Emit the generic diagnostic and, optionally, add the hints to it.
8420 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8421 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008422 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008423 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8424 << (unsigned) (Cand->Fix.Kind);
8425
8426 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008427 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8428 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008429 FDiag << *HI;
8430 S.Diag(Fn->getLocation(), FDiag);
8431
Sebastian Redlf677ea32011-02-05 19:23:19 +00008432 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008433}
8434
8435void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8436 unsigned NumFormalArgs) {
8437 // TODO: treat calls to a missing default constructor as a special case
8438
8439 FunctionDecl *Fn = Cand->Function;
8440 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8441
8442 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008443
Douglas Gregor439d3c32011-05-05 00:13:13 +00008444 // With invalid overloaded operators, it's possible that we think we
8445 // have an arity mismatch when it fact it looks like we have the
8446 // right number of arguments, because only overloaded operators have
8447 // the weird behavior of overloading member and non-member functions.
8448 // Just don't report anything.
8449 if (Fn->isInvalidDecl() &&
8450 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8451 return;
8452
John McCalladbb8f82010-01-13 09:16:55 +00008453 // at least / at most / exactly
8454 unsigned mode, modeCount;
8455 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008456 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8457 (Cand->FailureKind == ovl_fail_bad_deduction &&
8458 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008459 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008460 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008461 mode = 0; // "at least"
8462 else
8463 mode = 2; // "exactly"
8464 modeCount = MinParams;
8465 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008466 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8467 (Cand->FailureKind == ovl_fail_bad_deduction &&
8468 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008469 if (MinParams != FnTy->getNumArgs())
8470 mode = 1; // "at most"
8471 else
8472 mode = 2; // "exactly"
8473 modeCount = FnTy->getNumArgs();
8474 }
8475
8476 std::string Description;
8477 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8478
Richard Smithf7b80562012-05-11 05:16:41 +00008479 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8481 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8482 << Fn->getParamDecl(0) << NumFormalArgs;
8483 else
8484 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8485 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8486 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008487 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008488}
8489
John McCall342fec42010-02-01 18:53:26 +00008490/// Diagnose a failed template-argument deduction.
8491void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008492 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008493 FunctionDecl *Fn = Cand->Function; // pattern
8494
Douglas Gregora9333192010-05-08 17:41:32 +00008495 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008496 NamedDecl *ParamD;
8497 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8498 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8499 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008500 switch (Cand->DeductionFailure.Result) {
8501 case Sema::TDK_Success:
8502 llvm_unreachable("TDK_success while diagnosing bad deduction");
8503
8504 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008505 assert(ParamD && "no parameter found for incomplete deduction result");
8506 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8507 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008508 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008509 return;
8510 }
8511
John McCall57e97782010-08-05 09:05:08 +00008512 case Sema::TDK_Underqualified: {
8513 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8514 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8515
8516 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8517
8518 // Param will have been canonicalized, but it should just be a
8519 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008520 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008521 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008522 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008523 assert(S.Context.hasSameType(Param, NonCanonParam));
8524
8525 // Arg has also been canonicalized, but there's nothing we can do
8526 // about that. It also doesn't matter as much, because it won't
8527 // have any template parameters in it (because deduction isn't
8528 // done on dependent types).
8529 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8530
8531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8532 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008533 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008534 return;
8535 }
8536
8537 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008538 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008539 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008540 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008541 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008542 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008543 which = 1;
8544 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008545 which = 2;
8546 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008547
Douglas Gregora9333192010-05-08 17:41:32 +00008548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008549 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008550 << *Cand->DeductionFailure.getFirstArg()
8551 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008552 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008553 return;
8554 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008555
Douglas Gregorf1a84452010-05-08 19:15:54 +00008556 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008557 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008558 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008559 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008560 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8561 << ParamD->getDeclName();
8562 else {
8563 int index = 0;
8564 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8565 index = TTP->getIndex();
8566 else if (NonTypeTemplateParmDecl *NTTP
8567 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8568 index = NTTP->getIndex();
8569 else
8570 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008571 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008572 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8573 << (index + 1);
8574 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008575 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008576 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008577
Douglas Gregora18592e2010-05-08 18:13:28 +00008578 case Sema::TDK_TooManyArguments:
8579 case Sema::TDK_TooFewArguments:
8580 DiagnoseArityMismatch(S, Cand, NumArgs);
8581 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008582
8583 case Sema::TDK_InstantiationDepth:
8584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008585 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008586 return;
8587
8588 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008589 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008590 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008591 if (TemplateArgumentList *Args =
8592 Cand->DeductionFailure.getTemplateArgumentList()) {
8593 TemplateArgString = " ";
8594 TemplateArgString += S.getTemplateArgumentBindingsText(
8595 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8596 }
8597
Richard Smith4493c0a2012-05-09 05:17:00 +00008598 // If this candidate was disabled by enable_if, say so.
8599 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8600 if (PDiag && PDiag->second.getDiagID() ==
8601 diag::err_typename_nested_not_found_enable_if) {
8602 // FIXME: Use the source range of the condition, and the fully-qualified
8603 // name of the enable_if template. These are both present in PDiag.
8604 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8605 << "'enable_if'" << TemplateArgString;
8606 return;
8607 }
8608
Richard Smithb8590f32012-05-07 09:03:25 +00008609 // Format the SFINAE diagnostic into the argument string.
8610 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8611 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008612 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008613 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008614 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008615 SFINAEArgString = ": ";
8616 R = SourceRange(PDiag->first, PDiag->first);
8617 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8618 }
8619
Douglas Gregorec20f462010-05-08 20:07:26 +00008620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008621 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008622 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008623 return;
8624 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008625
Richard Smith0efa62f2013-01-31 04:03:12 +00008626 case Sema::TDK_FailedOverloadResolution: {
8627 OverloadExpr::FindResult R =
8628 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8629 S.Diag(Fn->getLocation(),
8630 diag::note_ovl_candidate_failed_overload_resolution)
8631 << R.Expression->getName();
8632 return;
8633 }
8634
Richard Trieueef35f82013-04-08 21:11:40 +00008635 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008636 // FIXME: Provide a source location to indicate what we couldn't match.
Richard Trieueef35f82013-04-08 21:11:40 +00008637 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8638 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
8639 if (FirstTA.getKind() == TemplateArgument::Template &&
8640 SecondTA.getKind() == TemplateArgument::Template) {
8641 TemplateName FirstTN = FirstTA.getAsTemplate();
8642 TemplateName SecondTN = SecondTA.getAsTemplate();
8643 if (FirstTN.getKind() == TemplateName::Template &&
8644 SecondTN.getKind() == TemplateName::Template) {
8645 if (FirstTN.getAsTemplateDecl()->getName() ==
8646 SecondTN.getAsTemplateDecl()->getName()) {
8647 // FIXME: This fixes a bad diagnostic where both templates are named
8648 // the same. This particular case is a bit difficult since:
8649 // 1) It is passed as a string to the diagnostic printer.
8650 // 2) The diagnostic printer only attempts to find a better
8651 // name for types, not decls.
8652 // Ideally, this should folded into the diagnostic printer.
8653 S.Diag(Fn->getLocation(),
8654 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8655 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8656 return;
8657 }
8658 }
8659 }
Richard Smith29805ca2013-01-31 05:19:49 +00008660 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
Richard Trieueef35f82013-04-08 21:11:40 +00008661 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008662 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008663 }
John McCall342fec42010-02-01 18:53:26 +00008664 // TODO: diagnose these individually, then kill off
8665 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008666 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008667 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008668 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008669 return;
8670 }
8671}
8672
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008673/// CUDA: diagnose an invalid call across targets.
8674void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8675 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8676 FunctionDecl *Callee = Cand->Function;
8677
8678 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8679 CalleeTarget = S.IdentifyCUDATarget(Callee);
8680
8681 std::string FnDesc;
8682 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8683
8684 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8685 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8686}
8687
John McCall342fec42010-02-01 18:53:26 +00008688/// Generates a 'note' diagnostic for an overload candidate. We've
8689/// already generated a primary error at the call site.
8690///
8691/// It really does need to be a single diagnostic with its caret
8692/// pointed at the candidate declaration. Yes, this creates some
8693/// major challenges of technical writing. Yes, this makes pointing
8694/// out problems with specific arguments quite awkward. It's still
8695/// better than generating twenty screens of text for every failed
8696/// overload.
8697///
8698/// It would be great to be able to express per-candidate problems
8699/// more richly for those diagnostic clients that cared, but we'd
8700/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008701void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008702 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008703 FunctionDecl *Fn = Cand->Function;
8704
John McCall81201622010-01-08 04:41:39 +00008705 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008706 if (Cand->Viable && (Fn->isDeleted() ||
8707 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008708 std::string FnDesc;
8709 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008710
8711 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008712 << FnKind << FnDesc
8713 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008714 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008715 return;
John McCall81201622010-01-08 04:41:39 +00008716 }
8717
John McCall220ccbf2010-01-13 00:25:19 +00008718 // We don't really have anything else to say about viable candidates.
8719 if (Cand->Viable) {
8720 S.NoteOverloadCandidate(Fn);
8721 return;
8722 }
John McCall1d318332010-01-12 00:44:57 +00008723
John McCalladbb8f82010-01-13 09:16:55 +00008724 switch (Cand->FailureKind) {
8725 case ovl_fail_too_many_arguments:
8726 case ovl_fail_too_few_arguments:
8727 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008728
John McCalladbb8f82010-01-13 09:16:55 +00008729 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008730 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008731
John McCall717e8912010-01-23 05:17:32 +00008732 case ovl_fail_trivial_conversion:
8733 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008734 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008735 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008736
John McCallb1bdc622010-02-25 01:37:24 +00008737 case ovl_fail_bad_conversion: {
8738 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008739 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008740 if (Cand->Conversions[I].isBad())
8741 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008742
John McCalladbb8f82010-01-13 09:16:55 +00008743 // FIXME: this currently happens when we're called from SemaInit
8744 // when user-conversion overload fails. Figure out how to handle
8745 // those conditions and diagnose them well.
8746 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008747 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008748
8749 case ovl_fail_bad_target:
8750 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008751 }
John McCalla1d7d622010-01-08 00:58:21 +00008752}
8753
8754void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8755 // Desugar the type of the surrogate down to a function type,
8756 // retaining as many typedefs as possible while still showing
8757 // the function type (and, therefore, its parameter types).
8758 QualType FnType = Cand->Surrogate->getConversionType();
8759 bool isLValueReference = false;
8760 bool isRValueReference = false;
8761 bool isPointer = false;
8762 if (const LValueReferenceType *FnTypeRef =
8763 FnType->getAs<LValueReferenceType>()) {
8764 FnType = FnTypeRef->getPointeeType();
8765 isLValueReference = true;
8766 } else if (const RValueReferenceType *FnTypeRef =
8767 FnType->getAs<RValueReferenceType>()) {
8768 FnType = FnTypeRef->getPointeeType();
8769 isRValueReference = true;
8770 }
8771 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8772 FnType = FnTypePtr->getPointeeType();
8773 isPointer = true;
8774 }
8775 // Desugar down to a function type.
8776 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8777 // Reconstruct the pointer/reference as appropriate.
8778 if (isPointer) FnType = S.Context.getPointerType(FnType);
8779 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8780 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8781
8782 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8783 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008784 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008785}
8786
8787void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008788 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008789 SourceLocation OpLoc,
8790 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008791 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008792 std::string TypeStr("operator");
8793 TypeStr += Opc;
8794 TypeStr += "(";
8795 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008796 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008797 TypeStr += ")";
8798 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8799 } else {
8800 TypeStr += ", ";
8801 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8802 TypeStr += ")";
8803 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8804 }
8805}
8806
8807void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8808 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008809 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008810 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8811 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008812 if (ICS.isBad()) break; // all meaningless after first invalid
8813 if (!ICS.isAmbiguous()) continue;
8814
John McCall120d63c2010-08-24 20:38:10 +00008815 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008816 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008817 }
8818}
8819
John McCall1b77e732010-01-15 23:32:50 +00008820SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8821 if (Cand->Function)
8822 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008823 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008824 return Cand->Surrogate->getLocation();
8825 return SourceLocation();
8826}
8827
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008828static unsigned
8829RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008830 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008831 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008832 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008833
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008834 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008835 case Sema::TDK_Incomplete:
8836 return 1;
8837
8838 case Sema::TDK_Underqualified:
8839 case Sema::TDK_Inconsistent:
8840 return 2;
8841
8842 case Sema::TDK_SubstitutionFailure:
8843 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008844 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008845 return 3;
8846
8847 case Sema::TDK_InstantiationDepth:
8848 case Sema::TDK_FailedOverloadResolution:
8849 return 4;
8850
8851 case Sema::TDK_InvalidExplicitArguments:
8852 return 5;
8853
8854 case Sema::TDK_TooManyArguments:
8855 case Sema::TDK_TooFewArguments:
8856 return 6;
8857 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008858 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008859}
8860
John McCallbf65c0b2010-01-12 00:48:53 +00008861struct CompareOverloadCandidatesForDisplay {
8862 Sema &S;
8863 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008864
8865 bool operator()(const OverloadCandidate *L,
8866 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008867 // Fast-path this check.
8868 if (L == R) return false;
8869
John McCall81201622010-01-08 04:41:39 +00008870 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008871 if (L->Viable) {
8872 if (!R->Viable) return true;
8873
8874 // TODO: introduce a tri-valued comparison for overload
8875 // candidates. Would be more worthwhile if we had a sort
8876 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008877 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8878 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008879 } else if (R->Viable)
8880 return false;
John McCall81201622010-01-08 04:41:39 +00008881
John McCall1b77e732010-01-15 23:32:50 +00008882 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008883
John McCall1b77e732010-01-15 23:32:50 +00008884 // Criteria by which we can sort non-viable candidates:
8885 if (!L->Viable) {
8886 // 1. Arity mismatches come after other candidates.
8887 if (L->FailureKind == ovl_fail_too_many_arguments ||
8888 L->FailureKind == ovl_fail_too_few_arguments)
8889 return false;
8890 if (R->FailureKind == ovl_fail_too_many_arguments ||
8891 R->FailureKind == ovl_fail_too_few_arguments)
8892 return true;
John McCall81201622010-01-08 04:41:39 +00008893
John McCall717e8912010-01-23 05:17:32 +00008894 // 2. Bad conversions come first and are ordered by the number
8895 // of bad conversions and quality of good conversions.
8896 if (L->FailureKind == ovl_fail_bad_conversion) {
8897 if (R->FailureKind != ovl_fail_bad_conversion)
8898 return true;
8899
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008900 // The conversion that can be fixed with a smaller number of changes,
8901 // comes first.
8902 unsigned numLFixes = L->Fix.NumConversionsFixed;
8903 unsigned numRFixes = R->Fix.NumConversionsFixed;
8904 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8905 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008906 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008907 if (numLFixes < numRFixes)
8908 return true;
8909 else
8910 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008911 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008912
John McCall717e8912010-01-23 05:17:32 +00008913 // If there's any ordering between the defined conversions...
8914 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008915 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008916
8917 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008918 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008919 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008920 switch (CompareImplicitConversionSequences(S,
8921 L->Conversions[I],
8922 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008923 case ImplicitConversionSequence::Better:
8924 leftBetter++;
8925 break;
8926
8927 case ImplicitConversionSequence::Worse:
8928 leftBetter--;
8929 break;
8930
8931 case ImplicitConversionSequence::Indistinguishable:
8932 break;
8933 }
8934 }
8935 if (leftBetter > 0) return true;
8936 if (leftBetter < 0) return false;
8937
8938 } else if (R->FailureKind == ovl_fail_bad_conversion)
8939 return false;
8940
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008941 if (L->FailureKind == ovl_fail_bad_deduction) {
8942 if (R->FailureKind != ovl_fail_bad_deduction)
8943 return true;
8944
8945 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8946 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008947 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008948 } else if (R->FailureKind == ovl_fail_bad_deduction)
8949 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008950
John McCall1b77e732010-01-15 23:32:50 +00008951 // TODO: others?
8952 }
8953
8954 // Sort everything else by location.
8955 SourceLocation LLoc = GetLocationForCandidate(L);
8956 SourceLocation RLoc = GetLocationForCandidate(R);
8957
8958 // Put candidates without locations (e.g. builtins) at the end.
8959 if (LLoc.isInvalid()) return false;
8960 if (RLoc.isInvalid()) return true;
8961
8962 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008963 }
8964};
8965
John McCall717e8912010-01-23 05:17:32 +00008966/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008967/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008968void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008969 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008970 assert(!Cand->Viable);
8971
8972 // Don't do anything on failures other than bad conversion.
8973 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8974
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008975 // We only want the FixIts if all the arguments can be corrected.
8976 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008977 // Use a implicit copy initialization to check conversion fixes.
8978 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008979
John McCall717e8912010-01-23 05:17:32 +00008980 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008981 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008982 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008983 while (true) {
8984 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8985 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008986 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008987 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008988 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008989 }
John McCall717e8912010-01-23 05:17:32 +00008990 }
8991
8992 if (ConvIdx == ConvCount)
8993 return;
8994
John McCallb1bdc622010-02-25 01:37:24 +00008995 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8996 "remaining conversion is initialized?");
8997
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008998 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008999 // operation somehow.
9000 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00009001
9002 const FunctionProtoType* Proto;
9003 unsigned ArgIdx = ConvIdx;
9004
9005 if (Cand->IsSurrogate) {
9006 QualType ConvType
9007 = Cand->Surrogate->getConversionType().getNonReferenceType();
9008 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9009 ConvType = ConvPtrType->getPointeeType();
9010 Proto = ConvType->getAs<FunctionProtoType>();
9011 ArgIdx--;
9012 } else if (Cand->Function) {
9013 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9014 if (isa<CXXMethodDecl>(Cand->Function) &&
9015 !isa<CXXConstructorDecl>(Cand->Function))
9016 ArgIdx--;
9017 } else {
9018 // Builtin binary operator with a bad first conversion.
9019 assert(ConvCount <= 3);
9020 for (; ConvIdx != ConvCount; ++ConvIdx)
9021 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009022 = TryCopyInitialization(S, Args[ConvIdx],
9023 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009024 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009025 /*InOverloadResolution*/ true,
9026 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009027 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009028 return;
9029 }
9030
9031 // Fill in the rest of the conversions.
9032 unsigned NumArgsInProto = Proto->getNumArgs();
9033 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009034 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009035 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009036 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009037 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009038 /*InOverloadResolution=*/true,
9039 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009040 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009041 // Store the FixIt in the candidate if it exists.
9042 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009043 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009044 }
John McCall717e8912010-01-23 05:17:32 +00009045 else
9046 Cand->Conversions[ConvIdx].setEllipsis();
9047 }
9048}
9049
John McCalla1d7d622010-01-08 00:58:21 +00009050} // end anonymous namespace
9051
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009052/// PrintOverloadCandidates - When overload resolution fails, prints
9053/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009054/// set.
John McCall120d63c2010-08-24 20:38:10 +00009055void OverloadCandidateSet::NoteCandidates(Sema &S,
9056 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009057 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009058 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009059 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009060 // Sort the candidates by viability and position. Sorting directly would
9061 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009062 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009063 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9064 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009065 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009066 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009067 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009068 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009069 if (Cand->Function || Cand->IsSurrogate)
9070 Cands.push_back(Cand);
9071 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9072 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009073 }
9074 }
9075
John McCallbf65c0b2010-01-12 00:48:53 +00009076 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009077 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009078
John McCall1d318332010-01-12 00:44:57 +00009079 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009080
Chris Lattner5f9e2722011-07-23 10:55:15 +00009081 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009082 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009083 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009084 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9085 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009086
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009087 // Set an arbitrary limit on the number of candidate functions we'll spam
9088 // the user with. FIXME: This limit should depend on details of the
9089 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009090 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009091 break;
9092 }
9093 ++CandsShown;
9094
John McCalla1d7d622010-01-08 00:58:21 +00009095 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009096 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009097 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009098 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009099 else {
9100 assert(Cand->Viable &&
9101 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009102 // Generally we only see ambiguities including viable builtin
9103 // operators if overload resolution got screwed up by an
9104 // ambiguous user-defined conversion.
9105 //
9106 // FIXME: It's quite possible for different conversions to see
9107 // different ambiguities, though.
9108 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009109 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009110 ReportedAmbiguousConversions = true;
9111 }
John McCalla1d7d622010-01-08 00:58:21 +00009112
John McCall1d318332010-01-12 00:44:57 +00009113 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009114 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009115 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009116 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009117
9118 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009119 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009120}
9121
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009122// [PossiblyAFunctionType] --> [Return]
9123// NonFunctionType --> NonFunctionType
9124// R (A) --> R(A)
9125// R (*)(A) --> R (A)
9126// R (&)(A) --> R (A)
9127// R (S::*)(A) --> R (A)
9128QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9129 QualType Ret = PossiblyAFunctionType;
9130 if (const PointerType *ToTypePtr =
9131 PossiblyAFunctionType->getAs<PointerType>())
9132 Ret = ToTypePtr->getPointeeType();
9133 else if (const ReferenceType *ToTypeRef =
9134 PossiblyAFunctionType->getAs<ReferenceType>())
9135 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009136 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009137 PossiblyAFunctionType->getAs<MemberPointerType>())
9138 Ret = MemTypePtr->getPointeeType();
9139 Ret =
9140 Context.getCanonicalType(Ret).getUnqualifiedType();
9141 return Ret;
9142}
Douglas Gregor904eed32008-11-10 20:40:00 +00009143
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009144// A helper class to help with address of function resolution
9145// - allows us to avoid passing around all those ugly parameters
9146class AddressOfFunctionResolver
9147{
9148 Sema& S;
9149 Expr* SourceExpr;
9150 const QualType& TargetType;
9151 QualType TargetFunctionType; // Extracted function type from target type
9152
9153 bool Complain;
9154 //DeclAccessPair& ResultFunctionAccessPair;
9155 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009156
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009157 bool TargetTypeIsNonStaticMemberFunction;
9158 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009159
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009160 OverloadExpr::FindResult OvlExprInfo;
9161 OverloadExpr *OvlExpr;
9162 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009163 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009164
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009165public:
9166 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9167 const QualType& TargetType, bool Complain)
9168 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9169 Complain(Complain), Context(S.getASTContext()),
9170 TargetTypeIsNonStaticMemberFunction(
9171 !!TargetType->getAs<MemberPointerType>()),
9172 FoundNonTemplateFunction(false),
9173 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9174 OvlExpr(OvlExprInfo.Expression)
9175 {
9176 ExtractUnqualifiedFunctionTypeFromTargetType();
9177
9178 if (!TargetFunctionType->isFunctionType()) {
9179 if (OvlExpr->hasExplicitTemplateArgs()) {
9180 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009181 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009182 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009183
9184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9185 if (!Method->isStatic()) {
9186 // If the target type is a non-function type and the function
9187 // found is a non-static member function, pretend as if that was
9188 // the target, it's the only possible type to end up with.
9189 TargetTypeIsNonStaticMemberFunction = true;
9190
9191 // And skip adding the function if its not in the proper form.
9192 // We'll diagnose this due to an empty set of functions.
9193 if (!OvlExprInfo.HasFormOfMemberPointer)
9194 return;
9195 }
9196 }
9197
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009198 Matches.push_back(std::make_pair(dap,Fn));
9199 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009200 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009201 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009202 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009203
9204 if (OvlExpr->hasExplicitTemplateArgs())
9205 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009206
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009207 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9208 // C++ [over.over]p4:
9209 // If more than one function is selected, [...]
9210 if (Matches.size() > 1) {
9211 if (FoundNonTemplateFunction)
9212 EliminateAllTemplateMatches();
9213 else
9214 EliminateAllExceptMostSpecializedTemplate();
9215 }
9216 }
9217 }
9218
9219private:
9220 bool isTargetTypeAFunction() const {
9221 return TargetFunctionType->isFunctionType();
9222 }
9223
9224 // [ToType] [Return]
9225
9226 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9227 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9228 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9229 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9230 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9231 }
9232
9233 // return true if any matching specializations were found
9234 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9235 const DeclAccessPair& CurAccessFunPair) {
9236 if (CXXMethodDecl *Method
9237 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9238 // Skip non-static function templates when converting to pointer, and
9239 // static when converting to member pointer.
9240 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9241 return false;
9242 }
9243 else if (TargetTypeIsNonStaticMemberFunction)
9244 return false;
9245
9246 // C++ [over.over]p2:
9247 // If the name is a function template, template argument deduction is
9248 // done (14.8.2.2), and if the argument deduction succeeds, the
9249 // resulting template argument list is used to generate a single
9250 // function template specialization, which is added to the set of
9251 // overloaded functions considered.
9252 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009253 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009254 if (Sema::TemplateDeductionResult Result
9255 = S.DeduceTemplateArguments(FunctionTemplate,
9256 &OvlExplicitTemplateArgs,
9257 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009258 Info, /*InOverloadResolution=*/true)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009259 // FIXME: make a note of the failed deduction for diagnostics.
9260 (void)Result;
9261 return false;
9262 }
9263
Douglas Gregor092140a2013-04-17 08:45:07 +00009264 // Template argument deduction ensures that we have an exact match or
9265 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009266 // This function template specicalization works.
9267 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009268 assert(S.isSameOrCompatibleFunctionType(
9269 Context.getCanonicalType(Specialization->getType()),
9270 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009271 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9272 return true;
9273 }
9274
9275 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9276 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009277 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009278 // Skip non-static functions when converting to pointer, and static
9279 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009280 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9281 return false;
9282 }
9283 else if (TargetTypeIsNonStaticMemberFunction)
9284 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009285
Chandler Carruthbd647292009-12-29 06:17:27 +00009286 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009287 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009288 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9289 if (S.CheckCUDATarget(Caller, FunDecl))
9290 return false;
9291
Richard Smith60e141e2013-05-04 07:00:32 +00009292 // If any candidate has a placeholder return type, trigger its deduction
9293 // now.
9294 if (S.getLangOpts().CPlusPlus1y &&
9295 FunDecl->getResultType()->isUndeducedType() &&
9296 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9297 return false;
9298
Douglas Gregor43c79c22009-12-09 00:47:37 +00009299 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009300 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9301 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009302 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9303 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009304 Matches.push_back(std::make_pair(CurAccessFunPair,
9305 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009306 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009307 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009308 }
Mike Stump1eb44332009-09-09 15:08:12 +00009309 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009310
9311 return false;
9312 }
9313
9314 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9315 bool Ret = false;
9316
9317 // If the overload expression doesn't have the form of a pointer to
9318 // member, don't try to convert it to a pointer-to-member type.
9319 if (IsInvalidFormOfPointerToMemberFunction())
9320 return false;
9321
9322 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9323 E = OvlExpr->decls_end();
9324 I != E; ++I) {
9325 // Look through any using declarations to find the underlying function.
9326 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9327
9328 // C++ [over.over]p3:
9329 // Non-member functions and static member functions match
9330 // targets of type "pointer-to-function" or "reference-to-function."
9331 // Nonstatic member functions match targets of
9332 // type "pointer-to-member-function."
9333 // Note that according to DR 247, the containing class does not matter.
9334 if (FunctionTemplateDecl *FunctionTemplate
9335 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9336 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9337 Ret = true;
9338 }
9339 // If we have explicit template arguments supplied, skip non-templates.
9340 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9341 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9342 Ret = true;
9343 }
9344 assert(Ret || Matches.empty());
9345 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009346 }
9347
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009348 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009349 // [...] and any given function template specialization F1 is
9350 // eliminated if the set contains a second function template
9351 // specialization whose function template is more specialized
9352 // than the function template of F1 according to the partial
9353 // ordering rules of 14.5.5.2.
9354
9355 // The algorithm specified above is quadratic. We instead use a
9356 // two-pass algorithm (similar to the one used to identify the
9357 // best viable function in an overload set) that identifies the
9358 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009359
9360 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9361 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9362 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009363
John McCallc373d482010-01-27 01:50:18 +00009364 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009365 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9366 TPOC_Other, 0, SourceExpr->getLocStart(),
9367 S.PDiag(),
9368 S.PDiag(diag::err_addr_ovl_ambiguous)
9369 << Matches[0].second->getDeclName(),
9370 S.PDiag(diag::note_ovl_candidate)
9371 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009372 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009373
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009374 if (Result != MatchesCopy.end()) {
9375 // Make it the first and only element
9376 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9377 Matches[0].second = cast<FunctionDecl>(*Result);
9378 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009379 }
9380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009381
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009382 void EliminateAllTemplateMatches() {
9383 // [...] any function template specializations in the set are
9384 // eliminated if the set also contains a non-template function, [...]
9385 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9386 if (Matches[I].second->getPrimaryTemplate() == 0)
9387 ++I;
9388 else {
9389 Matches[I] = Matches[--N];
9390 Matches.set_size(N);
9391 }
9392 }
9393 }
9394
9395public:
9396 void ComplainNoMatchesFound() const {
9397 assert(Matches.empty());
9398 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9399 << OvlExpr->getName() << TargetFunctionType
9400 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009401 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009402 }
9403
9404 bool IsInvalidFormOfPointerToMemberFunction() const {
9405 return TargetTypeIsNonStaticMemberFunction &&
9406 !OvlExprInfo.HasFormOfMemberPointer;
9407 }
9408
9409 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9410 // TODO: Should we condition this on whether any functions might
9411 // have matched, or is it more appropriate to do that in callers?
9412 // TODO: a fixit wouldn't hurt.
9413 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9414 << TargetType << OvlExpr->getSourceRange();
9415 }
9416
9417 void ComplainOfInvalidConversion() const {
9418 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9419 << OvlExpr->getName() << TargetType;
9420 }
9421
9422 void ComplainMultipleMatchesFound() const {
9423 assert(Matches.size() > 1);
9424 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9425 << OvlExpr->getName()
9426 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009427 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009428 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009429
9430 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9431
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009432 int getNumMatches() const { return Matches.size(); }
9433
9434 FunctionDecl* getMatchingFunctionDecl() const {
9435 if (Matches.size() != 1) return 0;
9436 return Matches[0].second;
9437 }
9438
9439 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9440 if (Matches.size() != 1) return 0;
9441 return &Matches[0].first;
9442 }
9443};
9444
9445/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9446/// an overloaded function (C++ [over.over]), where @p From is an
9447/// expression with overloaded function type and @p ToType is the type
9448/// we're trying to resolve to. For example:
9449///
9450/// @code
9451/// int f(double);
9452/// int f(int);
9453///
9454/// int (*pfd)(double) = f; // selects f(double)
9455/// @endcode
9456///
9457/// This routine returns the resulting FunctionDecl if it could be
9458/// resolved, and NULL otherwise. When @p Complain is true, this
9459/// routine will emit diagnostics if there is an error.
9460FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009461Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9462 QualType TargetType,
9463 bool Complain,
9464 DeclAccessPair &FoundResult,
9465 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009466 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009467
9468 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9469 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009470 int NumMatches = Resolver.getNumMatches();
9471 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009472 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009473 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9474 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9475 else
9476 Resolver.ComplainNoMatchesFound();
9477 }
9478 else if (NumMatches > 1 && Complain)
9479 Resolver.ComplainMultipleMatchesFound();
9480 else if (NumMatches == 1) {
9481 Fn = Resolver.getMatchingFunctionDecl();
9482 assert(Fn);
9483 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009484 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009485 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009486 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009487
9488 if (pHadMultipleCandidates)
9489 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009490 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009491}
9492
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009493/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009494/// resolve that overloaded function expression down to a single function.
9495///
9496/// This routine can only resolve template-ids that refer to a single function
9497/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009498/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009499/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009500FunctionDecl *
9501Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9502 bool Complain,
9503 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009504 // C++ [over.over]p1:
9505 // [...] [Note: any redundant set of parentheses surrounding the
9506 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009507 // C++ [over.over]p1:
9508 // [...] The overloaded function name can be preceded by the &
9509 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009510
Douglas Gregor4b52e252009-12-21 23:17:24 +00009511 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009512 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009513 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009514
9515 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009516 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009517
Douglas Gregor4b52e252009-12-21 23:17:24 +00009518 // Look through all of the overloaded functions, searching for one
9519 // whose type matches exactly.
9520 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009521 for (UnresolvedSetIterator I = ovl->decls_begin(),
9522 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009523 // C++0x [temp.arg.explicit]p3:
9524 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009525 // where deduction is not done, if a template argument list is
9526 // specified and it, along with any default template arguments,
9527 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009528 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009529 FunctionTemplateDecl *FunctionTemplate
9530 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009531
Douglas Gregor4b52e252009-12-21 23:17:24 +00009532 // C++ [over.over]p2:
9533 // If the name is a function template, template argument deduction is
9534 // done (14.8.2.2), and if the argument deduction succeeds, the
9535 // resulting template argument list is used to generate a single
9536 // function template specialization, which is added to the set of
9537 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009538 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009539 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009540 if (TemplateDeductionResult Result
9541 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009542 Specialization, Info,
9543 /*InOverloadResolution=*/true)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009544 // FIXME: make a note of the failed deduction for diagnostics.
9545 (void)Result;
9546 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009547 }
9548
John McCall864c0412011-04-26 20:42:42 +00009549 assert(Specialization && "no specialization and no error?");
9550
Douglas Gregor4b52e252009-12-21 23:17:24 +00009551 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009552 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009553 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009554 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9555 << ovl->getName();
9556 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009557 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009558 return 0;
John McCall864c0412011-04-26 20:42:42 +00009559 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009560
John McCall864c0412011-04-26 20:42:42 +00009561 Matched = Specialization;
9562 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009563 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009564
Richard Smith60e141e2013-05-04 07:00:32 +00009565 if (Matched && getLangOpts().CPlusPlus1y &&
9566 Matched->getResultType()->isUndeducedType() &&
9567 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9568 return 0;
9569
Douglas Gregor4b52e252009-12-21 23:17:24 +00009570 return Matched;
9571}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009572
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009573
9574
9575
John McCall6dbba4f2011-10-11 23:14:30 +00009576// Resolve and fix an overloaded expression that can be resolved
9577// because it identifies a single function template specialization.
9578//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009579// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009580//
9581// Return true if it was logically possible to so resolve the
9582// expression, regardless of whether or not it succeeded. Always
9583// returns true if 'complain' is set.
9584bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9585 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9586 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009587 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009588 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009589 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009590
John McCall6dbba4f2011-10-11 23:14:30 +00009591 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009592
John McCall864c0412011-04-26 20:42:42 +00009593 DeclAccessPair found;
9594 ExprResult SingleFunctionExpression;
9595 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9596 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009597 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009598 SrcExpr = ExprError();
9599 return true;
9600 }
John McCall864c0412011-04-26 20:42:42 +00009601
9602 // It is only correct to resolve to an instance method if we're
9603 // resolving a form that's permitted to be a pointer to member.
9604 // Otherwise we'll end up making a bound member expression, which
9605 // is illegal in all the contexts we resolve like this.
9606 if (!ovl.HasFormOfMemberPointer &&
9607 isa<CXXMethodDecl>(fn) &&
9608 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009609 if (!complain) return false;
9610
9611 Diag(ovl.Expression->getExprLoc(),
9612 diag::err_bound_member_function)
9613 << 0 << ovl.Expression->getSourceRange();
9614
9615 // TODO: I believe we only end up here if there's a mix of
9616 // static and non-static candidates (otherwise the expression
9617 // would have 'bound member' type, not 'overload' type).
9618 // Ideally we would note which candidate was chosen and why
9619 // the static candidates were rejected.
9620 SrcExpr = ExprError();
9621 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009622 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009623
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009624 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009625 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009626 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009627
9628 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009629 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009630 SingleFunctionExpression =
9631 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009632 if (SingleFunctionExpression.isInvalid()) {
9633 SrcExpr = ExprError();
9634 return true;
9635 }
9636 }
John McCall864c0412011-04-26 20:42:42 +00009637 }
9638
9639 if (!SingleFunctionExpression.isUsable()) {
9640 if (complain) {
9641 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9642 << ovl.Expression->getName()
9643 << DestTypeForComplaining
9644 << OpRangeForComplaining
9645 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009646 NoteAllOverloadCandidates(SrcExpr.get());
9647
9648 SrcExpr = ExprError();
9649 return true;
9650 }
9651
9652 return false;
John McCall864c0412011-04-26 20:42:42 +00009653 }
9654
John McCall6dbba4f2011-10-11 23:14:30 +00009655 SrcExpr = SingleFunctionExpression;
9656 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009657}
9658
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009659/// \brief Add a single candidate to the overload set.
9660static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009661 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009662 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009663 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009664 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009665 bool PartialOverloading,
9666 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009667 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009668 if (isa<UsingShadowDecl>(Callee))
9669 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9670
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009671 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009672 if (ExplicitTemplateArgs) {
9673 assert(!KnownValid && "Explicit template arguments?");
9674 return;
9675 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009676 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9677 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009678 return;
John McCallba135432009-11-21 08:51:07 +00009679 }
9680
9681 if (FunctionTemplateDecl *FuncTemplate
9682 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009683 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009684 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009685 return;
9686 }
9687
Richard Smith2ced0442011-06-26 22:19:54 +00009688 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009689}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009690
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009691/// \brief Add the overload candidates named by callee and/or found by argument
9692/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009693void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009694 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009695 OverloadCandidateSet &CandidateSet,
9696 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009697
9698#ifndef NDEBUG
9699 // Verify that ArgumentDependentLookup is consistent with the rules
9700 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009701 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009702 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9703 // and let Y be the lookup set produced by argument dependent
9704 // lookup (defined as follows). If X contains
9705 //
9706 // -- a declaration of a class member, or
9707 //
9708 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009709 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009710 //
9711 // -- a declaration that is neither a function or a function
9712 // template
9713 //
9714 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009715
John McCall3b4294e2009-12-16 12:17:52 +00009716 if (ULE->requiresADL()) {
9717 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9718 E = ULE->decls_end(); I != E; ++I) {
9719 assert(!(*I)->getDeclContext()->isRecord());
9720 assert(isa<UsingShadowDecl>(*I) ||
9721 !(*I)->getDeclContext()->isFunctionOrMethod());
9722 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009723 }
9724 }
9725#endif
9726
John McCall3b4294e2009-12-16 12:17:52 +00009727 // It would be nice to avoid this copy.
9728 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009729 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009730 if (ULE->hasExplicitTemplateArgs()) {
9731 ULE->copyTemplateArgumentsInto(TABuffer);
9732 ExplicitTemplateArgs = &TABuffer;
9733 }
9734
9735 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9736 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009737 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9738 CandidateSet, PartialOverloading,
9739 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009740
John McCall3b4294e2009-12-16 12:17:52 +00009741 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009742 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009743 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009744 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009745 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009746}
John McCall578b69b2009-12-16 08:11:27 +00009747
Richard Smithd3ff3252013-06-12 22:56:54 +00009748/// Determine whether a declaration with the specified name could be moved into
9749/// a different namespace.
9750static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9751 switch (Name.getCXXOverloadedOperator()) {
9752 case OO_New: case OO_Array_New:
9753 case OO_Delete: case OO_Array_Delete:
9754 return false;
9755
9756 default:
9757 return true;
9758 }
9759}
9760
Richard Smithf50e88a2011-06-05 22:42:48 +00009761/// Attempt to recover from an ill-formed use of a non-dependent name in a
9762/// template, where the non-dependent name was declared after the template
9763/// was defined. This is common in code written for a compilers which do not
9764/// correctly implement two-stage name lookup.
9765///
9766/// Returns true if a viable candidate was found and a diagnostic was issued.
9767static bool
9768DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9769 const CXXScopeSpec &SS, LookupResult &R,
9770 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009771 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009772 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9773 return false;
9774
9775 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009776 if (DC->isTransparentContext())
9777 continue;
9778
Richard Smithf50e88a2011-06-05 22:42:48 +00009779 SemaRef.LookupQualifiedName(R, DC);
9780
9781 if (!R.empty()) {
9782 R.suppressDiagnostics();
9783
9784 if (isa<CXXRecordDecl>(DC)) {
9785 // Don't diagnose names we find in classes; we get much better
9786 // diagnostics for these from DiagnoseEmptyLookup.
9787 R.clear();
9788 return false;
9789 }
9790
9791 OverloadCandidateSet Candidates(FnLoc);
9792 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9793 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009794 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009795 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009796
9797 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009798 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009799 // No viable functions. Don't bother the user with notes for functions
9800 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009801 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009802 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009803 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009804
9805 // Find the namespaces where ADL would have looked, and suggest
9806 // declaring the function there instead.
9807 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9808 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009809 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009810 AssociatedNamespaces,
9811 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009812 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009813 if (canBeDeclaredInNamespace(R.getLookupName())) {
9814 DeclContext *Std = SemaRef.getStdNamespace();
9815 for (Sema::AssociatedNamespaceSet::iterator
9816 it = AssociatedNamespaces.begin(),
9817 end = AssociatedNamespaces.end(); it != end; ++it) {
9818 // Never suggest declaring a function within namespace 'std'.
9819 if (Std && Std->Encloses(*it))
9820 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009821
Richard Smithd3ff3252013-06-12 22:56:54 +00009822 // Never suggest declaring a function within a namespace with a
9823 // reserved name, like __gnu_cxx.
9824 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9825 if (NS &&
9826 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9827 continue;
9828
9829 SuggestedNamespaces.insert(*it);
9830 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009831 }
9832
9833 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9834 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009835 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009836 SemaRef.Diag(Best->Function->getLocation(),
9837 diag::note_not_found_by_two_phase_lookup)
9838 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009839 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009840 SemaRef.Diag(Best->Function->getLocation(),
9841 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009842 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009843 } else {
9844 // FIXME: It would be useful to list the associated namespaces here,
9845 // but the diagnostics infrastructure doesn't provide a way to produce
9846 // a localized representation of a list of items.
9847 SemaRef.Diag(Best->Function->getLocation(),
9848 diag::note_not_found_by_two_phase_lookup)
9849 << R.getLookupName() << 2;
9850 }
9851
9852 // Try to recover by calling this function.
9853 return true;
9854 }
9855
9856 R.clear();
9857 }
9858
9859 return false;
9860}
9861
9862/// Attempt to recover from ill-formed use of a non-dependent operator in a
9863/// template, where the non-dependent operator was declared after the template
9864/// was defined.
9865///
9866/// Returns true if a viable candidate was found and a diagnostic was issued.
9867static bool
9868DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9869 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009870 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009871 DeclarationName OpName =
9872 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9873 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9874 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009875 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009876}
9877
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009878namespace {
9879// Callback to limit the allowed keywords and to only accept typo corrections
9880// that are keywords or whose decls refer to functions (or template functions)
9881// that accept the given number of arguments.
9882class RecoveryCallCCC : public CorrectionCandidateCallback {
9883 public:
9884 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9885 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009886 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009887 WantRemainingKeywords = false;
9888 }
9889
9890 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9891 if (!candidate.getCorrectionDecl())
9892 return candidate.isKeyword();
9893
9894 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9895 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9896 FunctionDecl *FD = 0;
9897 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9898 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9899 FD = FTD->getTemplatedDecl();
9900 if (!HasExplicitTemplateArgs && !FD) {
9901 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9902 // If the Decl is neither a function nor a template function,
9903 // determine if it is a pointer or reference to a function. If so,
9904 // check against the number of arguments expected for the pointee.
9905 QualType ValType = cast<ValueDecl>(ND)->getType();
9906 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9907 ValType = ValType->getPointeeType();
9908 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9909 if (FPT->getNumArgs() == NumArgs)
9910 return true;
9911 }
9912 }
9913 if (FD && FD->getNumParams() >= NumArgs &&
9914 FD->getMinRequiredArguments() <= NumArgs)
9915 return true;
9916 }
9917 return false;
9918 }
9919
9920 private:
9921 unsigned NumArgs;
9922 bool HasExplicitTemplateArgs;
9923};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009924
9925// Callback that effectively disabled typo correction
9926class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9927 public:
9928 NoTypoCorrectionCCC() {
9929 WantTypeSpecifiers = false;
9930 WantExpressionKeywords = false;
9931 WantCXXNamedCasts = false;
9932 WantRemainingKeywords = false;
9933 }
9934
9935 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9936 return false;
9937 }
9938};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009939
9940class BuildRecoveryCallExprRAII {
9941 Sema &SemaRef;
9942public:
9943 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9944 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9945 SemaRef.IsBuildingRecoveryCallExpr = true;
9946 }
9947
9948 ~BuildRecoveryCallExprRAII() {
9949 SemaRef.IsBuildingRecoveryCallExpr = false;
9950 }
9951};
9952
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009953}
9954
John McCall578b69b2009-12-16 08:11:27 +00009955/// Attempts to recover from a call where no functions were found.
9956///
9957/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009958static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009959BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009960 UnresolvedLookupExpr *ULE,
9961 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009962 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009963 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009964 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009965 // Do not try to recover if it is already building a recovery call.
9966 // This stops infinite loops for template instantiations like
9967 //
9968 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9969 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9970 //
9971 if (SemaRef.IsBuildingRecoveryCallExpr)
9972 return ExprError();
9973 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009974
9975 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009976 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009977 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009978
John McCall3b4294e2009-12-16 12:17:52 +00009979 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009980 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009981 if (ULE->hasExplicitTemplateArgs()) {
9982 ULE->copyTemplateArgumentsInto(TABuffer);
9983 ExplicitTemplateArgs = &TABuffer;
9984 }
9985
John McCall578b69b2009-12-16 08:11:27 +00009986 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9987 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009988 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009989 NoTypoCorrectionCCC RejectAll;
9990 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9991 (CorrectionCandidateCallback*)&Validator :
9992 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009993 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009994 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009995 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009996 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009997 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009998 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009999
John McCall3b4294e2009-12-16 12:17:52 +000010000 assert(!R.empty() && "lookup results empty despite recovery");
10001
10002 // Build an implicit member call if appropriate. Just drop the
10003 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010004 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010005 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010006 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10007 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010008 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010009 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010010 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010011 else
10012 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10013
10014 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010015 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010016
10017 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010018 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010019 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010020 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010021 MultiExprArg(Args.data(), Args.size()),
10022 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010023}
Douglas Gregord7a95972010-06-08 17:35:15 +000010024
Sam Panzere1715b62012-08-21 00:52:01 +000010025/// \brief Constructs and populates an OverloadedCandidateSet from
10026/// the given function.
10027/// \returns true when an the ExprResult output parameter has been set.
10028bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10029 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010030 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010031 SourceLocation RParenLoc,
10032 OverloadCandidateSet *CandidateSet,
10033 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010034#ifndef NDEBUG
10035 if (ULE->requiresADL()) {
10036 // To do ADL, we must have found an unqualified name.
10037 assert(!ULE->getQualifier() && "qualified name with ADL");
10038
10039 // We don't perform ADL for implicit declarations of builtins.
10040 // Verify that this was correctly set up.
10041 FunctionDecl *F;
10042 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10043 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10044 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010045 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010046
John McCall3b4294e2009-12-16 12:17:52 +000010047 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010048 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010049 }
John McCall3b4294e2009-12-16 12:17:52 +000010050#endif
10051
John McCall5acb0c92011-10-17 18:40:02 +000010052 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010053 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010054 *Result = ExprError();
10055 return true;
10056 }
Douglas Gregor17330012009-02-04 15:01:18 +000010057
John McCall3b4294e2009-12-16 12:17:52 +000010058 // Add the functions denoted by the callee to the set of candidate
10059 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010060 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010061
10062 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010063 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10064 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010065 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010066 // In Microsoft mode, if we are inside a template class member function then
10067 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010068 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010069 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010070 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010071 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010072 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010073 Context.DependentTy, VK_RValue,
10074 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010075 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010076 *Result = Owned(CE);
10077 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010078 }
Sam Panzere1715b62012-08-21 00:52:01 +000010079 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010080 }
John McCall578b69b2009-12-16 08:11:27 +000010081
John McCall5acb0c92011-10-17 18:40:02 +000010082 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010083 return false;
10084}
John McCall5acb0c92011-10-17 18:40:02 +000010085
Sam Panzere1715b62012-08-21 00:52:01 +000010086/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10087/// the completed call expression. If overload resolution fails, emits
10088/// diagnostics and returns ExprError()
10089static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10090 UnresolvedLookupExpr *ULE,
10091 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010092 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010093 SourceLocation RParenLoc,
10094 Expr *ExecConfig,
10095 OverloadCandidateSet *CandidateSet,
10096 OverloadCandidateSet::iterator *Best,
10097 OverloadingResult OverloadResult,
10098 bool AllowTypoCorrection) {
10099 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010100 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010101 RParenLoc, /*EmptyLookup=*/true,
10102 AllowTypoCorrection);
10103
10104 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010105 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010106 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010107 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010108 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10109 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010110 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010111 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10112 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010113 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010114
Richard Smithf50e88a2011-06-05 22:42:48 +000010115 case OR_No_Viable_Function: {
10116 // Try to recover by looking for viable functions which the user might
10117 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010118 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010119 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010120 /*EmptyLookup=*/false,
10121 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010122 if (!Recovery.isInvalid())
10123 return Recovery;
10124
Sam Panzere1715b62012-08-21 00:52:01 +000010125 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010126 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010127 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010128 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010129 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010130 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010131
10132 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010133 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010134 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010135 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010136 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010137
Sam Panzere1715b62012-08-21 00:52:01 +000010138 case OR_Deleted: {
10139 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10140 << (*Best)->Function->isDeleted()
10141 << ULE->getName()
10142 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10143 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010144 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010145
Sam Panzere1715b62012-08-21 00:52:01 +000010146 // We emitted an error for the unvailable/deleted function call but keep
10147 // the call in the AST.
10148 FunctionDecl *FDecl = (*Best)->Function;
10149 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010150 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10151 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010152 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010153 }
10154
Douglas Gregorff331c12010-07-25 18:17:45 +000010155 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010156 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010157}
10158
Sam Panzere1715b62012-08-21 00:52:01 +000010159/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10160/// (which eventually refers to the declaration Func) and the call
10161/// arguments Args/NumArgs, attempt to resolve the function call down
10162/// to a specific function. If overload resolution succeeds, returns
10163/// the call expression produced by overload resolution.
10164/// Otherwise, emits diagnostics and returns ExprError.
10165ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10166 UnresolvedLookupExpr *ULE,
10167 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010168 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010169 SourceLocation RParenLoc,
10170 Expr *ExecConfig,
10171 bool AllowTypoCorrection) {
10172 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10173 ExprResult result;
10174
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010175 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10176 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010177 return result;
10178
10179 OverloadCandidateSet::iterator Best;
10180 OverloadingResult OverloadResult =
10181 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10182
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010183 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010184 RParenLoc, ExecConfig, &CandidateSet,
10185 &Best, OverloadResult,
10186 AllowTypoCorrection);
10187}
10188
John McCall6e266892010-01-26 03:27:55 +000010189static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010190 return Functions.size() > 1 ||
10191 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10192}
10193
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010194/// \brief Create a unary operation that may resolve to an overloaded
10195/// operator.
10196///
10197/// \param OpLoc The location of the operator itself (e.g., '*').
10198///
10199/// \param OpcIn The UnaryOperator::Opcode that describes this
10200/// operator.
10201///
James Dennett40ae6662012-06-22 08:52:37 +000010202/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010203/// considered by overload resolution. The caller needs to build this
10204/// set based on the context using, e.g.,
10205/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10206/// set should not contain any member functions; those will be added
10207/// by CreateOverloadedUnaryOp().
10208///
James Dennett8da16872012-06-22 10:32:46 +000010209/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010210ExprResult
John McCall6e266892010-01-26 03:27:55 +000010211Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10212 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010213 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010214 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010215
10216 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10217 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10218 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010219 // TODO: provide better source location info.
10220 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010221
John McCall5acb0c92011-10-17 18:40:02 +000010222 if (checkPlaceholderForOverload(*this, Input))
10223 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010224
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010225 Expr *Args[2] = { Input, 0 };
10226 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010227
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010228 // For post-increment and post-decrement, add the implicit '0' as
10229 // the second argument, so that we know this is a post-increment or
10230 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010231 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010232 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010233 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10234 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010235 NumArgs = 2;
10236 }
10237
Richard Smith958ba642013-05-05 15:51:06 +000010238 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10239
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010240 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010241 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010242 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010243 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010244 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010245 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010246 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010247
John McCallc373d482010-01-27 01:50:18 +000010248 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010249 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010250 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010251 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010252 /*ADL*/ true, IsOverloaded(Fns),
10253 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010254 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010255 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010256 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010257 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010258 }
10259
10260 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010261 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010262
10263 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010264 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010265
10266 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010267 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010268
John McCall6e266892010-01-26 03:27:55 +000010269 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010270 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10271 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010272 CandidateSet);
10273
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010274 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010275 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010276
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010277 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10278
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010279 // Perform overload resolution.
10280 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010281 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010282 case OR_Success: {
10283 // We found a built-in operator or an overloaded operator.
10284 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010285
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010286 if (FnDecl) {
10287 // We matched an overloaded operator. Build a call to that
10288 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010289
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010290 // Convert the arguments.
10291 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010292 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010293
John Wiegley429bb272011-04-08 18:41:53 +000010294 ExprResult InputRes =
10295 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10296 Best->FoundDecl, Method);
10297 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010298 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010299 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010300 } else {
10301 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010302 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010303 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010304 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010305 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010306 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010307 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010308 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010309 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010310 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010311 }
10312
John McCallf89e55a2010-11-18 06:31:45 +000010313 // Determine the result type.
10314 QualType ResultTy = FnDecl->getResultType();
10315 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10316 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010317
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010318 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010319 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010320 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010321 if (FnExpr.isInvalid())
10322 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010323
Eli Friedman4c3b8962009-11-18 03:58:17 +000010324 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010325 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010326 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010327 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010328
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010329 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010330 FnDecl))
10331 return ExprError();
10332
John McCall9ae2f072010-08-23 23:25:46 +000010333 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010334 } else {
10335 // We matched a built-in operator. Convert the arguments, then
10336 // break out so that we will build the appropriate built-in
10337 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010338 ExprResult InputRes =
10339 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10340 Best->Conversions[0], AA_Passing);
10341 if (InputRes.isInvalid())
10342 return ExprError();
10343 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010344 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010345 }
John Wiegley429bb272011-04-08 18:41:53 +000010346 }
10347
10348 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010349 // This is an erroneous use of an operator which can be overloaded by
10350 // a non-member function. Check for non-member operators which were
10351 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010352 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010353 // FIXME: Recover by calling the found function.
10354 return ExprError();
10355
John Wiegley429bb272011-04-08 18:41:53 +000010356 // No viable function; fall through to handling this as a
10357 // built-in operator, which will produce an error message for us.
10358 break;
10359
10360 case OR_Ambiguous:
10361 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10362 << UnaryOperator::getOpcodeStr(Opc)
10363 << Input->getType()
10364 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010365 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010366 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10367 return ExprError();
10368
10369 case OR_Deleted:
10370 Diag(OpLoc, diag::err_ovl_deleted_oper)
10371 << Best->Function->isDeleted()
10372 << UnaryOperator::getOpcodeStr(Opc)
10373 << getDeletedOrUnavailableSuffix(Best->Function)
10374 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010375 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010376 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010377 return ExprError();
10378 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010379
10380 // Either we found no viable overloaded operator or we matched a
10381 // built-in operator. In either case, fall through to trying to
10382 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010383 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010384}
10385
Douglas Gregor063daf62009-03-13 18:40:31 +000010386/// \brief Create a binary operation that may resolve to an overloaded
10387/// operator.
10388///
10389/// \param OpLoc The location of the operator itself (e.g., '+').
10390///
10391/// \param OpcIn The BinaryOperator::Opcode that describes this
10392/// operator.
10393///
James Dennett40ae6662012-06-22 08:52:37 +000010394/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010395/// considered by overload resolution. The caller needs to build this
10396/// set based on the context using, e.g.,
10397/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10398/// set should not contain any member functions; those will be added
10399/// by CreateOverloadedBinOp().
10400///
10401/// \param LHS Left-hand argument.
10402/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010403ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010404Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010405 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010406 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010407 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010408 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010409 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010410
10411 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10412 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10413 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10414
10415 // If either side is type-dependent, create an appropriate dependent
10416 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010417 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010418 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010419 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010420 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010421 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010422 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010423 Context.DependentTy,
10424 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010425 OpLoc,
10426 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010427
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010428 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10429 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010430 VK_LValue,
10431 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010432 Context.DependentTy,
10433 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010434 OpLoc,
10435 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010436 }
John McCall6e266892010-01-26 03:27:55 +000010437
10438 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010439 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010440 // TODO: provide better source location info in DNLoc component.
10441 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010442 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010443 = UnresolvedLookupExpr::Create(Context, NamingClass,
10444 NestedNameSpecifierLoc(), OpNameInfo,
10445 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010446 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010447 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10448 Context.DependentTy, VK_RValue,
10449 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010450 }
10451
John McCall5acb0c92011-10-17 18:40:02 +000010452 // Always do placeholder-like conversions on the RHS.
10453 if (checkPlaceholderForOverload(*this, Args[1]))
10454 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010455
John McCall3c3b7f92011-10-25 17:37:35 +000010456 // Do placeholder-like conversion on the LHS; note that we should
10457 // not get here with a PseudoObject LHS.
10458 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010459 if (checkPlaceholderForOverload(*this, Args[0]))
10460 return ExprError();
10461
Sebastian Redl275c2b42009-11-18 23:10:33 +000010462 // If this is the assignment operator, we only perform overload resolution
10463 // if the left-hand side is a class or enumeration type. This is actually
10464 // a hack. The standard requires that we do overload resolution between the
10465 // various built-in candidates, but as DR507 points out, this can lead to
10466 // problems. So we do it this way, which pretty much follows what GCC does.
10467 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010468 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010469 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010470
John McCall0e800c92010-12-04 08:14:53 +000010471 // If this is the .* operator, which is not overloadable, just
10472 // create a built-in binary operator.
10473 if (Opc == BO_PtrMemD)
10474 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10475
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010476 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010477 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010478
10479 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010480 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010481
10482 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010483 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010484
John McCall6e266892010-01-26 03:27:55 +000010485 // Add candidates from ADL.
10486 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010487 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010488 /*ExplicitTemplateArgs*/ 0,
10489 CandidateSet);
10490
Douglas Gregor063daf62009-03-13 18:40:31 +000010491 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010492 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010493
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010494 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10495
Douglas Gregor063daf62009-03-13 18:40:31 +000010496 // Perform overload resolution.
10497 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010498 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010499 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010500 // We found a built-in operator or an overloaded operator.
10501 FunctionDecl *FnDecl = Best->Function;
10502
10503 if (FnDecl) {
10504 // We matched an overloaded operator. Build a call to that
10505 // operator.
10506
10507 // Convert the arguments.
10508 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010509 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010510 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010511
Chandler Carruth6df868e2010-12-12 08:17:55 +000010512 ExprResult Arg1 =
10513 PerformCopyInitialization(
10514 InitializedEntity::InitializeParameter(Context,
10515 FnDecl->getParamDecl(0)),
10516 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010517 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010518 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010519
John Wiegley429bb272011-04-08 18:41:53 +000010520 ExprResult Arg0 =
10521 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10522 Best->FoundDecl, Method);
10523 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010524 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010525 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010526 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010527 } else {
10528 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010529 ExprResult Arg0 = PerformCopyInitialization(
10530 InitializedEntity::InitializeParameter(Context,
10531 FnDecl->getParamDecl(0)),
10532 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010533 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010534 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010535
Chandler Carruth6df868e2010-12-12 08:17:55 +000010536 ExprResult Arg1 =
10537 PerformCopyInitialization(
10538 InitializedEntity::InitializeParameter(Context,
10539 FnDecl->getParamDecl(1)),
10540 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010541 if (Arg1.isInvalid())
10542 return ExprError();
10543 Args[0] = LHS = Arg0.takeAs<Expr>();
10544 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010545 }
10546
John McCallf89e55a2010-11-18 06:31:45 +000010547 // Determine the result type.
10548 QualType ResultTy = FnDecl->getResultType();
10549 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10550 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010551
10552 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010553 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010554 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010555 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010556 if (FnExpr.isInvalid())
10557 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010558
John McCall9ae2f072010-08-23 23:25:46 +000010559 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010560 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010561 Args, ResultTy, VK, OpLoc,
10562 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010563
10564 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010565 FnDecl))
10566 return ExprError();
10567
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010568 ArrayRef<const Expr *> ArgsArray(Args, 2);
10569 // Cut off the implicit 'this'.
10570 if (isa<CXXMethodDecl>(FnDecl))
10571 ArgsArray = ArgsArray.slice(1);
10572 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10573 TheCall->getSourceRange(), VariadicDoesNotApply);
10574
John McCall9ae2f072010-08-23 23:25:46 +000010575 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010576 } else {
10577 // We matched a built-in operator. Convert the arguments, then
10578 // break out so that we will build the appropriate built-in
10579 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010580 ExprResult ArgsRes0 =
10581 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10582 Best->Conversions[0], AA_Passing);
10583 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010584 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010585 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010586
John Wiegley429bb272011-04-08 18:41:53 +000010587 ExprResult ArgsRes1 =
10588 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10589 Best->Conversions[1], AA_Passing);
10590 if (ArgsRes1.isInvalid())
10591 return ExprError();
10592 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010593 break;
10594 }
10595 }
10596
Douglas Gregor33074752009-09-30 21:46:01 +000010597 case OR_No_Viable_Function: {
10598 // C++ [over.match.oper]p9:
10599 // If the operator is the operator , [...] and there are no
10600 // viable functions, then the operator is assumed to be the
10601 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010602 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010603 break;
10604
Chandler Carruth6df868e2010-12-12 08:17:55 +000010605 // For class as left operand for assignment or compound assigment
10606 // operator do not fall through to handling in built-in, but report that
10607 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010608 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010609 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010610 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010611 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10612 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010613 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010614 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010615 // This is an erroneous use of an operator which can be overloaded by
10616 // a non-member function. Check for non-member operators which were
10617 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010618 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010619 // FIXME: Recover by calling the found function.
10620 return ExprError();
10621
Douglas Gregor33074752009-09-30 21:46:01 +000010622 // No viable function; try to create a built-in operation, which will
10623 // produce an error. Then, show the non-viable candidates.
10624 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010625 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010626 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010627 "C++ binary operator overloading is missing candidates!");
10628 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010629 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010630 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010631 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010632 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010633
10634 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010635 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010636 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010637 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010638 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010639 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010640 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010641 return ExprError();
10642
10643 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010644 if (isImplicitlyDeleted(Best->Function)) {
10645 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10646 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010647 << Context.getRecordType(Method->getParent())
10648 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010649
Richard Smith0f46e642012-12-28 12:23:24 +000010650 // The user probably meant to call this special member. Just
10651 // explain why it's deleted.
10652 NoteDeletedFunction(Method);
10653 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010654 } else {
10655 Diag(OpLoc, diag::err_ovl_deleted_oper)
10656 << Best->Function->isDeleted()
10657 << BinaryOperator::getOpcodeStr(Opc)
10658 << getDeletedOrUnavailableSuffix(Best->Function)
10659 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10660 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010661 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010662 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010663 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010664 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010665
Douglas Gregor33074752009-09-30 21:46:01 +000010666 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010667 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010668}
10669
John McCall60d7b3a2010-08-24 06:29:42 +000010670ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010671Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10672 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010673 Expr *Base, Expr *Idx) {
10674 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010675 DeclarationName OpName =
10676 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10677
10678 // If either side is type-dependent, create an appropriate dependent
10679 // expression.
10680 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10681
John McCallc373d482010-01-27 01:50:18 +000010682 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010683 // CHECKME: no 'operator' keyword?
10684 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10685 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010686 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010687 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010688 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010689 /*ADL*/ true, /*Overloaded*/ false,
10690 UnresolvedSetIterator(),
10691 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010692 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010693
Sebastian Redlf322ed62009-10-29 20:17:01 +000010694 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010695 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010696 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010697 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010698 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010699 }
10700
John McCall5acb0c92011-10-17 18:40:02 +000010701 // Handle placeholders on both operands.
10702 if (checkPlaceholderForOverload(*this, Args[0]))
10703 return ExprError();
10704 if (checkPlaceholderForOverload(*this, Args[1]))
10705 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010706
Sebastian Redlf322ed62009-10-29 20:17:01 +000010707 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010708 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010709
10710 // Subscript can only be overloaded as a member function.
10711
10712 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010713 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010714
10715 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010716 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010717
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010718 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10719
Sebastian Redlf322ed62009-10-29 20:17:01 +000010720 // Perform overload resolution.
10721 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010722 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010723 case OR_Success: {
10724 // We found a built-in operator or an overloaded operator.
10725 FunctionDecl *FnDecl = Best->Function;
10726
10727 if (FnDecl) {
10728 // We matched an overloaded operator. Build a call to that
10729 // operator.
10730
John McCall9aa472c2010-03-19 07:35:19 +000010731 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010732
Sebastian Redlf322ed62009-10-29 20:17:01 +000010733 // Convert the arguments.
10734 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010735 ExprResult Arg0 =
10736 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10737 Best->FoundDecl, Method);
10738 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010739 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010740 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010741
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010742 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010743 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010744 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010745 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010746 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010747 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010748 Owned(Args[1]));
10749 if (InputInit.isInvalid())
10750 return ExprError();
10751
10752 Args[1] = InputInit.takeAs<Expr>();
10753
Sebastian Redlf322ed62009-10-29 20:17:01 +000010754 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010755 QualType ResultTy = FnDecl->getResultType();
10756 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10757 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010758
10759 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010760 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10761 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010762 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010763 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010764 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010765 OpLocInfo.getLoc(),
10766 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010767 if (FnExpr.isInvalid())
10768 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010769
John McCall9ae2f072010-08-23 23:25:46 +000010770 CXXOperatorCallExpr *TheCall =
10771 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010772 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010773 ResultTy, VK, RLoc,
10774 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010775
John McCall9ae2f072010-08-23 23:25:46 +000010776 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010777 FnDecl))
10778 return ExprError();
10779
John McCall9ae2f072010-08-23 23:25:46 +000010780 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010781 } else {
10782 // We matched a built-in operator. Convert the arguments, then
10783 // break out so that we will build the appropriate built-in
10784 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010785 ExprResult ArgsRes0 =
10786 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10787 Best->Conversions[0], AA_Passing);
10788 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010789 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010790 Args[0] = ArgsRes0.take();
10791
10792 ExprResult ArgsRes1 =
10793 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10794 Best->Conversions[1], AA_Passing);
10795 if (ArgsRes1.isInvalid())
10796 return ExprError();
10797 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010798
10799 break;
10800 }
10801 }
10802
10803 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010804 if (CandidateSet.empty())
10805 Diag(LLoc, diag::err_ovl_no_oper)
10806 << Args[0]->getType() << /*subscript*/ 0
10807 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10808 else
10809 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10810 << Args[0]->getType()
10811 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010812 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010813 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010814 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010815 }
10816
10817 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010818 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010819 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010820 << Args[0]->getType() << Args[1]->getType()
10821 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010822 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010823 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010824 return ExprError();
10825
10826 case OR_Deleted:
10827 Diag(LLoc, diag::err_ovl_deleted_oper)
10828 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010829 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010830 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010831 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010832 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010833 return ExprError();
10834 }
10835
10836 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010837 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010838}
10839
Douglas Gregor88a35142008-12-22 05:46:06 +000010840/// BuildCallToMemberFunction - Build a call to a member
10841/// function. MemExpr is the expression that refers to the member
10842/// function (and includes the object parameter), Args/NumArgs are the
10843/// arguments to the function call (not including the object
10844/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010845/// expression refers to a non-static member function or an overloaded
10846/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010847ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010848Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010849 SourceLocation LParenLoc,
10850 MultiExprArg Args,
10851 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010852 assert(MemExprE->getType() == Context.BoundMemberTy ||
10853 MemExprE->getType() == Context.OverloadTy);
10854
Douglas Gregor88a35142008-12-22 05:46:06 +000010855 // Dig out the member expression. This holds both the object
10856 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010857 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010858
John McCall864c0412011-04-26 20:42:42 +000010859 // Determine whether this is a call to a pointer-to-member function.
10860 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10861 assert(op->getType() == Context.BoundMemberTy);
10862 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10863
10864 QualType fnType =
10865 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10866
10867 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10868 QualType resultType = proto->getCallResultType(Context);
10869 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10870
10871 // Check that the object type isn't more qualified than the
10872 // member function we're calling.
10873 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10874
10875 QualType objectType = op->getLHS()->getType();
10876 if (op->getOpcode() == BO_PtrMemI)
10877 objectType = objectType->castAs<PointerType>()->getPointeeType();
10878 Qualifiers objectQuals = objectType.getQualifiers();
10879
10880 Qualifiers difference = objectQuals - funcQuals;
10881 difference.removeObjCGCAttr();
10882 difference.removeAddressSpace();
10883 if (difference) {
10884 std::string qualsString = difference.getAsString();
10885 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10886 << fnType.getUnqualifiedType()
10887 << qualsString
10888 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10889 }
10890
10891 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010892 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000010893 resultType, valueKind, RParenLoc);
10894
10895 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010896 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010897 call, 0))
10898 return ExprError();
10899
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010900 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000010901 return ExprError();
10902
Richard Trieue2a90b82013-06-22 02:30:38 +000010903 if (CheckOtherCall(call, proto))
10904 return ExprError();
10905
John McCall864c0412011-04-26 20:42:42 +000010906 return MaybeBindToTemporary(call);
10907 }
10908
John McCall5acb0c92011-10-17 18:40:02 +000010909 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010910 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000010911 return ExprError();
10912
John McCall129e2df2009-11-30 22:42:35 +000010913 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010914 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010915 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010916 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010917 if (isa<MemberExpr>(NakedMemExpr)) {
10918 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010919 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010920 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010921 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010922 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010923 } else {
10924 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010925 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010926
John McCall701c89e2009-12-03 04:06:58 +000010927 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010928 Expr::Classification ObjectClassification
10929 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10930 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010931
Douglas Gregor88a35142008-12-22 05:46:06 +000010932 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010933 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010934
John McCallaa81e162009-12-01 22:10:20 +000010935 // FIXME: avoid copy.
10936 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10937 if (UnresExpr->hasExplicitTemplateArgs()) {
10938 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10939 TemplateArgs = &TemplateArgsBuffer;
10940 }
10941
John McCall129e2df2009-11-30 22:42:35 +000010942 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10943 E = UnresExpr->decls_end(); I != E; ++I) {
10944
John McCall701c89e2009-12-03 04:06:58 +000010945 NamedDecl *Func = *I;
10946 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10947 if (isa<UsingShadowDecl>(Func))
10948 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10949
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010950
Francois Pichetdbee3412011-01-18 05:04:39 +000010951 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010952 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010953 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010954 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010955 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010956 // If explicit template arguments were provided, we can't call a
10957 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010958 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010959 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010960
John McCall9aa472c2010-03-19 07:35:19 +000010961 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010962 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010963 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010964 } else {
John McCall129e2df2009-11-30 22:42:35 +000010965 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010966 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010967 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010968 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010969 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010970 }
Douglas Gregordec06662009-08-21 18:42:58 +000010971 }
Mike Stump1eb44332009-09-09 15:08:12 +000010972
John McCall129e2df2009-11-30 22:42:35 +000010973 DeclarationName DeclName = UnresExpr->getMemberName();
10974
John McCall5acb0c92011-10-17 18:40:02 +000010975 UnbridgedCasts.restore();
10976
Douglas Gregor88a35142008-12-22 05:46:06 +000010977 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010978 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010979 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010980 case OR_Success:
10981 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010982 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010983 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010984 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
10985 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000010986 // If FoundDecl is different from Method (such as if one is a template
10987 // and the other a specialization), make sure DiagnoseUseOfDecl is
10988 // called on both.
10989 // FIXME: This would be more comprehensively addressed by modifying
10990 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
10991 // being used.
10992 if (Method != FoundDecl.getDecl() &&
10993 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
10994 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010995 break;
10996
10997 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010998 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010999 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011000 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011001 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011002 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011003 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011004
11005 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011006 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011007 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011008 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011009 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011010 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011011
11012 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011013 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011014 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011015 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011016 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011017 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011018 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011019 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011020 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011021 }
11022
John McCall6bb80172010-03-30 21:47:33 +000011023 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011024
John McCallaa81e162009-12-01 22:10:20 +000011025 // If overload resolution picked a static member, build a
11026 // non-member call based on that function.
11027 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011028 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11029 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011030 }
11031
John McCall129e2df2009-11-30 22:42:35 +000011032 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011033 }
11034
John McCallf89e55a2010-11-18 06:31:45 +000011035 QualType ResultType = Method->getResultType();
11036 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11037 ResultType = ResultType.getNonLValueExprType(Context);
11038
Douglas Gregor88a35142008-12-22 05:46:06 +000011039 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011040 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011041 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011042 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011043
Anders Carlssoneed3e692009-10-10 00:06:20 +000011044 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011045 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011046 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011047 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011048
Douglas Gregor88a35142008-12-22 05:46:06 +000011049 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011050 // We only need to do this if there was actually an overload; otherwise
11051 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011052 if (!Method->isStatic()) {
11053 ExprResult ObjectArg =
11054 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11055 FoundDecl, Method);
11056 if (ObjectArg.isInvalid())
11057 return ExprError();
11058 MemExpr->setBase(ObjectArg.take());
11059 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011060
11061 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011062 const FunctionProtoType *Proto =
11063 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011064 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011065 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011066 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011067
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011068 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011069
Richard Smith831421f2012-06-25 20:30:08 +000011070 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011071 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011072
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011073 if ((isa<CXXConstructorDecl>(CurContext) ||
11074 isa<CXXDestructorDecl>(CurContext)) &&
11075 TheCall->getMethodDecl()->isPure()) {
11076 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11077
Chandler Carruthae198062011-06-27 08:31:58 +000011078 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011079 Diag(MemExpr->getLocStart(),
11080 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11081 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11082 << MD->getParent()->getDeclName();
11083
11084 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011085 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011086 }
John McCall9ae2f072010-08-23 23:25:46 +000011087 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011088}
11089
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011090/// BuildCallToObjectOfClassType - Build a call to an object of class
11091/// type (C++ [over.call.object]), which can end up invoking an
11092/// overloaded function call operator (@c operator()) or performing a
11093/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011094ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011095Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011096 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011097 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011098 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011099 if (checkPlaceholderForOverload(*this, Obj))
11100 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011101 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011102
11103 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011104 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011105 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011106
John Wiegley429bb272011-04-08 18:41:53 +000011107 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11108 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011109
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011110 // C++ [over.call.object]p1:
11111 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011112 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011113 // candidate functions includes at least the function call
11114 // operators of T. The function call operators of T are obtained by
11115 // ordinary lookup of the name operator() in the context of
11116 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011117 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011118 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011119
John Wiegley429bb272011-04-08 18:41:53 +000011120 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011121 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011122 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011123
John McCalla24dc2e2009-11-17 02:14:36 +000011124 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11125 LookupQualifiedName(R, Record->getDecl());
11126 R.suppressDiagnostics();
11127
Douglas Gregor593564b2009-11-15 07:48:03 +000011128 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011129 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011130 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011131 Object.get()->Classify(Context),
11132 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011133 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011134 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011135
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011136 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011137 // In addition, for each (non-explicit in C++0x) conversion function
11138 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011139 //
11140 // operator conversion-type-id () cv-qualifier;
11141 //
11142 // where cv-qualifier is the same cv-qualification as, or a
11143 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011144 // denotes the type "pointer to function of (P1,...,Pn) returning
11145 // R", or the type "reference to pointer to function of
11146 // (P1,...,Pn) returning R", or the type "reference to function
11147 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011148 // is also considered as a candidate function. Similarly,
11149 // surrogate call functions are added to the set of candidate
11150 // functions for each conversion function declared in an
11151 // accessible base class provided the function is not hidden
11152 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011153 std::pair<CXXRecordDecl::conversion_iterator,
11154 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011155 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011156 for (CXXRecordDecl::conversion_iterator
11157 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011158 NamedDecl *D = *I;
11159 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11160 if (isa<UsingShadowDecl>(D))
11161 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011162
Douglas Gregor4a27d702009-10-21 06:18:39 +000011163 // Skip over templated conversion functions; they aren't
11164 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011165 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011166 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011167
John McCall701c89e2009-12-03 04:06:58 +000011168 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011169 if (!Conv->isExplicit()) {
11170 // Strip the reference type (if any) and then the pointer type (if
11171 // any) to get down to what might be a function type.
11172 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11173 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11174 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011175
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011176 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11177 {
11178 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011179 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011180 }
11181 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011182 }
Mike Stump1eb44332009-09-09 15:08:12 +000011183
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011184 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11185
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011186 // Perform overload resolution.
11187 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011188 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011189 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011190 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011191 // Overload resolution succeeded; we'll build the appropriate call
11192 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011193 break;
11194
11195 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011196 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011197 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011198 << Object.get()->getType() << /*call*/ 1
11199 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011200 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011201 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011202 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011203 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011204 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011205 break;
11206
11207 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011208 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011209 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011210 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011211 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011212 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011213
11214 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011215 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011216 diag::err_ovl_deleted_object_call)
11217 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011218 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011219 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011220 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011221 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011222 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011223 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011224
Douglas Gregorff331c12010-07-25 18:17:45 +000011225 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011226 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011227
John McCall5acb0c92011-10-17 18:40:02 +000011228 UnbridgedCasts.restore();
11229
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011230 if (Best->Function == 0) {
11231 // Since there is no function declaration, this is one of the
11232 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011233 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011234 = cast<CXXConversionDecl>(
11235 Best->Conversions[0].UserDefined.ConversionFunction);
11236
John Wiegley429bb272011-04-08 18:41:53 +000011237 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011238 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11239 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011240 assert(Conv == Best->FoundDecl.getDecl() &&
11241 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011242 // We selected one of the surrogate functions that converts the
11243 // object parameter to a function pointer. Perform the conversion
11244 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011245
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011246 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011247 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011248 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11249 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011250 if (Call.isInvalid())
11251 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011252 // Record usage of conversion in an implicit cast.
11253 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11254 CK_UserDefinedConversion,
11255 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011256
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011257 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011258 }
11259
John Wiegley429bb272011-04-08 18:41:53 +000011260 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011261
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011262 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11263 // that calls this method, using Object for the implicit object
11264 // parameter and passing along the remaining arguments.
11265 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011266
11267 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011268 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011269 return ExprError();
11270
Chandler Carruth6df868e2010-12-12 08:17:55 +000011271 const FunctionProtoType *Proto =
11272 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011273
11274 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011275 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011276
11277 // Build the full argument list for the method call (the
11278 // implicit object parameter is placed at the beginning of the
11279 // list).
11280 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011281 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011282 NumArgsToCheck = NumArgsInProto;
11283 MethodArgs = new Expr*[NumArgsInProto + 1];
11284 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011285 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011286 }
John Wiegley429bb272011-04-08 18:41:53 +000011287 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011288 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011289 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011290
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011291 DeclarationNameInfo OpLocInfo(
11292 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11293 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011294 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011295 HadMultipleCandidates,
11296 OpLocInfo.getLoc(),
11297 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011298 if (NewFn.isInvalid())
11299 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011300
11301 // Once we've built TheCall, all of the expressions are properly
11302 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011303 QualType ResultTy = Method->getResultType();
11304 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11305 ResultTy = ResultTy.getNonLValueExprType(Context);
11306
John McCall9ae2f072010-08-23 23:25:46 +000011307 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011308 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011309 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011310 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011311 delete [] MethodArgs;
11312
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011313 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011314 Method))
11315 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011316
Douglas Gregor518fda12009-01-13 05:10:00 +000011317 // We may have default arguments. If so, we need to allocate more
11318 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011319 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011320 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011321 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011322 NumArgsToCheck = NumArgsInProto;
11323
Chris Lattner312531a2009-04-12 08:11:20 +000011324 bool IsError = false;
11325
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011326 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011327 ExprResult ObjRes =
11328 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11329 Best->FoundDecl, Method);
11330 if (ObjRes.isInvalid())
11331 IsError = true;
11332 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011333 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011334 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011335
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011336 // Check the argument types.
11337 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011338 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011339 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011340 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011341
Douglas Gregor518fda12009-01-13 05:10:00 +000011342 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011343
John McCall60d7b3a2010-08-24 06:29:42 +000011344 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011345 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011346 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011347 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011348 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011349
Anders Carlsson3faa4862010-01-29 18:43:53 +000011350 IsError |= InputInit.isInvalid();
11351 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011352 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011353 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011354 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11355 if (DefArg.isInvalid()) {
11356 IsError = true;
11357 break;
11358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011359
Douglas Gregord47c47d2009-11-09 19:27:57 +000011360 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011361 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011362
11363 TheCall->setArg(i + 1, Arg);
11364 }
11365
11366 // If this is a variadic call, handle args passed through "...".
11367 if (Proto->isVariadic()) {
11368 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011369 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011370 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11371 IsError |= Arg.isInvalid();
11372 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011373 }
11374 }
11375
Chris Lattner312531a2009-04-12 08:11:20 +000011376 if (IsError) return true;
11377
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011378 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011379
Richard Smith831421f2012-06-25 20:30:08 +000011380 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011381 return true;
11382
John McCall182f7092010-08-24 06:09:16 +000011383 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011384}
11385
Douglas Gregor8ba10742008-11-20 16:27:02 +000011386/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011387/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011388/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011389ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011390Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011391 assert(Base->getType()->isRecordType() &&
11392 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011393
John McCall5acb0c92011-10-17 18:40:02 +000011394 if (checkPlaceholderForOverload(*this, Base))
11395 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011396
John McCall5769d612010-02-08 23:07:23 +000011397 SourceLocation Loc = Base->getExprLoc();
11398
Douglas Gregor8ba10742008-11-20 16:27:02 +000011399 // C++ [over.ref]p1:
11400 //
11401 // [...] An expression x->m is interpreted as (x.operator->())->m
11402 // for a class object x of type T if T::operator->() exists and if
11403 // the operator is selected as the best match function by the
11404 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011405 DeclarationName OpName =
11406 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011407 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011408 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011409
John McCall5769d612010-02-08 23:07:23 +000011410 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011411 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011412 return ExprError();
11413
John McCalla24dc2e2009-11-17 02:14:36 +000011414 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11415 LookupQualifiedName(R, BaseRecord->getDecl());
11416 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011417
11418 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011419 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011420 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011421 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011422 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011423
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011424 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11425
Douglas Gregor8ba10742008-11-20 16:27:02 +000011426 // Perform overload resolution.
11427 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011428 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011429 case OR_Success:
11430 // Overload resolution succeeded; we'll build the call below.
11431 break;
11432
11433 case OR_No_Viable_Function:
11434 if (CandidateSet.empty())
11435 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011436 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011437 else
11438 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011439 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011440 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011441 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011442
11443 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011444 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11445 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011446 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011447 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011448
11449 case OR_Deleted:
11450 Diag(OpLoc, diag::err_ovl_deleted_oper)
11451 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011452 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011453 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011454 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011455 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011456 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011457 }
11458
John McCall9aa472c2010-03-19 07:35:19 +000011459 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11460
Douglas Gregor8ba10742008-11-20 16:27:02 +000011461 // Convert the object parameter.
11462 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011463 ExprResult BaseResult =
11464 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11465 Best->FoundDecl, Method);
11466 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011467 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011468 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011469
Douglas Gregor8ba10742008-11-20 16:27:02 +000011470 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011471 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011472 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011473 if (FnExpr.isInvalid())
11474 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011475
John McCallf89e55a2010-11-18 06:31:45 +000011476 QualType ResultTy = Method->getResultType();
11477 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11478 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011479 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011480 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011481 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011482
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011483 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011484 Method))
11485 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011486
11487 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011488}
11489
Richard Smith36f5cfe2012-03-09 08:00:36 +000011490/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11491/// a literal operator described by the provided lookup results.
11492ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11493 DeclarationNameInfo &SuffixInfo,
11494 ArrayRef<Expr*> Args,
11495 SourceLocation LitEndLoc,
11496 TemplateArgumentListInfo *TemplateArgs) {
11497 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011498
Richard Smith36f5cfe2012-03-09 08:00:36 +000011499 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11500 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11501 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011502
Richard Smith36f5cfe2012-03-09 08:00:36 +000011503 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11504
Richard Smith36f5cfe2012-03-09 08:00:36 +000011505 // Perform overload resolution. This will usually be trivial, but might need
11506 // to perform substitutions for a literal operator template.
11507 OverloadCandidateSet::iterator Best;
11508 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11509 case OR_Success:
11510 case OR_Deleted:
11511 break;
11512
11513 case OR_No_Viable_Function:
11514 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11515 << R.getLookupName();
11516 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11517 return ExprError();
11518
11519 case OR_Ambiguous:
11520 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11521 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11522 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011523 }
11524
Richard Smith36f5cfe2012-03-09 08:00:36 +000011525 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011526 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11527 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011528 SuffixInfo.getLoc(),
11529 SuffixInfo.getInfo());
11530 if (Fn.isInvalid())
11531 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011532
11533 // Check the argument types. This should almost always be a no-op, except
11534 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011535 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011536 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011537 ExprResult InputInit = PerformCopyInitialization(
11538 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11539 SourceLocation(), Args[ArgIdx]);
11540 if (InputInit.isInvalid())
11541 return true;
11542 ConvArgs[ArgIdx] = InputInit.take();
11543 }
11544
Richard Smith9fcce652012-03-07 08:35:16 +000011545 QualType ResultTy = FD->getResultType();
11546 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11547 ResultTy = ResultTy.getNonLValueExprType(Context);
11548
Richard Smith9fcce652012-03-07 08:35:16 +000011549 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011550 new (Context) UserDefinedLiteral(Context, Fn.take(),
11551 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011552 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11553
11554 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11555 return ExprError();
11556
Richard Smith831421f2012-06-25 20:30:08 +000011557 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011558 return ExprError();
11559
11560 return MaybeBindToTemporary(UDL);
11561}
11562
Sam Panzere1715b62012-08-21 00:52:01 +000011563/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11564/// given LookupResult is non-empty, it is assumed to describe a member which
11565/// will be invoked. Otherwise, the function will be found via argument
11566/// dependent lookup.
11567/// CallExpr is set to a valid expression and FRS_Success returned on success,
11568/// otherwise CallExpr is set to ExprError() and some non-success value
11569/// is returned.
11570Sema::ForRangeStatus
11571Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11572 SourceLocation RangeLoc, VarDecl *Decl,
11573 BeginEndFunction BEF,
11574 const DeclarationNameInfo &NameInfo,
11575 LookupResult &MemberLookup,
11576 OverloadCandidateSet *CandidateSet,
11577 Expr *Range, ExprResult *CallExpr) {
11578 CandidateSet->clear();
11579 if (!MemberLookup.empty()) {
11580 ExprResult MemberRef =
11581 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11582 /*IsPtr=*/false, CXXScopeSpec(),
11583 /*TemplateKWLoc=*/SourceLocation(),
11584 /*FirstQualifierInScope=*/0,
11585 MemberLookup,
11586 /*TemplateArgs=*/0);
11587 if (MemberRef.isInvalid()) {
11588 *CallExpr = ExprError();
11589 Diag(Range->getLocStart(), diag::note_in_for_range)
11590 << RangeLoc << BEF << Range->getType();
11591 return FRS_DiagnosticIssued;
11592 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011593 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011594 if (CallExpr->isInvalid()) {
11595 *CallExpr = ExprError();
11596 Diag(Range->getLocStart(), diag::note_in_for_range)
11597 << RangeLoc << BEF << Range->getType();
11598 return FRS_DiagnosticIssued;
11599 }
11600 } else {
11601 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011602 UnresolvedLookupExpr *Fn =
11603 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11604 NestedNameSpecifierLoc(), NameInfo,
11605 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011606 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011607
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011608 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011609 CandidateSet, CallExpr);
11610 if (CandidateSet->empty() || CandidateSetError) {
11611 *CallExpr = ExprError();
11612 return FRS_NoViableFunction;
11613 }
11614 OverloadCandidateSet::iterator Best;
11615 OverloadingResult OverloadResult =
11616 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11617
11618 if (OverloadResult == OR_No_Viable_Function) {
11619 *CallExpr = ExprError();
11620 return FRS_NoViableFunction;
11621 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011622 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011623 Loc, 0, CandidateSet, &Best,
11624 OverloadResult,
11625 /*AllowTypoCorrection=*/false);
11626 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11627 *CallExpr = ExprError();
11628 Diag(Range->getLocStart(), diag::note_in_for_range)
11629 << RangeLoc << BEF << Range->getType();
11630 return FRS_DiagnosticIssued;
11631 }
11632 }
11633 return FRS_Success;
11634}
11635
11636
Douglas Gregor904eed32008-11-10 20:40:00 +000011637/// FixOverloadedFunctionReference - E is an expression that refers to
11638/// a C++ overloaded function (possibly with some parentheses and
11639/// perhaps a '&' around it). We have resolved the overloaded function
11640/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011641/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011642Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011643 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011644 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011645 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11646 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011647 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011648 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011649
Douglas Gregor699ee522009-11-20 19:42:02 +000011650 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011651 }
11652
Douglas Gregor699ee522009-11-20 19:42:02 +000011653 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011654 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11655 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011656 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011657 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011658 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011659 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011660 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011661 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011662
11663 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011664 ICE->getCastKind(),
11665 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011666 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011667 }
11668
Douglas Gregor699ee522009-11-20 19:42:02 +000011669 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011670 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011671 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011672 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11673 if (Method->isStatic()) {
11674 // Do nothing: static member functions aren't any different
11675 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011676 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011677 // Fix the sub expression, which really has to be an
11678 // UnresolvedLookupExpr holding an overloaded member function
11679 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011680 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11681 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011682 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011683 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011684
John McCallba135432009-11-21 08:51:07 +000011685 assert(isa<DeclRefExpr>(SubExpr)
11686 && "fixed to something other than a decl ref");
11687 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11688 && "fixed to a member ref with no nested name qualifier");
11689
11690 // We have taken the address of a pointer to member
11691 // function. Perform the computation here so that we get the
11692 // appropriate pointer to member type.
11693 QualType ClassType
11694 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11695 QualType MemPtrType
11696 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11697
John McCallf89e55a2010-11-18 06:31:45 +000011698 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11699 VK_RValue, OK_Ordinary,
11700 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011701 }
11702 }
John McCall6bb80172010-03-30 21:47:33 +000011703 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11704 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011705 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011706 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011707
John McCall2de56d12010-08-25 11:45:40 +000011708 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011709 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011710 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011711 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011712 }
John McCallba135432009-11-21 08:51:07 +000011713
11714 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011715 // FIXME: avoid copy.
11716 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011717 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011718 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11719 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011720 }
11721
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011722 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11723 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011724 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011725 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011726 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011727 ULE->getNameLoc(),
11728 Fn->getType(),
11729 VK_LValue,
11730 Found.getDecl(),
11731 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011732 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011733 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11734 return DRE;
John McCallba135432009-11-21 08:51:07 +000011735 }
11736
John McCall129e2df2009-11-30 22:42:35 +000011737 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011738 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011739 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11740 if (MemExpr->hasExplicitTemplateArgs()) {
11741 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11742 TemplateArgs = &TemplateArgsBuffer;
11743 }
John McCalld5532b62009-11-23 01:53:49 +000011744
John McCallaa81e162009-12-01 22:10:20 +000011745 Expr *Base;
11746
John McCallf89e55a2010-11-18 06:31:45 +000011747 // If we're filling in a static method where we used to have an
11748 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011749 if (MemExpr->isImplicitAccess()) {
11750 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011751 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11752 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011753 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011754 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011755 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011756 MemExpr->getMemberLoc(),
11757 Fn->getType(),
11758 VK_LValue,
11759 Found.getDecl(),
11760 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011761 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011762 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11763 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011764 } else {
11765 SourceLocation Loc = MemExpr->getMemberLoc();
11766 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011767 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011768 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011769 Base = new (Context) CXXThisExpr(Loc,
11770 MemExpr->getBaseType(),
11771 /*isImplicit=*/true);
11772 }
John McCallaa81e162009-12-01 22:10:20 +000011773 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011774 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011775
John McCallf5307512011-04-27 00:36:17 +000011776 ExprValueKind valueKind;
11777 QualType type;
11778 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11779 valueKind = VK_LValue;
11780 type = Fn->getType();
11781 } else {
11782 valueKind = VK_RValue;
11783 type = Context.BoundMemberTy;
11784 }
11785
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011786 MemberExpr *ME = MemberExpr::Create(Context, Base,
11787 MemExpr->isArrow(),
11788 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011789 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011790 Fn,
11791 Found,
11792 MemExpr->getMemberNameInfo(),
11793 TemplateArgs,
11794 type, valueKind, OK_Ordinary);
11795 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011796 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011797 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011798 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011799
John McCall3fa5cae2010-10-26 07:05:15 +000011800 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011801}
11802
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011803ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011804 DeclAccessPair Found,
11805 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011806 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011807}
11808
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011809} // end namespace clang